/** Convert PKCS#8 PEM file to DER encoded private key */ private static byte[] getDer(Path path) throws IOException { List<String> lines = Files.readAllLines(path); // remove header and footer, combine to single string without line breaks String base64Text = lines.subList(1, lines.size() - 1).stream().collect(joining()); Decoder decoder = Base64.getDecoder(); return decoder.decode(base64Text); }
public Collection<KeyPair> loadKeyPairs( String resourceKey, String pubData, String prvData, String prvEncryption, FilePasswordProvider passwordProvider) throws IOException, GeneralSecurityException { Decoder b64Decoder = Base64.getDecoder(); byte[] pubBytes = b64Decoder.decode(pubData); byte[] prvBytes = b64Decoder.decode(prvData); String password = null; if ((GenericUtils.length(prvEncryption) > 0) && (!NO_PRIVATE_KEY_ENCRYPTION_VALUE.equalsIgnoreCase(prvEncryption))) { password = passwordProvider.getPassword(resourceKey); } if (GenericUtils.isEmpty(prvEncryption) || NO_PRIVATE_KEY_ENCRYPTION_VALUE.equalsIgnoreCase(prvEncryption) || GenericUtils.isEmpty(password)) { return loadKeyPairs(resourceKey, pubBytes, prvBytes); } // format is "<cipher><bits>-<mode>" - e.g., "aes256-cbc" int pos = prvEncryption.indexOf('-'); if (pos <= 0) { throw new StreamCorruptedException("Missing private key encryption mode in " + prvEncryption); } String mode = prvEncryption.substring(pos + 1).toUpperCase(); String algName = null; int numBits = 0; for (int index = 0; index < pos; index++) { char ch = prvEncryption.charAt(index); if ((ch >= '0') && (ch <= '9')) { algName = prvEncryption.substring(0, index).toUpperCase(); numBits = Integer.parseInt(prvEncryption.substring(index, pos)); break; } } if (GenericUtils.isEmpty(algName) || (numBits <= 0)) { throw new StreamCorruptedException( "Missing private key encryption algorithm details in " + prvEncryption); } prvBytes = PuttyKeyPairResourceParser.decodePrivateKeyBytes( prvBytes, algName, numBits, mode, password); return loadKeyPairs(resourceKey, pubBytes, prvBytes); }