Path: blob/master/test/jdk/com/sun/crypto/provider/Cipher/AEAD/KeyWrapper.java
41161 views
/*1* Copyright (c) 2007, 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 java.security.AlgorithmParameters;24import java.security.Key;25import java.util.Arrays;26import javax.crypto.SecretKey;27import javax.crypto.Cipher;28import javax.crypto.KeyGenerator;2930/*31* @test32* @bug 804859633* @summary Check if a key wrapper works properly with GCM mode34*/35public class KeyWrapper {3637static final String AES = "AES";38static final String TRANSFORMATION = "AES/GCM/NoPadding";39static final String PROVIDER = "SunJCE";40static final int KEY_LENGTH = 128;4142public static void main(String argv[]) throws Exception {43doTest(PROVIDER, TRANSFORMATION);44}4546private static void doTest(String provider, String algo) throws Exception {47SecretKey key;48SecretKey keyToWrap;4950// init a secret Key51KeyGenerator kg = KeyGenerator.getInstance(AES, PROVIDER);52kg.init(KEY_LENGTH);53key = kg.generateKey();54keyToWrap = kg.generateKey();5556// initialization57Cipher cipher = Cipher.getInstance(algo, provider);58cipher.init(Cipher.WRAP_MODE, key);59AlgorithmParameters params = cipher.getParameters();6061// wrap the key62byte[] keyWrapper = cipher.wrap(keyToWrap);63try {64// check if we can't wrap it again with the same key/IV65keyWrapper = cipher.wrap(keyToWrap);66throw new RuntimeException(67"FAILED: expected IllegalStateException hasn't "68+ "been thrown ");69} catch (IllegalStateException ise) {70System.out.println(ise.getMessage());71System.out.println("Expected exception");72}7374// unwrap the key75cipher.init(Cipher.UNWRAP_MODE, key, params);76cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);7778// check if we can unwrap second time79Key unwrapKey = cipher.unwrap(keyWrapper, algo, Cipher.SECRET_KEY);8081if (!Arrays.equals(keyToWrap.getEncoded(), unwrapKey.getEncoded())) {82throw new RuntimeException(83"FAILED: original and unwrapped keys are not equal");84}85}86}878889