Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/security/pkcs12/P12SecretKey.java
38840 views
/*1* Copyright (c) 2016, 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*/2223/*24* @test25* @bug 814941126* @summary Get AES key from keystore (uses SecretKeySpec not SecretKeyFactory)27*/2829import java.io.File;30import java.io.FileInputStream;31import java.io.FileOutputStream;32import java.security.KeyStore;33import java.security.cert.CertificateException;34import java.util.Arrays;3536import javax.crypto.KeyGenerator;37import javax.crypto.SecretKey;3839public class P12SecretKey {4041private static final String ALIAS = "alias";4243public static void main(String[] args) throws Exception {44P12SecretKey testp12 = new P12SecretKey();45String keystoreType = "pkcs12";46if (args != null && args.length > 0) {47keystoreType = args[0];48}49testp12.run(keystoreType);50}5152private void run(String keystoreType) throws Exception {53char[] pw = "password".toCharArray();54KeyStore ks = KeyStore.getInstance(keystoreType);55ks.load(null, pw);5657KeyGenerator kg = KeyGenerator.getInstance("AES");58kg.init(128);59SecretKey key = kg.generateKey();6061KeyStore.SecretKeyEntry ske = new KeyStore.SecretKeyEntry(key);62KeyStore.ProtectionParameter kspp = new KeyStore.PasswordProtection(pw);63ks.setEntry(ALIAS, ske, kspp);6465File ksFile = File.createTempFile("test", ".test");66try (FileOutputStream fos = new FileOutputStream(ksFile)) {67ks.store(fos, pw);68fos.flush();69}7071// now see if we can get it back72try (FileInputStream fis = new FileInputStream(ksFile)) {73KeyStore ks2 = KeyStore.getInstance(keystoreType);74ks2.load(fis, pw);75KeyStore.Entry entry = ks2.getEntry(ALIAS, kspp);76SecretKey keyIn = ((KeyStore.SecretKeyEntry)entry).getSecretKey();77if (Arrays.equals(key.getEncoded(), keyIn.getEncoded())) {78System.err.println("OK: worked just fine with " + keystoreType +79" keystore");80} else {81System.err.println("ERROR: keys are NOT equal after storing in "82+ keystoreType + " keystore");83}84}85}86}878889