1 /* 2 * Copyright (c) 2018, 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 8153029 27 * @summary ChaCha20 key generator test. 28 * @library /test/lib 29 */ 30 31 import java.security.InvalidAlgorithmParameterException; 32 import java.security.InvalidParameterException; 33 34 import javax.crypto.KeyGenerator; 35 import javax.crypto.SecretKey; 36 import javax.crypto.spec.ChaCha20ParameterSpec; 37 38 import jdk.test.lib.Utils; 39 40 public class ChaCha20KeyGeneratorTest { 41 42 public static void main(String[] args) throws Exception { 43 KeyGenerator generator = KeyGenerator.getInstance("ChaCha20"); 44 45 try { 46 generator.init(new ChaCha20ParameterSpec( 47 Utils.toByteArray("100000000000000000000000"), 0)); 48 throw new RuntimeException( 49 "ChaCha20 key generation should not consume AlgorithmParameterSpec"); 50 } catch (InvalidAlgorithmParameterException e) { 51 System.out.println("Expected InvalidAlgorithmParameterException: " 52 + e.getMessage()); 53 } 54 55 for (int keySize : new int[] { 32, 64, 128, 512, 1024 }) { 56 try { 57 generator.init(keySize); 58 throw new RuntimeException("The key size for ChaCha20 must be 256"); 59 } catch (InvalidParameterException e) { 60 System.out.println( 61 "Expected InvalidParameterException: " + keySize); 62 } 63 } 64 65 generator.init(256); 66 SecretKey key = generator.generateKey(); 67 byte[] keyValue = key.getEncoded(); 68 System.out.println("Key: " + Utils.toHexString(keyValue)); 69 if (keyValue.length != 32) { 70 throw new RuntimeException("The size of generated key must be 256"); 71 } 72 } 73 }