Path: blob/master/test/jdk/sun/security/pkcs11/KeyStore/SecretKeysBasic.java
41152 views
/*1* Copyright (c) 2008, 2021, 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*/22/* @test23* @bug 659997924* @summary Ensure that re-assigning the alias works25* @library /test/lib ..26* @run testng/othervm SecretKeysBasic27*/28import org.testng.annotations.BeforeClass;29import org.testng.annotations.Test;3031import java.io.*;32import java.nio.file.Path;33import java.util.*;34import java.security.*;35import javax.crypto.*;36import javax.crypto.spec.*;3738public class SecretKeysBasic extends PKCS11Test {3940private static final char SEP = File.separatorChar;41private static char[] tokenPwd;42private static final char[] nssPwd =43new char[]{'t', 'e', 's', 't', '1', '2'};44private static final char[] solarisPwd =45new char[]{'p', 'i', 'n'};46private static SecretKey sk1;47private static SecretKey sk2;48private static SecretKey softkey;49private static KeyStore ks;50private static final String KS_TYPE = "PKCS11";51private static Provider provider;5253@BeforeClass54public void setUp() throws Exception {55copyNssCertKeyToClassesDir();56setCommonSystemProps();57System.setProperty("TOKEN", "nss");58System.setProperty("CUSTOM_P11_CONFIG", Path.of(BASE)59.resolve("BasicData").resolve("p11-nss.txt").toString());60}6162@Test63public void testBasic() throws Exception {64main(new SecretKeysBasic());65}6667public void main(Provider p) throws Exception {68this.provider = p;6970// create secret key71byte[] keyVal = new byte[16];72(new SecureRandom()).nextBytes(keyVal);73// NSS will throw CKR_HOST_MEMORY if calling C_DecryptInit w/74// (keyVal[0] == 0)75if (keyVal[0] == 0) {76keyVal[0] = 1;77}78softkey = new SecretKeySpec(keyVal, "AES");79dumpKey("softkey", softkey);8081KeyGenerator kg = KeyGenerator.getInstance("DESede", provider);82sk1 = kg.generateKey();83dumpKey("skey1", sk1);84sk2 = kg.generateKey();85dumpKey("skey2", sk2);8687String token = System.getProperty("TOKEN");8889if (token == null || token.length() == 0) {90System.out.println("Error: missing TOKEN system property");91throw new Exception("token arg required");92}9394if ("nss".equals(token)) {95tokenPwd = nssPwd;96} else if ("solaris".equals(token)) {97tokenPwd = solarisPwd;98}99100int testnum = 1;101doTest();102}103104private static boolean checkSecretKeyEntry(String alias,105SecretKey expected,106boolean saveBeforeCheck)107throws Exception {108109// A bug in NSS 3.12 (Mozilla bug 471665) causes AES key lengths110// to be read incorrectly. Checking for improper 16 byte length111// in key string.112if (isNSS(provider) && expected.getAlgorithm().equals("AES") &&113(getNSSVersion() >= 3.12 && getNSSVersion() <= 3.122)) {114System.out.println("NSS 3.12 bug returns incorrect AES key "+115"length breaking key storage. Aborting...");116return true;117}118119if (saveBeforeCheck) {120ks.setKeyEntry(alias, expected, null, null);121}122SecretKey result = (SecretKey) (ks.getKey(alias, null));123String keyEncFormat = result.getFormat();124if (keyEncFormat == null) {125// sensitive or un-extractable keys - verify by encrypt/decrypt126byte[] data = new byte[64];127Cipher c =128Cipher.getInstance(result.getAlgorithm() + "/CBC/NoPadding",129provider);130c.init(Cipher.ENCRYPT_MODE, expected);131byte[] encOut = c.doFinal(data);132c.init(Cipher.DECRYPT_MODE, result, c.getParameters());133byte[] decOut = c.doFinal(encOut);134if (!Arrays.equals(data, decOut)) {135return false;136}137} else if (keyEncFormat.toUpperCase().equals("RAW")) {138if (!Arrays.equals(result.getEncoded(), expected.getEncoded())) {139dumpKey("\texpected:", expected);140dumpKey("\treturns:", result);141return false;142}143}144return true;145}146147private static void dumpKey(String info, SecretKey key) {148System.out.println(info + "> " + key);149System.out.println("\tALGO=" + key.getAlgorithm());150if (key.getFormat() != null) {151StringBuilder sb = new StringBuilder();152for (byte b : key.getEncoded()) {153sb.append(String.format("%02x", b & 0xff));154}155System.out.println("\t[" + key.getFormat() + "] VALUE=" + sb);156} else {157System.out.println("\tVALUE=n/a");158}159}160161private static void doTest() throws Exception {162// Make sure both NSS libraries are the same version.163if (isNSS(provider) &&164(getLibsoftokn3Version() != getLibnss3Version())) {165System.out.println("libsoftokn3 and libnss3 versions do not match. Aborting test...");166return;167}168169if (ks == null) {170ks = KeyStore.getInstance(KS_TYPE, provider);171ks.load(null, tokenPwd);172}173174System.out.println("Number of entries: " + ks.size());175if (ks.size() != 0) {176System.out.println("Deleting entries under aliases: ");177for (Enumeration<String> aliases = ks.aliases();178aliases.hasMoreElements();) {179String alias = aliases.nextElement();180System.out.println("\t" + alias);181ks.deleteEntry(alias);182}183}184185String alias = "testSKey";186187boolean testResult = checkSecretKeyEntry(alias, softkey, true);188if (!testResult) {189System.out.println("FAILURE: setKey() w/ softSecretKey failed");190}191192if (!checkSecretKeyEntry(alias, sk1, true)) {193testResult = false;194System.out.println("FAILURE: setKey() w/ skey1 failed");195}196if (!checkSecretKeyEntry(alias, sk2, true)) {197testResult = false;198System.out.println("FAILURE: setKey() w/ skey2 failed");199}200201ks.store(null);202System.out.println("Reloading keystore...");203204ks.load(null, "whatever".toCharArray());205if (ks.size() != 1) {206System.out.println("FAILURE: reload#1 ks.size() != 1");207}208if (!checkSecretKeyEntry(alias, sk2, false)) {209testResult = false;210System.out.println("FAILURE: reload#1 ks entry check failed");211}212213ks.deleteEntry(alias);214ks.store(null);215216System.out.println("Reloading keystore...");217ks.load(null, "whatever".toCharArray());218if (ks.size() != 0) {219testResult = false;220System.out.println("FAILURE: reload#2 ks.size() != 0");221}222if (!testResult) {223throw new Exception("One or more test failed!");224}225}226}227228229