1 /* 2 * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /* 25 * @test 26 * @bug 8014374 27 * @summary Ensure key wrap/unwrap works using AES/GCM/NoPadding 28 * @key randomness 29 */ 30 31 import java.io.*; 32 import java.security.*; 33 import java.security.spec.*; 34 import java.util.*; 35 import javax.crypto.*; 36 import javax.crypto.spec.*; 37 38 public class TestGCMKeyWrap extends UcryptoTest { 39 40 public static void main(String[] args) throws Exception { 41 main(new TestGCMKeyWrap(), null); 42 } 43 44 public void doTest(Provider p) throws Exception { 45 // check if GCM support exists 46 try { 47 Cipher.getInstance("AES/GCM/NoPadding", p); 48 } catch (NoSuchAlgorithmException nsae) { 49 System.out.println("Skipping Test due to no GCM support"); 50 return; 51 } 52 53 Random rdm = new Random(); 54 55 //init Secret Key 56 byte[] keyValue = new byte[16]; 57 rdm.nextBytes(keyValue); 58 SecretKey key = new SecretKeySpec(keyValue, "AES"); 59 60 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", p); 61 cipher.init(Cipher.WRAP_MODE, key); 62 63 byte[] wrappedKey = cipher.wrap(key); 64 65 try { // make sure ISE is thrown if re-using the same key/IV 66 wrappedKey = cipher.wrap(key); 67 throw new Exception("FAIL: expected ISE not thrown"); 68 } catch(IllegalStateException ise){ 69 System.out.println("Expected ISE thrown for re-wrapping"); 70 } 71 72 //unwrap the key 73 AlgorithmParameters params = cipher.getParameters(); 74 cipher.init(Cipher.UNWRAP_MODE, key, params); 75 Key unwrappedKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); 76 77 //check if we can unwrap second time 78 unwrappedKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); 79 80 // Comparison 81 if (!Arrays.equals(key.getEncoded(), unwrappedKey.getEncoded())) { 82 throw new Exception("FAIL: keys are not equal"); 83 } else { 84 System.out.println("Passed key equality check"); 85 } 86 } 87 }