1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
| final class PemUtils {
private static final String PKCS1_HEADER = "-----BEGIN RSA PRIVATE KEY-----"; private static final String PKCS1_FOOTER = "-----END RSA PRIVATE KEY-----"; private static final String OPENSSL_DSA_HEADER = "-----BEGIN DSA PRIVATE KEY-----"; private static final String OPENSSL_DSA_FOOTER = "-----END DSA PRIVATE KEY-----"; private static final String OPENSSL_DSA_PARAMS_HEADER = "-----BEGIN DSA PARAMETERS-----"; private static final String OPENSSL_DSA_PARAMS_FOOTER = "-----END DSA PARAMETERS-----"; private static final String PKCS8_HEADER = "-----BEGIN PRIVATE KEY-----"; private static final String PKCS8_FOOTER = "-----END PRIVATE KEY-----"; private static final String PKCS8_ENCRYPTED_HEADER = "-----BEGIN ENCRYPTED PRIVATE KEY-----"; private static final String PKCS8_ENCRYPTED_FOOTER = "-----END ENCRYPTED PRIVATE KEY-----"; private static final String OPENSSL_EC_HEADER = "-----BEGIN EC PRIVATE KEY-----"; private static final String OPENSSL_EC_FOOTER = "-----END EC PRIVATE KEY-----"; private static final String OPENSSL_EC_PARAMS_HEADER = "-----BEGIN EC PARAMETERS-----"; private static final String OPENSSL_EC_PARAMS_FOOTER = "-----END EC PARAMETERS-----"; private static final String HEADER = "-----BEGIN";
private PemUtils() { throw new IllegalStateException("Utility class should not be instantiated"); }
static PrivateKey readPrivateKey(Path keyPath, Supplier<char[]> passwordSupplier) { try (BufferedReader bReader = Files.newBufferedReader(keyPath, StandardCharsets.UTF_8)) { String line = bReader.readLine(); while (null != line && !line.startsWith(HEADER)) { line = bReader.readLine(); } if (null == line) { throw new SslConfigException( "Error parsing Private Key [" + keyPath.toAbsolutePath() + "], file is empty"); } switch (line.trim()) { case PKCS8_ENCRYPTED_HEADER: char[] password = passwordSupplier.get(); if (password == null) { throw new SslConfigException( "cannot read encrypted key [" + keyPath.toAbsolutePath() + "] " + "without a password"); } return parsePKCS8Encrypted(bReader, password); case PKCS8_HEADER: return parsePKCS8(bReader); case PKCS1_HEADER: return parsePKCS1Rsa(bReader, passwordSupplier); case OPENSSL_DSA_HEADER: return parseOpenSslDsa(bReader, passwordSupplier); case OPENSSL_DSA_PARAMS_HEADER: return parseOpenSslDsa(removeDsaHeaders(bReader), passwordSupplier); case OPENSSL_EC_HEADER: return parseOpenSslEC(bReader, passwordSupplier); case OPENSSL_EC_PARAMS_HEADER: return parseOpenSslEC(removeECHeaders(bReader), passwordSupplier); default: throw new SslConfigException( "error parsing Private Key [" + keyPath.toAbsolutePath() + "], file " + "does not contain a supported key format"); } } catch (FileNotFoundException | NoSuchFileException e) { throw new SslConfigException( "private key file [" + keyPath.toAbsolutePath() + "] does not exist", e); } catch (IOException | GeneralSecurityException e) { throw new SslConfigException( "private key file [" + keyPath.toAbsolutePath() + "] cannot be parsed", e); } }
private static BufferedReader removeECHeaders(BufferedReader bReader) throws IOException { String line = bReader.readLine(); while (line != null) { if (OPENSSL_EC_PARAMS_FOOTER.equals(line.trim())) { break; } line = bReader.readLine(); } if (null == line) { throw new IOException("Malformed PEM file, EC Parameters footer is missing"); } if (!OPENSSL_EC_HEADER.equals(bReader.readLine())) { throw new IOException("Malformed PEM file, EC Key header is missing"); } return bReader; }
private static BufferedReader removeDsaHeaders(BufferedReader bReader) throws IOException { String line = bReader.readLine(); while (line != null) { if (OPENSSL_DSA_PARAMS_FOOTER.equals(line.trim())) { break; } line = bReader.readLine(); } if (null == line) { throw new IOException("Malformed PEM file, DSA Parameters footer is missing"); } if (!OPENSSL_DSA_HEADER.equals(bReader.readLine())) { throw new IOException("Malformed PEM file, DSA Key header is missing"); } return bReader; }
private static PrivateKey parsePKCS8(BufferedReader bReader) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); while (line != null) { if (PKCS8_FOOTER.equals(line.trim())) { break; } sb.append(line.trim()); line = bReader.readLine(); } if (null == line) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = Base64.getDecoder().decode(sb.toString()); String keyAlgo = getKeyAlgorithmIdentifier(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(keyAlgo); return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); }
private static PrivateKey parseOpenSslEC( BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>(); while (line != null) { if (OPENSSL_EC_FOOTER.equals(line.trim())) { break; } if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); KeyFactory keyFactory = KeyFactory.getInstance("EC"); ECPrivateKeySpec ecSpec = parseEcDer(keyBytes); return keyFactory.generatePrivate(ecSpec); }
private static PrivateKey parsePKCS1Rsa( BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>();
while (line != null) { if (PKCS1_FOOTER.equals(line.trim())) { break; } if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); RSAPrivateCrtKeySpec spec = parseRsaDer(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(spec); }
private static PrivateKey parseOpenSslDsa( BufferedReader bReader, Supplier<char[]> passwordSupplier) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); Map<String, String> pemHeaders = new HashMap<>();
while (line != null) { if (OPENSSL_DSA_FOOTER.equals(line.trim())) { break; } if (line.contains(":")) { String[] header = line.split(":"); pemHeaders.put(header[0].trim(), header[1].trim()); } else { sb.append(line.trim()); } line = bReader.readLine(); } if (null == line) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = possiblyDecryptPKCS1Key(pemHeaders, sb.toString(), passwordSupplier); DSAPrivateKeySpec spec = parseDsaDer(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); return keyFactory.generatePrivate(spec); }
private static PrivateKey parsePKCS8Encrypted(BufferedReader bReader, char[] keyPassword) throws IOException, GeneralSecurityException { StringBuilder sb = new StringBuilder(); String line = bReader.readLine(); while (line != null) { if (PKCS8_ENCRYPTED_FOOTER.equals(line.trim())) { break; } sb.append(line.trim()); line = bReader.readLine(); } if (null == line) { throw new IOException("Malformed PEM file, PEM footer is invalid or missing"); } byte[] keyBytes = Base64.getDecoder().decode(sb.toString());
EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(keyBytes); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName()); SecretKey secretKey = secretKeyFactory.generateSecret(new PBEKeySpec(keyPassword)); Arrays.fill(keyPassword, '\u0000'); Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, secretKey, encryptedPrivateKeyInfo.getAlgParameters()); PKCS8EncodedKeySpec keySpec = encryptedPrivateKeyInfo.getKeySpec(cipher); String keyAlgo = getKeyAlgorithmIdentifier(keySpec.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance(keyAlgo); return keyFactory.generatePrivate(keySpec); }
private static byte[] possiblyDecryptPKCS1Key( Map<String, String> pemHeaders, String keyContents, Supplier<char[]> passwordSupplier) throws GeneralSecurityException, IOException { byte[] keyBytes = Base64.getDecoder().decode(keyContents); String procType = pemHeaders.get("Proc-Type"); if ("4,ENCRYPTED".equals(procType)) { String encryptionParameters = pemHeaders.get("DEK-Info"); if (null == encryptionParameters) { throw new IOException("Malformed PEM File, DEK-Info header is missing"); } char[] password = passwordSupplier.get(); if (password == null) { throw new IOException("cannot read encrypted key without a password"); } Cipher cipher = getCipherFromParameters(encryptionParameters, password); return cipher.doFinal(keyBytes); } return keyBytes; }
private static Cipher getCipherFromParameters(String dekHeaderValue, char[] password) throws GeneralSecurityException, IOException { final String padding = "PKCS5Padding"; final SecretKey encryptionKey; final String[] valueTokens = dekHeaderValue.split(","); if (valueTokens.length != 2) { throw new IOException("Malformed PEM file, DEK-Info PEM header is invalid"); } final String algorithm = valueTokens[0]; final String ivString = valueTokens[1]; final byte[] iv; try { iv = hexStringToByteArray(ivString); } catch (IllegalArgumentException e) { throw new IOException("Malformed PEM file, DEK-Info IV is invalid", e); } if ("DES-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 8); encryptionKey = new SecretKeySpec(key, "DES"); } else if ("DES-EDE3-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 24); encryptionKey = new SecretKeySpec(key, "DESede"); } else if ("AES-128-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 16); encryptionKey = new SecretKeySpec(key, "AES"); } else if ("AES-192-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 24); encryptionKey = new SecretKeySpec(key, "AES"); } else if ("AES-256-CBC".equals(algorithm)) { byte[] key = generateOpenSslKey(password, iv, 32); encryptionKey = new SecretKeySpec(key, "AES"); } else { throw new GeneralSecurityException( "Private Key encrypted with unsupported algorithm [" + algorithm + "]"); } String transformation = encryptionKey.getAlgorithm() + "/" + "CBC" + "/" + padding; Cipher cipher = Cipher.getInstance(transformation); cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv)); return cipher; }
private static byte[] generateOpenSslKey(char[] password, byte[] salt, int keyLength) { byte[] passwordBytes = toUtf8Bytes(password); try { MessageDigest md5 = MessageDigest.getInstance("md5"); byte[] key = new byte[keyLength]; int copied = 0; int remaining; while (copied < keyLength) { remaining = keyLength - copied; md5.update(passwordBytes, 0, passwordBytes.length); md5.update(salt, 0, 8); byte[] tempDigest = md5.digest(); int bytesToCopy = Math.min(remaining, 16); System.arraycopy(tempDigest, 0, key, copied, bytesToCopy); copied += bytesToCopy; if (remaining == 0) { break; } md5.update(tempDigest, 0, 16); } Arrays.fill(passwordBytes, (byte) 0); return key; } catch (NoSuchAlgorithmException e) { throw new SslConfigException( "unexpected exception creating MessageDigest instance for [md5]", e); } }
public static byte[] toUtf8Bytes(char[] chars) { final CharBuffer charBuffer = CharBuffer.wrap(chars); final ByteBuffer byteBuffer = StandardCharsets.UTF_8.encode(charBuffer); final byte[] bytes; if (byteBuffer.hasArray()) { bytes = Arrays.copyOfRange( byteBuffer.array(), byteBuffer.position(), byteBuffer.limit()); Arrays.fill(byteBuffer.array(), (byte) 0); } else { final int length = byteBuffer.limit() - byteBuffer.position(); bytes = new byte[length]; byteBuffer.get(bytes); if (!byteBuffer.isReadOnly()) { byteBuffer.clear(); for (int i = 0; i < byteBuffer.limit(); i++) { byteBuffer.put((byte) 0); } } } return bytes; }
private static byte[] hexStringToByteArray(String hexString) { int len = hexString.length(); if (len % 2 == 0) { byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { final int k = Character.digit(hexString.charAt(i), 16); final int l = Character.digit(hexString.charAt(i + 1), 16); if (k == -1 || l == -1) { throw new IllegalStateException( "String [" + hexString + "] is not hexadecimal"); } data[i / 2] = (byte) ((k << 4) + l); } return data; } else { throw new IllegalStateException( "Hexadecimal string [" + hexString + "] has odd length and cannot be converted to a byte array"); } }
private static ECPrivateKeySpec parseEcDer(byte[] keyBytes) throws IOException, GeneralSecurityException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); String keyHex = parser.readAsn1Object().getString(); BigInteger privateKeyInt = new BigInteger(keyHex, 16); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); AlgorithmParameterSpec prime256v1ParamSpec = new ECGenParameterSpec("secp256r1"); keyPairGenerator.initialize(prime256v1ParamSpec); ECParameterSpec parameterSpec = ((ECKey) keyPairGenerator.generateKeyPair().getPrivate()).getParams(); return new ECPrivateKeySpec(privateKeyInt, parameterSpec); }
private static RSAPrivateCrtKeySpec parseRsaDer(byte[] keyBytes) throws IOException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object() .getInteger(); BigInteger modulus = parser.readAsn1Object().getInteger(); BigInteger publicExponent = parser.readAsn1Object().getInteger(); BigInteger privateExponent = parser.readAsn1Object().getInteger(); BigInteger prime1 = parser.readAsn1Object().getInteger(); BigInteger prime2 = parser.readAsn1Object().getInteger(); BigInteger exponent1 = parser.readAsn1Object().getInteger(); BigInteger exponent2 = parser.readAsn1Object().getInteger(); BigInteger coefficient = parser.readAsn1Object().getInteger(); return new RSAPrivateCrtKeySpec( modulus, publicExponent, privateExponent, prime1, prime2, exponent1, exponent2, coefficient); }
private static DSAPrivateKeySpec parseDsaDer(byte[] keyBytes) throws IOException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object() .getInteger(); BigInteger p = parser.readAsn1Object().getInteger(); BigInteger q = parser.readAsn1Object().getInteger(); BigInteger g = parser.readAsn1Object().getInteger(); parser.readAsn1Object().getInteger(); BigInteger x = parser.readAsn1Object().getInteger(); return new DSAPrivateKeySpec(x, p, q, g); }
private static String getKeyAlgorithmIdentifier(byte[] keyBytes) throws IOException, GeneralSecurityException { DerParser parser = new DerParser(keyBytes); DerParser.Asn1Object sequence = parser.readAsn1Object(); parser = sequence.getParser(); parser.readAsn1Object().getInteger(); DerParser.Asn1Object algSequence = parser.readAsn1Object(); parser = algSequence.getParser(); String oidString = parser.readAsn1Object().getOid(); switch (oidString) { case "1.2.840.10040.4.1": return "DSA"; case "1.2.840.113549.1.1.1": return "RSA"; case "1.2.840.10045.2.1": return "EC"; } throw new GeneralSecurityException( "Error parsing key algorithm identifier. Algorithm with OID [" + oidString + "] is not supported"); }
static List<Certificate> readCertificates(Collection<Path> certPaths) throws CertificateException, IOException { CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); List<Certificate> certificates = new ArrayList<>(certPaths.size()); for (Path path : certPaths) { try (InputStream input = Files.newInputStream(path)) { final Collection<? extends Certificate> parsed = certFactory.generateCertificates(input); if (parsed.isEmpty()) { throw new SslConfigException( "failed to parse any certificates from [" + path.toAbsolutePath() + "]"); } certificates.addAll(parsed); } } return certificates; } }
|