/** * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ import java.util.Arrays; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.KeyGenerator; import java.security.AlgorithmParameters; import javax.crypto.SecretKey; import javax.crypto.Cipher; import static java.lang.System.out; /** * Chech if the key wrapper works properly with GCM mode: * - generate secret key * - init Cipher with AES/GCM/NoPadding * - using the wrapper method of Cipher do key wrapping * - check if we can't wrap it again with the same key/IV (negative case) * - using the unwrap method of Cipher do key unwrapping * - compare the original key with unwrapped one. * * @author Alexander Fomin */ public class AEADKeyWrapperTest { public static final int PASSED = 0; public static final int FAILED = 1; public static final int ERROR = 2; static final String AES = "AES"; static final String TRANSFORMATION = "AES/GCM/NoPadding"; static final String PROVIDER = "SunJCE"; static final int KEY_LENGTH = 128; private final SecretKey key1; private final SecretKey keyToWrap; private int status = PASSED; public static void main( String argv[] ) throws NoSuchAlgorithmException, NoSuchProviderException { AEADKeyWrapperTest test = new AEADKeyWrapperTest(); int status = test.execute(PROVIDER, TRANSFORMATION); if (status != PASSED) System.exit(status); } public AEADKeyWrapperTest() throws NoSuchAlgorithmException, NoSuchProviderException { //init Secret Key KeyGenerator kg = KeyGenerator.getInstance(AES, PROVIDER); kg.init(KEY_LENGTH); key1 = kg.generateKey(); keyToWrap = kg.generateKey(); } public int execute(String provider, String algo){ try { // Initialization Cipher cipher = Cipher.getInstance(algo); cipher.init( Cipher.WRAP_MODE, key1); AlgorithmParameters params = cipher.getParameters(); //wrap the key byte[] keyWrapper=cipher.wrap(keyToWrap); try{ //check if we can't wrap it again with the same key/IV keyWrapper=cipher.wrap(keyToWrap); out.println("FAILED: expected IllegalStateException hasn't " + "been thrown "); this.status = FAILED; }catch(IllegalStateException ise){}//ignore expected exception //unwrap the key cipher.init(Cipher.UNWRAP_MODE, key1, params); Key unwrappedKey = cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY); //check if we can unwrap second time unwrappedKey=cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY); // Comparison if (!Arrays.equals(keyToWrap.getEncoded(), unwrappedKey.getEncoded())){ out.println("FAILED: original and unwrapped keys are not equal."); status = FAILED; } }catch (Exception ex){//do not expect any exceptions status = ERROR; ex.printStackTrace(); } return status; } }