Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/com/sun/crypto/provider/Cipher/KeyWrap/TestCipherKeyWrapperTest.java
38889 views
/*1* Copyright (c) 2015, 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.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import static java.lang.System.out;2425import java.lang.Integer;26import java.lang.String;27import java.lang.System;28import java.security.AlgorithmParameters;29import java.security.InvalidAlgorithmParameterException;30import java.security.InvalidKeyException;31import java.security.Key;32import java.security.KeyPair;33import java.security.NoSuchAlgorithmException;34import java.security.KeyPairGenerator;35import java.security.Provider;36import java.security.Security;37import java.security.spec.AlgorithmParameterSpec;38import java.security.spec.InvalidKeySpecException;39import java.util.Arrays;40import java.util.HashMap;41import java.util.Map;42import java.util.Random;4344import javax.crypto.IllegalBlockSizeException;45import javax.crypto.NoSuchPaddingException;46import javax.crypto.SecretKey;47import javax.crypto.Cipher;48import javax.crypto.KeyGenerator;49import javax.crypto.SecretKeyFactory;50import javax.crypto.spec.PBEKeySpec;51import javax.crypto.spec.PBEParameterSpec;5253/*54* @test55* @bug 804859956* @summary Tests for key wrap and unwrap operations57*/5859public class TestCipherKeyWrapperTest {60private static final String SUN_JCE = "SunJCE";61// Blowfish Variable key length: 32 bits to 448 bits62private static final int BLOWFISH_MIN_KEYSIZE = 32;63private static final int BLOWFISH_MAX_KEYSIZE = 448;64private static final int LINIMITED_KEYSIZE = 128;65private static final String NOPADDING = "NoPaDDing";66private static final String[] PBE_ALGORITHM_AR = { "pbeWithMD5ANDdes",67"PBEWithMD5AndDES/CBC/PKCS5Padding", "PBEWithMD5AndTripleDES",68"PBEWithMD5AndTripleDES/CBC/PKCS5Padding", "PBEwithSHA1AndDESede",69"PBEwithSHA1AndDESede/CBC/PKCS5Padding", "PBEwithSHA1AndRC2_40",70"PBEwithSHA1Andrc2_40/CBC/PKCS5Padding", "PBEWithSHA1AndRC2_128",71"PBEWithSHA1andRC2_128/CBC/PKCS5Padding", "PBEWithSHA1AndRC4_40",72"PBEWithsha1AndRC4_40/ECB/NoPadding", "PBEWithSHA1AndRC4_128",73"pbeWithSHA1AndRC4_128/ECB/NoPadding", "PBEWithHmacSHA1AndAES_128",74"PBEWithHmacSHA224AndAES_128", "PBEWithHmacSHA256AndAES_128",75"PBEWithHmacSHA384AndAES_128", "PBEWithHmacSHA512AndAES_128",76"PBEWithHmacSHA1AndAES_256", "PBEWithHmacSHA224AndAES_256",77"PBEWithHmacSHA256AndAES_256", "PBEWithHmacSHA384AndAES_256",78"PBEWithHmacSHA512AndAES_256" };79private static final String[] MODEL_AR = { "ECb", "pCbC", "cbC", "cFB",80"cFB24", "cFB40", "OfB48", "OFB64" };81private static final String[] PADDING_AR = { NOPADDING, "PKCS5Padding" };8283private enum AlgorithmWrapper {84AESWrap("AES", "AESWrap", -1),85AESWrap_128("AES", "AESWrap_128", 128),86AESWrap_192("AES", "AESWrap_192", 192),87AESWrap_256("AES", "AESWrap_256", 256),88DESedeWrap("desede", "DESedeWrap", -1),89NegtiveWrap("AES", "DESedeWrap", -1);9091private final String algorithm;92private final String wrapper;93private final int keySize;9495private AlgorithmWrapper(String algorithm, String wrapper, int kSize) {96this.algorithm = algorithm;97this.wrapper = wrapper;98this.keySize = kSize;99}100101public String getAlgorithm() {102return algorithm;103}104105public String getWrapper() {106return wrapper;107}108109public int getKeySize() {110return keySize;111}112113};114115public static void main(String[] args) throws Exception {116117TestCipherKeyWrapperTest test = new TestCipherKeyWrapperTest();118// AESWrap and DESedeWrap test119for (AlgorithmWrapper algoWrapper : AlgorithmWrapper.values()) {120String algo = algoWrapper.getAlgorithm();121String wrapper = algoWrapper.getWrapper();122try {123int keySize = algoWrapper.getKeySize();124// only run the tests on longer key lengths if unlimited125// version of JCE jurisdiction policy files are installed126if (!(Cipher.getMaxAllowedKeyLength(algo) == Integer.MAX_VALUE)127&& keySize > LINIMITED_KEYSIZE) {128out.println(algo + " will not run if unlimited version of"129+ " JCE jurisdiction policy files are installed");130continue;131}132test.wrapperAesDESedeKeyTest(algo, wrapper, keySize);133if (algoWrapper == AlgorithmWrapper.NegtiveWrap) {134throw new RuntimeException("Expected not throw when algo"135+ " and wrapAlgo are not match:" + algo);136}137} catch (InvalidKeyException e) {138if (algoWrapper == AlgorithmWrapper.NegtiveWrap) {139out.println("Expepted exception when algo"140+ " and wrapAlgo are not match:" + algo);141} else {142throw e;143}144}145}146test.wrapperBlowfishKeyTest();147// PBE and public wrapper test.148String[] publicPrivateAlgos = new String[] { "DiffieHellman", "DSA",149"RSA" };150Provider provider = Security.getProvider(SUN_JCE);151if (provider == null) {152throw new RuntimeException("SUN_JCE provider not exist");153}154155test.wrapperPBEKeyTest(provider);156// Public and private key wrap test157test.wrapperPublicPriviteKeyTest(provider, publicPrivateAlgos);158}159160private void wrapperAesDESedeKeyTest(String algo, String wrapAlgo,161int keySize) throws InvalidKeyException, NoSuchAlgorithmException,162NoSuchPaddingException, IllegalBlockSizeException,163InvalidAlgorithmParameterException {164// Initialization165KeyGenerator kg = KeyGenerator.getInstance(algo);166if (keySize != -1) {167kg.init(keySize);168}169SecretKey key = kg.generateKey();170wrapTest(algo, wrapAlgo, key, key, Cipher.SECRET_KEY, false);171}172173private void wrapperBlowfishKeyTest() throws InvalidKeyException,174NoSuchAlgorithmException, NoSuchPaddingException,175IllegalBlockSizeException, InvalidAlgorithmParameterException {176// how many kinds of padding mode177int padKinds;178// Keysize should be multiple of 8 bytes.179int KeyCutter = 8;180int kSize = BLOWFISH_MIN_KEYSIZE;181String algorithm = "Blowfish";182int maxAllowKeyLength = Cipher.getMaxAllowedKeyLength(algorithm);183boolean unLimitPolicy = maxAllowKeyLength == Integer.MAX_VALUE;184SecretKey key = null;185while (kSize <= BLOWFISH_MAX_KEYSIZE) {186for (String mode : MODEL_AR) {187// PKCS5padding is meaningful only for ECB, CBC, PCBC188if (mode.equalsIgnoreCase(MODEL_AR[0])189|| mode.equalsIgnoreCase(MODEL_AR[1])190|| mode.equalsIgnoreCase(MODEL_AR[2])) {191padKinds = PADDING_AR.length;192} else {193padKinds = 1;194}195// Initialization196KeyGenerator kg = KeyGenerator.getInstance(algorithm);197for (int k = 0; k < padKinds; k++) {198String transformation = algorithm + "/" + mode + "/"199+ PADDING_AR[k];200if (NOPADDING.equals(PADDING_AR[k]) && kSize % 64 != 0) {201out.println(transformation202+ " will not run if input length not multiple"203+ " of 8 bytes when padding is " + NOPADDING);204continue;205}206kg.init(kSize);207key = kg.generateKey();208// only run the tests on longer key lengths if unlimited209// version of JCE jurisdiction policy files are installed210if (!unLimitPolicy && kSize > LINIMITED_KEYSIZE) {211out.println("keyStrength > 128 within " + algorithm212+ " will not run under global policy");213} else {214wrapTest(transformation, transformation, key, key,215Cipher.SECRET_KEY, false);216}217}218}219if (kSize <= LINIMITED_KEYSIZE) {220KeyCutter = 8;221} else {222KeyCutter = 48;223}224kSize += KeyCutter;225}226}227228private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,229InvalidKeyException, NoSuchPaddingException,230IllegalBlockSizeException, InvalidAlgorithmParameterException,231NoSuchAlgorithmException {232for (String alg : PBE_ALGORITHM_AR) {233String baseAlgo = alg.split("/")[0].toUpperCase();234// only run the tests on longer key lengths if unlimited version235// of JCE jurisdiction policy files are installed236237if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE238&& (baseAlgo.endsWith("TRIPLEDES") || alg239.endsWith("AES_256"))) {240out.println("keyStrength > 128 within " + alg241+ " will not run under global policy");242continue;243}244SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);245SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"246.toCharArray()));247wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);248}249}250251private void wrapperPublicPriviteKeyTest(Provider p, String[] algorithms)252throws NoSuchAlgorithmException, InvalidKeyException,253NoSuchPaddingException, IllegalBlockSizeException,254InvalidAlgorithmParameterException {255for (String algo : algorithms) {256// Key pair generated257System.out.println("Generate key pair (algorithm: " + algo258+ ", provider: " + p.getName() + ")");259KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);260kpg.initialize(512);261KeyPair kp = kpg.genKeyPair();262// key generated263String algoWrap = "DES";264KeyGenerator kg = KeyGenerator.getInstance(algoWrap, p);265Key key = kg.generateKey();266wrapTest(algo, algoWrap, key, kp.getPrivate(), Cipher.PRIVATE_KEY,267false);268wrapTest(algo, algoWrap, key, kp.getPublic(), Cipher.PUBLIC_KEY,269false);270}271}272273private void wrapTest(String transformation, String wrapAlgo, Key initKey,274Key wrapKey, int keyType, boolean isPBE)275throws NoSuchAlgorithmException, NoSuchPaddingException,276InvalidKeyException, IllegalBlockSizeException,277InvalidAlgorithmParameterException {278String algo = transformation.split("/")[0];279boolean isAESBlowfish = algo.indexOf("AES") != -1280|| algo.indexOf("Blowfish") != -1;281AlgorithmParameters aps = null;282AlgorithmParameterSpec pbeParams = null;283if (isPBE) {284byte[] salt = new byte[8];285int iterCnt = 1000;286new Random().nextBytes(salt);287pbeParams = new PBEParameterSpec(salt, iterCnt);288}289// Wrap & UnWrap operation290Cipher wrapCI = Cipher.getInstance(wrapAlgo);291if (isPBE && !isAESBlowfish) {292wrapCI.init(Cipher.WRAP_MODE, initKey, pbeParams);293} else if (isAESBlowfish) {294wrapCI.init(Cipher.WRAP_MODE, initKey);295aps = wrapCI.getParameters();296} else {297wrapCI.init(Cipher.WRAP_MODE, initKey);298}299out.println("keysize : " + wrapKey.getEncoded().length);300byte[] keyWrapper = wrapCI.wrap(wrapKey);301if (isPBE && !isAESBlowfish) {302wrapCI.init(Cipher.UNWRAP_MODE, initKey, pbeParams);303} else if (isAESBlowfish) {304wrapCI.init(Cipher.UNWRAP_MODE, initKey, aps);305} else {306wrapCI.init(Cipher.UNWRAP_MODE, initKey);307}308Key unwrappedKey = wrapCI.unwrap(keyWrapper, algo, keyType);309// Comparison310if (!Arrays.equals(wrapKey.getEncoded(), unwrappedKey.getEncoded())) {311throw new RuntimeException("Comparation failed testing "312+ transformation + ":" + wrapAlgo + ":" + keyType);313}314}315}316317318