static void testBad(String s) throws Exception { System.err.println("Trying " + s); try { new ObjectIdentifier(s); throw new Exception("should be invalid ObjectIdentifier"); } catch (IOException ioe) { System.err.println(ioe); } try { new Oid(s); throw new Exception("should be invalid Oid"); } catch (GSSException gsse) { ; } try { new EncryptedPrivateKeyInfo(s, new byte[8]); throw new Exception("should be invalid algorithm"); } catch (NoSuchAlgorithmException e) { ; } }
public void engineSetKeyEntry(String alias, byte[] encodedKey, Certificate[] certChain) throws KeyStoreException { alias = alias.toLowerCase(); if (trustedCerts.containsKey(alias)) throw new KeyStoreException("\"" + alias + "\" is a trusted certificate entry"); try { new EncryptedPrivateKeyInfo(encodedKey); } catch (IOException ioe) { throw new KeyStoreException("encoded key is not an EncryptedPrivateKeyInfo"); } privateKeys.put(alias, encodedKey); if (certChain != null) certChains.put(alias, certChain); else certChains.put(alias, new Certificate[0]); if (!aliases.contains(alias)) { dates.put(alias, new Date()); aliases.add(alias); } }
private static PKCS8EncodedKeySpec readPrivateKey(File keyFile, Optional<String> keyPassword) throws IOException, GeneralSecurityException { String content = Files.toString(keyFile, US_ASCII); Matcher matcher = KEY_PATTERN.matcher(content); if (!matcher.find()) { throw new KeyStoreException("found no private key: " + keyFile); } byte[] encodedKey = base64Decode(matcher.group(1)); if (!keyPassword.isPresent()) { return new PKCS8EncodedKeySpec(encodedKey); } EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName()); SecretKey secretKey = keyFactory.generateSecret(new PBEKeySpec(keyPassword.get().toCharArray())); Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName()); cipher.init(DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters()); return encryptedPrivateKeyInfo.getKeySpec(cipher); }
/** * Reads the private key from an encrypted PKCS#8 file and returns it as an ECPrivateKey instance. * * @param A PKCS#8 (.key) file containing the private key with value "s" * @return The private key as an ECPrivateKey instance */ public static ECPrivateKey getPrivateKey(String keyFilePath) { Path fileLocation = Paths.get(keyFilePath); byte[] pkcs8ByteArray; try { pkcs8ByteArray = Files.readAllBytes(fileLocation); // The DER encoded private key is password-based encrypted and provided in PKCS#8. So we need to decrypt it first PBEKeySpec pbeKeySpec = new PBEKeySpec(GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString().toCharArray()); EncryptedPrivateKeyInfo encryptedPrivKeyInfo = new EncryptedPrivateKeyInfo(pkcs8ByteArray); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivKeyInfo.getAlgName()); Key secret = secretKeyFactory.generateSecret(pbeKeySpec); PKCS8EncodedKeySpec pkcs8PrivKeySpec = encryptedPrivKeyInfo.getKeySpec(secret); ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(pkcs8PrivKeySpec); return privateKey; } catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException e) { getLogger().error(e.getClass().getSimpleName() + " occurred while trying to access private key at " + "location '" + keyFilePath + "'"); return null; } }
public static PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception { String privateKeyPEM = key .replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "") .replace("-----END ENCRYPTED PRIVATE KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM); EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(epkInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters()); return epkInfo.getKeySpec(cipher); }
public PKCS8EncodedKeySpec getEncodedPrivateKeySpec(String key, String password) throws Exception { String privateKeyPEM = key .replace("-----BEGIN ENCRYPTED PRIVATE KEY-----", "") .replace("-----END ENCRYPTED PRIVATE KEY-----", "") .replaceAll("\\s", ""); // decode to get the binary DER representation byte[] privateKeyDER = Base64.getDecoder().decode(privateKeyPEM); EncryptedPrivateKeyInfo epkInfo = new EncryptedPrivateKeyInfo(privateKeyDER); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(epkInfo.getAlgName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(epkInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, pbeKey, epkInfo.getAlgParameters()); return epkInfo.getKeySpec(cipher); }
public static void main(String[] argv) throws Exception { EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo( Base64.getMimeDecoder().decode(PKCS8PrivateKey)); PBEKeySpec pks = new PBEKeySpec(password.toCharArray()); SecretKeyFactory skf = SecretKeyFactory.getInstance(epki.getAlgName()); SecretKey sk = skf.generateSecret(pks); PKCS8EncodedKeySpec keySpec = epki.getKeySpec(sk); // Get the key algorithm and make sure it's what we expect String alg = keySpec.getAlgorithm(); if (!alg.equals(keyAlg)) { throw new Exception("Expected: " + keyAlg + ", Got: " + alg); } System.out.println("Test passed"); }
private static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException { if (password == null) { return new PKCS8EncodedKeySpec(key); } EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters()); return encryptedPrivateKeyInfo.getKeySpec(cipher); }
/** * Generates a key specification for an (encrypted) private key. * * @param password characters, if {@code null} or empty an unencrypted key is assumed * @param key bytes of the DER encoded private key * * @return a key specification * * @throws IOException if parsing {@code key} fails * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unkown * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unkown * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt * {@code key} * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty */ protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException { if (password == null || password.length == 0) { return new PKCS8EncodedKeySpec(key); } EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters()); return encryptedPrivateKeyInfo.getKeySpec(cipher); }
private static PrivateKey decryptPrivateKey(String encryptedPrivateKey, String secret) throws GeneralSecurityException, IOException { byte[] encodedPrivateKey = Base64.getMimeDecoder() .decode(encryptedPrivateKey.getBytes(Constants.DEFAULT_ENCODING)); EncryptedPrivateKeyInfo encryptPKInfo = new EncryptedPrivateKeyInfo(encodedPrivateKey); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); PBEKeySpec pbeKeySpec = new PBEKeySpec(secret.toCharArray()); SecretKeyFactory secretFactory = SecretKeyFactory.getInstance(CIPHER_ALGORITHM); Key pbeKey = secretFactory.generateSecret(pbeKeySpec); AlgorithmParameters algorithmParameters = encryptPKInfo.getAlgParameters(); cipher.init(Cipher.DECRYPT_MODE, pbeKey, algorithmParameters); KeySpec pkcsKeySpec = encryptPKInfo.getKeySpec(cipher); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(pkcsKeySpec); }
/** * Test #6 for <code>EncryptedPrivateKeyInfo(byte[])</code> constructor * <br> * Assertion: byte array is copied to prevent subsequent modification <br> * Test preconditions: valid array passed then modified <br> * Expected: getEncoded(), invoked after above modification, must return * array as it was before the modification * * @throws IOException */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "This is a complete subset of tests for EncryptedPrivateKeyInfo(byte[]) constructor.", method = "EncryptedPrivateKeyInfo", args = {byte[].class} ) public final void testEncryptedPrivateKeyInfobyteArray6() throws Exception { byte[] encoded = EncryptedPrivateKeyInfoData .getValidEncryptedPrivateKeyInfoEncoding("DSA"); byte[] encodedCopy = encoded.clone(); // pass valid array EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(encodedCopy); // modify array passed encodedCopy[9] = (byte) 6; // check that internal state has not been affected assertTrue(Arrays.equals(encoded, epki.getEncoded())); }
/** * Test #1 for <code>EncryptedPrivateKeyInfo(String, byte[])</code> * constructor <br> * Assertion: creates <code>EncryptedPrivateKeyInfo</code> instance <br> * Test preconditions: valid parameters passed <br> * Expected: must pass without any exceptions */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "This is a complete subset of tests for EncryptedPrivateKeyInfo(String, byte[]) constructor.", method = "EncryptedPrivateKeyInfo", args = {java.lang.String.class, byte[].class} ) public final void testEncryptedPrivateKeyInfoStringbyteArray1() { boolean performed = false; for (int i = 0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) { try { new EncryptedPrivateKeyInfo( EncryptedPrivateKeyInfoData.algName0[i][0], EncryptedPrivateKeyInfoData.encryptedData); performed = true; } catch (NoSuchAlgorithmException allowed) { } } assertTrue("Test not performed", performed); }
/** * Test #5 for <code>EncryptedPrivateKeyInfo(String, byte[])</code> * constructor <br> * Assertion: byte array is copied to prevent subsequent modification <br> * Test preconditions: valid array passed then modified <br> * Expected: getEncryptedData(), invoked after above modification, must * return array as it was before the modification * * @throws IOException */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "This is a complete subset of tests for EncryptedPrivateKeyInfo(String, byte[]) constructor.", method = "EncryptedPrivateKeyInfo", args = {java.lang.String.class, byte[].class} ) public final void testEncryptedPrivateKeyInfoStringbyteArray5() throws Exception { byte[] encryptedDataCopy = EncryptedPrivateKeyInfoData.encryptedData .clone(); // pass valid array EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo("DSA", encryptedDataCopy); // modify array passed encryptedDataCopy[0] = (byte) 6; // check that internal state has not been affected assertTrue(Arrays.equals(EncryptedPrivateKeyInfoData.encryptedData, epki.getEncryptedData())); }
/** * @tests javax/crypto/EncryptedPrivateKeyInfo(String, byte[]) * Checks exception order */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "This is a complete subset of tests for EncryptedPrivateKeyInfo(String, byte[]) constructor.", method = "EncryptedPrivateKeyInfo", args = {java.lang.String.class, byte[].class} ) public final void testEncryptedPrivateKeyInfoStringbyteArray6() { //Regression for HARMONY-768 try { new EncryptedPrivateKeyInfo("0", new byte[] {}); fail("NoSuchAlgorithmException expected"); } catch (NoSuchAlgorithmException e) { //expected } }
/** * Test #3 for * <code>EncryptedPrivateKeyInfo(java.security.AlgorithmParameters, byte[]) * </code> * constructor <br> * Assertion: <code>IllegalArgumentException</code>- if encrypted data is * empty, i.e. 0-length <br> * Test preconditions: pass empty encrypted data <br> * Expected: <code>IllegalArgumentException</code> * * @throws NoSuchAlgorithmException * @throws IOException */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "IllegalArgumentException checked.", method = "EncryptedPrivateKeyInfo", args = {java.security.AlgorithmParameters.class, byte[].class} ) public final void testEncryptedPrivateKeyInfoAlgorithmParametersbyteArray3() throws Exception { try { AlgorithmParameters ap = AlgorithmParameters.getInstance("DSA"); // use pregenerated AlgorithmParameters encodings ap.init(EncryptedPrivateKeyInfoData.getParametersEncoding("DSA")); new EncryptedPrivateKeyInfo(ap, new byte[] {}); fail(getName() + ": IllegalArgumentException has not been thrown"); } catch (IllegalArgumentException ok) { } }
/** * Test #4 for * <code>EncryptedPrivateKeyInfo(java.security.AlgorithmParameters, byte[]) * </code> * constructor <br> * Assertion: byte array is copied to prevent subsequent modification <br> * Test preconditions: valid array passed then modified <br> * Expected: getEncryptedData(), invoked after above modification, must * return array as it was before the modification * * @throws IOException */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Functionality checked.", method = "EncryptedPrivateKeyInfo", args = {java.security.AlgorithmParameters.class, byte[].class} ) public final void testEncryptedPrivateKeyInfoAlgorithmParametersbyteArray4() throws Exception { AlgorithmParameters ap = AlgorithmParameters.getInstance("DSA"); // use pregenerated AlgorithmParameters encodings ap.init(EncryptedPrivateKeyInfoData.getParametersEncoding("DSA")); byte[] encryptedDataCopy = EncryptedPrivateKeyInfoData.encryptedData.clone(); // pass valid array EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(ap, encryptedDataCopy); // modify array passed encryptedDataCopy[0] = (byte) 6; // check that internal state has not been affected assertTrue(Arrays.equals(EncryptedPrivateKeyInfoData.encryptedData, epki.getEncryptedData())); }
@TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "This is a complete subset of tests for getAlgParameters method.", method = "getAlgParameters", args = {} ) public final void testGetAlgParameters01_01() throws Exception { byte[] validEncodingWithUnknownAlgOID = EncryptedPrivateKeyInfoData .getValidEncryptedPrivateKeyInfoEncoding("DH"); // correct oid value validEncodingWithUnknownAlgOID[18] = 0; EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo( validEncodingWithUnknownAlgOID); assertNull(epki.getAlgParameters()); }
/** * Test #2 for <code>getAlgParameters()</code> method <br> * Assertion: returns the algorithm parameters <br> * Test preconditions: test object created using ctor which takes encoded * form as the only parameter; encoded form passed does not contain * algorithm parameters encoding <br> * Expected: <code>null</code> must be returned * * @throws IOException */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "This is a complete subset of tests for getAlgParameters method.", method = "getAlgParameters", args = {} ) public final void testGetAlgParameters02() throws IOException { boolean performed = false; for (int i = 0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) { try { EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo( EncryptedPrivateKeyInfoData .getValidEncryptedPrivateKeyInfoEncoding( EncryptedPrivateKeyInfoData.algName0[i][0], false)); // check that method under test returns null assertNull(epki.getAlgParameters()); performed = true; } catch (NoSuchAlgorithmException allowedFailure) { } } assertTrue("Test not performed", performed); }
/** * Test #3 for <code>getAlgParameters()</code> method <br> * Assertion: returns the algorithm parameters <br> * Test #6 for <code>EncryptedPrivateKeyInfo(String, byte[])</code> * constructor <br> * Assertion: ...This constructor will use null as the value of the * algorithm parameters. <br> * Test preconditions: test object created using ctor which takes algorithm * name and encrypted data as a parameters <br> * Expected: <code>null</code> must be returned * * @throws IOException */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "This is a complete subset of tests for getAlgParameters method.", method = "getAlgParameters", args = {} ) public final void testGetAlgParameters03() throws IOException { boolean performed = false; for (int i = 0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) { try { EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo( EncryptedPrivateKeyInfoData.algName0[i][0], EncryptedPrivateKeyInfoData.encryptedData); // check that method under test returns null // for object constructed in such a way assertNull(epki.getAlgParameters()); performed = true; } catch (NoSuchAlgorithmException allowedFailure) { } } assertTrue("Test not performed", performed); }
/** * Test #1 for <code>getEncoded()</code> method <br> * Assertion: returns the ASN.1 encoding of this object <br> * Test preconditions: test object created using ctor which takes encoded * form as the only parameter <br> * Expected: equivalent encoded form must be returned * * @throws IOException */ @TestTargetNew( level = TestLevel.PARTIAL_COMPLETE, notes = "Can not check IOException", method = "getEncoded", args = {} ) public final void testGetEncoded01() throws IOException { boolean performed = false; for (int i = 0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) { try { byte[] enc = EncryptedPrivateKeyInfoData .getValidEncryptedPrivateKeyInfoEncoding( EncryptedPrivateKeyInfoData.algName0[i][0]); EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(enc); // check that method under test returns // valid encoded form assertTrue(Arrays.equals(enc, epki.getEncoded())); performed = true; } catch (NoSuchAlgorithmException allowedFailure) { } } assertTrue("Test not performed", performed); }
/** * Test #1 for <code>EncryptedPrivateKeyInfo(String, byte[])</code> * constructor <br> * Assertion: creates <code>EncryptedPrivateKeyInfo</code> instance <br> * Test preconditions: valid parameters passed <br> * Expected: must pass without any exceptions */ public final void testEncryptedPrivateKeyInfoStringbyteArray1() { boolean performed = false; for (int i = 0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) { try { new EncryptedPrivateKeyInfo( EncryptedPrivateKeyInfoData.algName0[i][0], EncryptedPrivateKeyInfoData.encryptedData); performed = true; } catch (NoSuchAlgorithmException allowed) { } } assertTrue("Test not performed", performed); }
/** * Test #1 for * <code>EncryptedPrivateKeyInfo(java.security.AlgorithmParameters, byte[]) * </code> * constructor <br> * Assertion: creates <code>EncryptedPrivateKeyInfo</code> instance <br> * Test preconditions: valid parameters passed <br> * Expected: must pass without any exceptions * * @throws IOException */ public final void testEncryptedPrivateKeyInfoAlgorithmParametersbyteArray1() throws IOException { boolean performed = false; for (int i = 0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) { try { AlgorithmParameters ap = AlgorithmParameters .getInstance(EncryptedPrivateKeyInfoData.algName0[i][0]); // use pregenerated AlgorithmParameters encodings ap.init(EncryptedPrivateKeyInfoData.getParametersEncoding( EncryptedPrivateKeyInfoData.algName0[i][0])); new EncryptedPrivateKeyInfo(ap, EncryptedPrivateKeyInfoData.encryptedData); performed = true; } catch (NoSuchAlgorithmException allowedFailure) { } } assertTrue("Test not performed", performed); }
/** * Test #4 for * <code>EncryptedPrivateKeyInfo(java.security.AlgorithmParameters, byte[]) * </code> * constructor <br> * Assertion: byte array is copied to prevent subsequent modification <br> * Test preconditions: valid array passed then modified <br> * Expected: getEncryptedData(), invoked after above modification, must * return array as it was before the modification * * @throws IOException */ public final void testEncryptedPrivateKeyInfoAlgorithmParametersbyteArray4() throws Exception { AlgorithmParameters ap = AlgorithmParameters.getInstance("DSA"); // use pregenerated AlgorithmParameters encodings ap.init(EncryptedPrivateKeyInfoData.getParametersEncoding("DSA")); byte[] encryptedDataCopy = EncryptedPrivateKeyInfoData.encryptedData.clone(); // pass valid array EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(ap, encryptedDataCopy); // modify array passed encryptedDataCopy[0] = (byte) 6; // check that internal state has not been affected assertTrue(Arrays.equals(EncryptedPrivateKeyInfoData.encryptedData, epki.getEncryptedData())); }
/** * Test #2 for <code>getAlgParameters()</code> method <br> * Assertion: returns the algorithm parameters <br> * Test preconditions: test object created using ctor which takes encoded * form as the only parameter; encoded form passed does not contain * algorithm parameters encoding <br> * Expected: <code>null</code> must be returned * * @throws IOException */ public final void testGetAlgParameters02() throws IOException { boolean performed = false; for (int i = 0; i < EncryptedPrivateKeyInfoData.algName0.length; i++) { try { EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo( EncryptedPrivateKeyInfoData .getValidEncryptedPrivateKeyInfoEncoding( EncryptedPrivateKeyInfoData.algName0[i][0], false)); // check that method under test returns null assertNull(epki.getAlgParameters()); performed = true; } catch (NoSuchAlgorithmException allowedFailure) { } } assertTrue("Test not performed", performed); }