Path: blob/master/src/java.base/share/classes/com/sun/crypto/provider/DESedeWrapCipher.java
41161 views
/*1* Copyright (c) 2004, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package com.sun.crypto.provider;2627import java.security.*;28import java.security.spec.*;29import java.util.Arrays;30import javax.crypto.*;31import javax.crypto.spec.*;3233/**34* This class implements the CMS DESede KeyWrap algorithm as defined35* in <a href=http://www.w3.org/TR/xmlenc-core/#sec-Alg-SymmetricKeyWrap></a>36* "XML Encryption Syntax and Processing" section 5.6.237* "CMS Triple DES Key Wrap".38* Note: only <code>CBC</code> mode and <code>NoPadding</code> padding39* scheme can be used for this algorithm.40*41* @author Valerie Peng42*43*44* @see DESedeCipher45*/46public final class DESedeWrapCipher extends CipherSpi {4748private static final byte[] IV2 = {49(byte) 0x4a, (byte) 0xdd, (byte) 0xa2, (byte) 0x2c,50(byte) 0x79, (byte) 0xe8, (byte) 0x21, (byte) 0x0551};5253private static final int CHECKSUM_LEN = 8;54private static final int IV_LEN = 8;5556/*57* internal cipher object which does the real work.58*/59private FeedbackCipher cipher;6061/*62* iv for (re-)initializing the internal cipher object.63*/64private byte[] iv = null;6566/*67* key for re-initializing the internal cipher object.68*/69private Key cipherKey = null;7071/*72* are we encrypting or decrypting?73*/74private boolean decrypting = false;7576/**77* Creates an instance of CMS DESede KeyWrap cipher with default78* mode, i.e. "CBC" and padding scheme, i.e. "NoPadding".79*/80public DESedeWrapCipher() {81cipher = new CipherBlockChaining(new DESedeCrypt());82}8384/**85* Sets the mode of this cipher. Only "CBC" mode is accepted for this86* cipher.87*88* @param mode the cipher mode.89*90* @exception NoSuchAlgorithmException if the requested cipher mode91* is not "CBC".92*/93protected void engineSetMode(String mode)94throws NoSuchAlgorithmException {95if (!mode.equalsIgnoreCase("CBC")) {96throw new NoSuchAlgorithmException(mode + " cannot be used");97}98}99100/**101* Sets the padding mechanism of this cipher. Only "NoPadding" schmem102* is accepted for this cipher.103*104* @param padding the padding mechanism.105*106* @exception NoSuchPaddingException if the requested padding mechanism107* is not "NoPadding".108*/109protected void engineSetPadding(String padding)110throws NoSuchPaddingException {111if (!padding.equalsIgnoreCase("NoPadding")) {112throw new NoSuchPaddingException(padding + " cannot be used");113}114}115116/**117* Returns the block size (in bytes), i.e. 8 bytes.118*119* @return the block size (in bytes), i.e. 8 bytes.120*/121protected int engineGetBlockSize() {122return DESConstants.DES_BLOCK_SIZE;123}124125/**126* Returns the length in bytes that an output buffer would need to be127* given the input length <code>inputLen</code> (in bytes).128*129* <p>The actual output length of the next <code>update</code> or130* <code>doFinal</code> call may be smaller than the length returned131* by this method.132*133* @param inputLen the input length (in bytes).134*135* @return the required output buffer size (in bytes).136*/137protected int engineGetOutputSize(int inputLen) {138// can only return an upper-limit if not initialized yet.139int result = 0;140if (decrypting) {141result = inputLen - 16; // CHECKSUM_LEN + IV_LEN;142} else {143result = Math.addExact(inputLen, 16);144}145return (result < 0? 0:result);146}147148/**149* Returns the initialization vector (IV) in a new buffer.150*151* @return the initialization vector, or null if the underlying152* algorithm does not use an IV, or if the IV has not yet153* been set.154*/155protected byte[] engineGetIV() {156return (iv == null) ? null : iv.clone();157}158159/**160* Initializes this cipher with a key and a source of randomness.161*162* <p>The cipher only supports the following two operation modes:163* {@code Cipher.WRAP_MODE}, and {@code Cipher.UNWRAP_MODE}.164* <p>For modes other than the above two, UnsupportedOperationException165* will be thrown.166* <p>If this cipher requires an initialization vector (IV), it will get167* it from <code>random</code>.168*169* @param opmode the operation mode of this cipher. Only170* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>) are accepted.171* @param key the secret key.172* @param random the source of randomness.173*174* @exception InvalidKeyException if the given key is inappropriate175* or if parameters are required but not supplied.176*/177protected void engineInit(int opmode, Key key, SecureRandom random)178throws InvalidKeyException {179try {180engineInit(opmode, key, (AlgorithmParameterSpec) null, random);181} catch (InvalidAlgorithmParameterException iape) {182// should never happen183InvalidKeyException ike =184new InvalidKeyException("Parameters required");185ike.initCause(iape);186throw ike;187}188}189190/**191* Initializes this cipher with a key, a set of algorithm parameters,192* and a source of randomness.193*194* <p>The cipher only supports the following two operation modes:195* {@code Cipher.WRAP_MODE}, and {@code Cipher.UNWRAP_MODE}.196* <p>For modes other than the above two, UnsupportedOperationException197* will be thrown.198* <p>If this cipher requires an initialization vector (IV), it will get199* it from <code>random</code>.200*201* @param opmode the operation mode of this cipher. Only202* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>) are accepted.203* @param key the secret key.204* @param params the algorithm parameters.205* @param random the source of randomness.206*207* @exception InvalidKeyException if the given key is inappropriate.208* @exception InvalidAlgorithmParameterException if the given algorithm209* parameters are inappropriate for this cipher.210*/211protected void engineInit(int opmode, Key key,212AlgorithmParameterSpec params,213SecureRandom random)214throws InvalidKeyException, InvalidAlgorithmParameterException {215byte[] currIv = null;216if (opmode == Cipher.WRAP_MODE) {217decrypting = false;218if (params == null) {219iv = new byte[IV_LEN];220if (random == null) {221random = SunJCE.getRandom();222}223random.nextBytes(iv);224}225else if (params instanceof IvParameterSpec) {226iv = ((IvParameterSpec) params).getIV();227} else {228throw new InvalidAlgorithmParameterException229("Wrong parameter type: IV expected");230}231currIv = iv;232} else if (opmode == Cipher.UNWRAP_MODE) {233if (params != null) {234throw new InvalidAlgorithmParameterException235("No parameter accepted for unwrapping keys");236}237iv = null;238decrypting = true;239currIv = IV2;240} else {241throw new UnsupportedOperationException("This cipher can " +242"only be used for key wrapping and unwrapping");243}244byte[] encoded = key.getEncoded();245try {246cipher.init(decrypting, key.getAlgorithm(), encoded, currIv);247} finally {248if (encoded != null) {249Arrays.fill(encoded, (byte) 0);250}251}252cipherKey = key;253}254255/**256* Initializes this cipher with a key, a set of algorithm parameters,257* and a source of randomness.258*259* <p>The cipher only supports the following two operation modes:260* {@code Cipher.WRAP_MODE}, and {@code Cipher.UNWRAP_MODE}.261* <p>For modes other than the above two, UnsupportedOperationException262* will be thrown.263* <p>If this cipher requires an initialization vector (IV), it will get264* it from <code>random</code>.265*266* @param opmode the operation mode of this cipher. Only267* <code>WRAP_MODE</code> or <code>UNWRAP_MODE</code>) are accepted.268* @param key the secret key.269* @param params the algorithm parameters.270* @param random the source of randomness.271*272* @exception InvalidKeyException if the given key is inappropriate.273* @exception InvalidAlgorithmParameterException if the given algorithm274* parameters are inappropriate for this cipher.275*/276protected void engineInit(int opmode, Key key,277AlgorithmParameters params,278SecureRandom random)279throws InvalidKeyException, InvalidAlgorithmParameterException {280IvParameterSpec ivSpec = null;281if (params != null) {282try {283DESedeParameters paramsEng = new DESedeParameters();284paramsEng.engineInit(params.getEncoded());285ivSpec = paramsEng.engineGetParameterSpec(IvParameterSpec.class);286} catch (Exception ex) {287InvalidAlgorithmParameterException iape =288new InvalidAlgorithmParameterException289("Wrong parameter type: IV expected");290iape.initCause(ex);291throw iape;292}293}294engineInit(opmode, key, ivSpec, random);295}296297/**298* This operation is not supported by this cipher.299* Since it's impossible to initialize this cipher given the300* current Cipher.engineInit(...) implementation,301* IllegalStateException will always be thrown upon invocation.302*303* @param in the input buffer.304* @param inOffset the offset in <code>in</code> where the input305* starts.306* @param inLen the input length.307*308* @return n/a.309*310* @exception IllegalStateException upon invocation of this method.311*/312protected byte[] engineUpdate(byte[] in, int inOffset, int inLen) {313throw new IllegalStateException("Cipher has not been initialized");314}315316/**317* This operation is not supported by this cipher.318* Since it's impossible to initialize this cipher given the319* current Cipher.engineInit(...) implementation,320* IllegalStateException will always be thrown upon invocation.321*322* @param in the input buffer.323* @param inOffset the offset in <code>in</code> where the input324* starts.325* @param inLen the input length.326* @param out the buffer for the result.327* @param outOffset the offset in <code>out</code> where the result328* is stored.329*330* @return n/a.331*332* @exception IllegalStateException upon invocation of this method.333*/334protected int engineUpdate(byte[] in, int inOffset, int inLen,335byte[] out, int outOffset)336throws ShortBufferException {337throw new IllegalStateException("Cipher has not been initialized");338}339340/**341* This operation is not supported by this cipher.342* Since it's impossible to initialize this cipher given the343* current Cipher.engineInit(...) implementation,344* IllegalStateException will always be thrown upon invocation.345*346* @param in the input buffer.347* @param inOffset the offset in <code>in</code> where the input348* starts.349* @param inLen the input length.350*351* @return the new buffer with the result.352*353* @exception IllegalStateException upon invocation of this method.354*/355protected byte[] engineDoFinal(byte[] in, int inOffset, int inLen)356throws IllegalBlockSizeException, BadPaddingException {357throw new IllegalStateException("Cipher has not been initialized");358}359360/**361* This operation is not supported by this cipher.362* Since it's impossible to initialize this cipher given the363* current Cipher.engineInit(...) implementation,364* IllegalStateException will always be thrown upon invocation.365*366* @param input the input buffer.367* @param inputOffset the offset in {@code input} where the input368* starts.369* @param inputLen the input length.370* @param output the buffer for the result.371* @param outputOffset the ofset in {@code output} where the result372* is stored.373*374* @return the number of bytes stored in {@code out}.375*376* @exception IllegalStateException upon invocation of this method.377*/378protected int engineDoFinal(byte[] input, int inputOffset, int inputLen,379byte[] output, int outputOffset)380throws IllegalBlockSizeException, ShortBufferException,381BadPaddingException {382throw new IllegalStateException("Cipher has not been initialized");383}384385/**386* Returns the parameters used with this cipher.387* Note that null maybe returned if this cipher does not use any388* parameters or when it has not be set, e.g. initialized with389* UNWRAP_MODE but wrapped key data has not been given.390*391* @return the parameters used with this cipher; can be null.392*/393protected AlgorithmParameters engineGetParameters() {394AlgorithmParameters params = null;395if (iv != null) {396String algo = cipherKey.getAlgorithm();397try {398params = AlgorithmParameters.getInstance(algo,399SunJCE.getInstance());400params.init(new IvParameterSpec(iv));401} catch (NoSuchAlgorithmException nsae) {402// should never happen403throw new RuntimeException("Cannot find " + algo +404" AlgorithmParameters implementation in SunJCE provider");405} catch (InvalidParameterSpecException ipse) {406// should never happen407throw new RuntimeException("IvParameterSpec not supported");408}409}410return params;411}412413/**414* Returns the key size of the given key object in number of bits.415* This cipher always return the same key size as the DESede ciphers.416*417* @param key the key object.418*419* @return the "effective" key size of the given key object.420*421* @exception InvalidKeyException if <code>key</code> is invalid.422*/423protected int engineGetKeySize(Key key) throws InvalidKeyException {424byte[] encoded = key.getEncoded();425Arrays.fill(encoded, (byte)0);426if (encoded.length != 24) {427throw new InvalidKeyException("Invalid key length: " +428encoded.length + " bytes");429}430// Return the effective key length431return 112;432}433434/**435* Wrap a key.436*437* @param key the key to be wrapped.438*439* @return the wrapped key.440*441* @exception IllegalBlockSizeException if this cipher is a block442* cipher, no padding has been requested, and the length of the443* encoding of the key to be wrapped is not a444* multiple of the block size.445*446* @exception InvalidKeyException if it is impossible or unsafe to447* wrap the key with this cipher (e.g., a hardware protected key is448* being passed to a software only cipher).449*/450protected byte[] engineWrap(Key key)451throws IllegalBlockSizeException, InvalidKeyException {452byte[] keyVal = key.getEncoded();453if ((keyVal == null) || (keyVal.length == 0)) {454throw new InvalidKeyException("Cannot get an encoding of " +455"the key to be wrapped");456}457458byte[] in = new byte[Math.addExact(keyVal.length, CHECKSUM_LEN)];459byte[] cipherKeyEncoded = cipherKey.getEncoded();460byte[] out = new byte[Math.addExact(iv.length, in.length)];461try {462byte[] cks = getChecksum(keyVal);463System.arraycopy(keyVal, 0, in, 0, keyVal.length);464System.arraycopy(cks, 0, in, keyVal.length, CHECKSUM_LEN);465466System.arraycopy(iv, 0, out, 0, iv.length);467468cipher.encrypt(in, 0, in.length, out, iv.length);469470// reverse the array content471for (int i = 0; i < out.length / 2; i++) {472byte temp = out[i];473out[i] = out[out.length - 1 - i];474out[out.length - 1 - i] = temp;475}476try {477cipher.init(false, cipherKey.getAlgorithm(),478cipherKeyEncoded, IV2);479} catch (InvalidKeyException ike) {480// should never happen481throw new RuntimeException("Internal cipher key is corrupted");482} catch (InvalidAlgorithmParameterException iape) {483// should never happen484throw new RuntimeException("Internal cipher IV is invalid");485}486byte[] out2 = new byte[out.length];487cipher.encrypt(out, 0, out.length, out2, 0);488489// restore cipher state to prior to this call490try {491cipher.init(decrypting, cipherKey.getAlgorithm(),492cipherKeyEncoded, iv);493} catch (InvalidKeyException ike) {494// should never happen495throw new RuntimeException("Internal cipher key is corrupted");496} catch (InvalidAlgorithmParameterException iape) {497// should never happen498throw new RuntimeException("Internal cipher IV is invalid");499}500return out2;501} finally {502Arrays.fill(keyVal, (byte)0);503Arrays.fill(in, (byte)0);504Arrays.fill(out, (byte)0);505if (cipherKeyEncoded != null) {506Arrays.fill(cipherKeyEncoded, (byte) 0);507}508}509}510511/**512* Unwrap a previously wrapped key.513*514* @param wrappedKey the key to be unwrapped.515*516* @param wrappedKeyAlgorithm the algorithm the wrapped key is for.517*518* @param wrappedKeyType the type of the wrapped key.519* This is one of <code>Cipher.SECRET_KEY</code>,520* <code>Cipher.PRIVATE_KEY</code>, or <code>Cipher.PUBLIC_KEY</code>.521*522* @return the unwrapped key.523*524* @exception NoSuchAlgorithmException if no installed providers525* can create keys of type <code>wrappedKeyType</code> for the526* <code>wrappedKeyAlgorithm</code>.527*528* @exception InvalidKeyException if <code>wrappedKey</code> does not529* represent a wrapped key of type <code>wrappedKeyType</code> for530* the <code>wrappedKeyAlgorithm</code>.531*/532protected Key engineUnwrap(byte[] wrappedKey,533String wrappedKeyAlgorithm,534int wrappedKeyType)535throws InvalidKeyException, NoSuchAlgorithmException {536if (wrappedKey.length == 0) {537throw new InvalidKeyException("The wrapped key is empty");538}539byte[] buffer = new byte[wrappedKey.length];540cipher.decrypt(wrappedKey, 0, wrappedKey.length, buffer, 0);541542// reverse array content543for (int i = 0; i < buffer.length/2; i++) {544byte temp = buffer[i];545buffer[i] = buffer[buffer.length-1-i];546buffer[buffer.length-1-i] = temp;547}548iv = new byte[IV_LEN];549System.arraycopy(buffer, 0, iv, 0, iv.length);550byte[] cipherKeyEncoded = cipherKey.getEncoded();551byte[] out = null;552byte[] buffer2 = new byte[buffer.length - iv.length];553try {554try {555cipher.init(true, cipherKey.getAlgorithm(), cipherKeyEncoded,556iv);557} catch (InvalidAlgorithmParameterException iape) {558throw new InvalidKeyException("IV in wrapped key is invalid");559}560cipher.decrypt(buffer, iv.length, buffer2.length,561buffer2, 0);562int keyValLen = buffer2.length - CHECKSUM_LEN;563byte[] cks = getChecksum(buffer2, 0, keyValLen);564int offset = keyValLen;565for (int i = 0; i < CHECKSUM_LEN; i++) {566if (buffer2[offset + i] != cks[i]) {567throw new InvalidKeyException("Checksum comparison failed");568}569}570// restore cipher state to prior to this call571try {572cipher.init(decrypting, cipherKey.getAlgorithm(),573cipherKeyEncoded, IV2);574} catch (InvalidAlgorithmParameterException iape) {575throw new InvalidKeyException("IV in wrapped key is invalid");576}577out = new byte[keyValLen];578System.arraycopy(buffer2, 0, out, 0, keyValLen);579return ConstructKeys.constructKey(out, wrappedKeyAlgorithm,580wrappedKeyType);581} finally {582if (out != null) {583Arrays.fill(out, (byte)0);584}585if (cipherKeyEncoded != null) {586Arrays.fill(cipherKeyEncoded, (byte) 0);587}588Arrays.fill(buffer2, (byte)0);589}590}591592private static final byte[] getChecksum(byte[] in) {593return getChecksum(in, 0, in.length);594}595private static final byte[] getChecksum(byte[] in, int offset, int len) {596MessageDigest md = null;597try {598md = MessageDigest.getInstance("SHA1");599} catch (NoSuchAlgorithmException nsae) {600throw new RuntimeException("SHA1 message digest not available");601}602md.update(in, offset, len);603byte[] cks = new byte[CHECKSUM_LEN];604System.arraycopy(md.digest(), 0, cks, 0, cks.length);605md.reset();606return cks;607}608}609610611