Java Code Examples for org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter#getPrivateKey()
The following examples show how to use
org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter#getPrivateKey() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSLFactory.java From ts-reaktive with MIT License | 6 votes |
/** * Reads a base64-format PEM key and returns a Java PrivateKey for it. * @param privateKey PEM-encoded private key */ public static PrivateKey readPrivateKey(String privateKey) { try (StringReader keyReader = new StringReader(privateKey); PEMParser pemReader = new PEMParser(keyReader)) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); Object keyPair = pemReader.readObject(); if (keyPair instanceof PrivateKeyInfo) { return converter.getPrivateKey((PrivateKeyInfo) keyPair); } else { return converter.getPrivateKey(((PEMKeyPair) keyPair).getPrivateKeyInfo()); } } catch (IOException x) { // Shouldn't occur, since we're only reading from strings throw new RuntimeException(x); } }
Example 2
Source File: BasicKeyStore.java From env-keystore with MIT License | 6 votes |
protected static PrivateKey getPrivateKeyFromPEM(final Reader keyReader) throws IOException { final JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter(); final PEMParser pem = new PEMParser(keyReader); PrivateKey key; Object pemContent = pem.readObject(); if (pemContent instanceof PEMKeyPair) { PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent; KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair); key = keyPair.getPrivate(); } else if (pemContent instanceof PrivateKeyInfo) { PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent; key = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo); } else { throw new IllegalArgumentException("Unsupported private key format '" + pemContent.getClass().getSimpleName() + '"'); } pem.close(); return key; }
Example 3
Source File: PrivateKeyConverter.java From jlogstash-input-plugin with Apache License 2.0 | 6 votes |
private PrivateKey loadKeyPair() throws IOException { PEMParser reader = new PEMParser(file); Object pemObject; JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); //PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(passphrase); while((pemObject = reader.readObject()) != null) { logger.debug("PemObject type: " + pemObject.getClass().getName()); if(pemObject instanceof PEMKeyPair) { logger.debug("it match"); PrivateKeyInfo pki = ((PEMKeyPair) pemObject).getPrivateKeyInfo(); logger.debug("content: " + pki.getEncoded("UTF-8")); return converter.getPrivateKey(pki); } else { logger.debug("Dont match"); } } logger.debug("fsdfsfs"); return null; }
Example 4
Source File: DKIMSign.java From james-project with Apache License 2.0 | 6 votes |
private PrivateKey extractPrivateKey(InputStream rawKey, char[] passphrase) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); try (InputStreamReader pemReader = new InputStreamReader(rawKey)) { try (PEMParser pemParser = new PEMParser(pemReader)) { Object pemObject = pemParser.readObject(); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); KeyPair keyPair; if (pemObject instanceof PrivateKeyInfo) { return converter.getPrivateKey((PrivateKeyInfo)pemObject); } if (pemObject instanceof PEMEncryptedKeyPair) { PEMEncryptedKeyPair pemEncryptedKeyPair = (PEMEncryptedKeyPair) pemObject; PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase); keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv)); } else { keyPair = converter.getKeyPair((PEMKeyPair) pemObject); } KeyFactory keyFac = KeyFactory.getInstance("RSA"); RSAPrivateCrtKeySpec privateKeySpec = keyFac.getKeySpec(keyPair.getPrivate(), RSAPrivateCrtKeySpec.class); return keyFac.generatePrivate(privateKeySpec); } } }
Example 5
Source File: KafkaClientKeystores.java From kafka-helmsman with MIT License | 5 votes |
/** * Create a keystore that serves the private key under the alias "client", where the key has the given certificate * and associated Certificate Authority (CA) chain. * * @param privateKey private key for the client. * @param certificate certificate verifying the private key, provided by the CA. * @param caChain chain of certificates for the CA back to the root * @return a keystore for the private key + chain of certificates */ public KeyStore createKeystore(InputStream privateKey, InputStream certificate, InputStream caChain) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { // initialize the keystore KeyStore ks = KeyStore.getInstance(JAVA_KEYSTORE); // need to load to initialize the keystore for use ks.load(null, password); // read the private key PEMParser parser = new PEMParser(new InputStreamReader(privateKey)); Object key = parser.readObject(); if (key instanceof PEMKeyPair) { key = ((PEMKeyPair) key).getPrivateKeyInfo(); } // either it was a key pair, in which case we got the private key, or it already was an unencrypted PEM private // key, so we can use it directly. We don't understand anything else. if (!(key instanceof PrivateKeyInfo)) { throw new IllegalArgumentException("Expected an RSA/DSA/ECDSA or an unencrypted PEM type key, but got a " + key); } JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BOUNCY_CASTLE_TYPE); PrivateKey pk = converter.getPrivateKey((PrivateKeyInfo) key); // build the certificate chain for the key List<X509Certificate> chain = readCertificateChain(certFactory, certificate); chain.addAll(readCertificateChain(certFactory, caChain)); ks.setKeyEntry(CLIENT_KEY_NAME, pk, password, chain.toArray(EMPTY_CERTS)); return ks; }
Example 6
Source File: EncryptionUtils.java From snowflake-kafka-connector with Apache License 2.0 | 5 votes |
public static PrivateKey parseEncryptedPrivateKey(String key, String passphrase) { //remove header, footer, and line breaks key = key.replaceAll("-+[A-Za-z ]+-+", ""); key = key.replaceAll("\\s", ""); StringBuilder builder = new StringBuilder(); builder.append("-----BEGIN ENCRYPTED PRIVATE KEY-----"); for (int i = 0; i < key.length(); i++) { if (i % 64 == 0) { builder.append("\n"); } builder.append(key.charAt(i)); } builder.append("\n-----END ENCRYPTED PRIVATE KEY-----"); key = builder.toString(); Security.addProvider(new BouncyCastleFipsProvider()); try { PEMParser pemParser = new PEMParser(new StringReader(key)); PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject(); pemParser.close(); InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase.toCharArray()); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleFipsProvider.PROVIDER_NAME); PrivateKeyInfo decryptedPrivateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(pkcs8Prov); return converter.getPrivateKey(decryptedPrivateKeyInfo); } catch (Exception e) { throw SnowflakeErrors.ERROR_0018.getException(e); } }
Example 7
Source File: AadAuthenticationHelperTest.java From azure-kusto-java with MIT License | 5 votes |
static KeyCert readPem(String path, String password) throws IOException, CertificateException, OperatorCreationException, PKCSException { Security.addProvider(new BouncyCastleProvider()); PEMParser pemParser = new PEMParser(new FileReader(new File(path))); PrivateKey privateKey = null; X509Certificate cert = null; Object object = pemParser.readObject(); while (object != null) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); if (object instanceof X509CertificateHolder) { cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object); } if (object instanceof PKCS8EncryptedPrivateKeyInfo) { PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object; InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray()); PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider); privateKey = converter.getPrivateKey(info); } if (object instanceof PrivateKeyInfo) { privateKey = converter.getPrivateKey((PrivateKeyInfo) object); } object = pemParser.readObject(); } KeyCert keycert = new KeyCert(null, null); keycert.setCertificate(cert); keycert.setKey(privateKey); pemParser.close(); return keycert; }
Example 8
Source File: AccessTokenRetrieverServiceImpl.java From okta-sdk-java with Apache License 2.0 | 5 votes |
/** * Get Private key from input PEM file. * * @param reader * @return {@link PrivateKey} * @throws IOException */ PrivateKey getPrivateKeyFromPEM(Reader reader) throws IOException { PrivateKey privateKey; try (PEMParser pemParser = new PEMParser(reader)) { JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter(); Object pemContent = pemParser.readObject(); if (pemContent == null) { throw new IllegalArgumentException("Invalid Private Key PEM file"); } if (pemContent instanceof PEMKeyPair) { PEMKeyPair pemKeyPair = (PEMKeyPair) pemContent; KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair); privateKey = keyPair.getPrivate(); } else if (pemContent instanceof PrivateKeyInfo) { PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemContent; privateKey = jcaPEMKeyConverter.getPrivateKey(privateKeyInfo); } else { throw new IllegalArgumentException("Unsupported Private Key format '" + pemContent.getClass().getSimpleName() + '"'); } } return privateKey; }
Example 9
Source File: AzureKeyVaultClientAuthenticator.java From ranger with Apache License 2.0 | 5 votes |
private KeyCert readPem(String path, String password) throws IOException, CertificateException, OperatorCreationException, PKCSException { Security.addProvider(new BouncyCastleProvider()); PEMParser pemParser = new PEMParser(new FileReader(new File(path))); PrivateKey privateKey = null; X509Certificate cert = null; Object object = pemParser.readObject(); while (object != null) { JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); if (object instanceof X509CertificateHolder) { cert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) object); } if (object instanceof PKCS8EncryptedPrivateKeyInfo) { PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) object; InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password.toCharArray()); PrivateKeyInfo info = pinfo.decryptPrivateKeyInfo(provider); privateKey = converter.getPrivateKey(info); } if (object instanceof PrivateKeyInfo) { privateKey = converter.getPrivateKey((PrivateKeyInfo) object); } object = pemParser.readObject(); } KeyCert keycert = new KeyCert(); keycert.setCertificate(cert); keycert.setKey(privateKey); pemParser.close(); return keycert; }
Example 10
Source File: DefaultQCloudClient.java From wakeup-qcloud-sdk with Apache License 2.0 | 4 votes |
@Override public String getUserSig(String identifier, long expire)throws QCloudException { try { Security.addProvider(new BouncyCastleProvider()); Reader reader = new CharArrayReader(imConfig.getPrivateKey().toCharArray()); JcaPEMKeyConverter converter = new JcaPEMKeyConverter(); PEMParser parser = new PEMParser(reader); Object obj = parser.readObject(); parser.close(); PrivateKey privKeyStruct = converter.getPrivateKey((PrivateKeyInfo) obj); String jsonString = "{" + "\"TLS.account_type\":\"" + 0 +"\"," +"\"TLS.identifier\":\"" + identifier +"\"," +"\"TLS.appid_at_3rd\":\"" + 0 +"\"," +"\"TLS.sdk_appid\":\"" + imConfig.getSdkAppId() +"\"," +"\"TLS.expire_after\":\"" + expire +"\"" // +"\"TLS.version\": \"201512300000\"" +"}"; String time = String.valueOf(System.currentTimeMillis()/1000); String SerialString = "TLS.appid_at_3rd:" + 0 + "\n" + "TLS.account_type:" + 0 + "\n" + "TLS.identifier:" + identifier + "\n" + "TLS.sdk_appid:" + imConfig.getSdkAppId() + "\n" + "TLS.time:" + time + "\n" + "TLS.expire_after:" + expire +"\n"; //Create Signature by SerialString Signature signature = Signature.getInstance("SHA256withECDSA", "BC"); signature.initSign(privKeyStruct); signature.update(SerialString.getBytes(Charset.forName("UTF-8"))); byte[] signatureBytes = signature.sign(); String sigTLS = Base64.encodeBase64String(signatureBytes); //Add TlsSig to jsonString JSONObject jsonObject= JSON.parseObject(jsonString); jsonObject.put("TLS.sig", (Object)sigTLS); jsonObject.put("TLS.time", (Object)time); jsonString = jsonObject.toString(); //compression Deflater compresser = new Deflater(); compresser.setInput(jsonString.getBytes(Charset.forName("UTF-8"))); compresser.finish(); byte [] compressBytes = new byte [512]; int compressBytesLength = compresser.deflate(compressBytes); compresser.end(); return new String(Base64Url.base64EncodeUrl(Arrays.copyOfRange(compressBytes,0,compressBytesLength))); }catch (Exception e) { throw new QCloudException(e); } }
Example 11
Source File: Utils.java From athenz with Apache License 2.0 | 4 votes |
/** * Create a {@link KeyStore} from suppliers of {@link InputStream} for cert and key. * * @param athenzPublicCertInputStream Supplier of the certificate input stream * @param athenzPublicCertLocationSupplier Supplier of the location of the certificate (for error logging) * @param athenzPrivateKeyInputStream Supplier of the private key input stream * @param athenzPrivateKeyLocationSupplier Supplier of the location of the certificate (for error logging) * @return a KeyStore with loaded key and certificate * @throws IOException * @throws KeyRefresherException */ public static KeyStore createKeyStore( final Supplier<InputStream> athenzPublicCertInputStream, final Supplier<String> athenzPublicCertLocationSupplier, final Supplier<InputStream> athenzPrivateKeyInputStream, final Supplier<String> athenzPrivateKeyLocationSupplier) throws IOException, KeyRefresherException { List<? extends Certificate> certificates; PrivateKey privateKey; KeyStore keyStore = null; try (InputStream publicCertStream = athenzPublicCertInputStream.get(); InputStream privateKeyStream = athenzPrivateKeyInputStream.get(); PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter(); Object key = pemParser.readObject(); if (key instanceof PEMKeyPair) { PrivateKeyInfo pKeyInfo = ((PEMKeyPair) key).getPrivateKeyInfo(); privateKey = pemConverter.getPrivateKey(pKeyInfo); } else if (key instanceof PrivateKeyInfo) { privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) key); } else { throw new KeyRefresherException("Unknown object type: " + key.getClass().getName()); } //noinspection unchecked certificates = (List<? extends Certificate>) cf.generateCertificates(publicCertStream); if (certificates.isEmpty()) { throw new KeyRefresherException("Certificate file contains empty certificate or an invalid certificate."); } //We are going to assume that the first one is the main certificate which will be used for the alias String alias = ((X509Certificate) certificates.get(0)).getSubjectX500Principal().getName(); if (LOG.isDebugEnabled()) { LOG.debug("{} number of certificates found. Using {} alias to create the keystore", certificates.size(), alias); } keyStore = KeyStore.getInstance(DEFAULT_KEYSTORE_TYPE); keyStore.load(null); keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD, certificates.toArray((Certificate[]) new X509Certificate[certificates.size()])); } catch (CertificateException | NoSuchAlgorithmException e) { String keyStoreFailMsg = "Unable to load " + athenzPublicCertLocationSupplier.get() + " as a KeyStore. Please check the validity of the file."; throw new KeyRefresherException(keyStoreFailMsg, e); } catch (KeyStoreException ignored) { LOG.error("No Provider supports a KeyStoreSpi implementation for the specified type.", ignored); } return keyStore; }
Example 12
Source File: CertificateManager.java From Openfire with Apache License 2.0 | 4 votes |
/** * Parses a PrivateKey instance from a PEM representation. * * When the provided key is encrypted, the provided pass phrase is applied. * * @param pemRepresentation a PEM representation of a private key (cannot be null or empty) * @param passPhrase optional pass phrase (must be present if the private key is encrypted). * @return a PrivateKey instance (never null) * @throws IOException if there was a problem parsing the key */ public static PrivateKey parsePrivateKey(InputStream pemRepresentation, String passPhrase) throws IOException { if ( passPhrase == null ) { passPhrase = ""; } try (Reader reader = new InputStreamReader(pemRepresentation); // PEMParser pemParser = new PEMParser(reader)) { final Object object = pemParser.readObject(); final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider( "BC" ); final KeyPair kp; if ( object instanceof PEMEncryptedKeyPair ) { // Encrypted key - we will use provided password final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build( passPhrase.toCharArray() ); kp = converter.getKeyPair( ( (PEMEncryptedKeyPair) object ).decryptKeyPair( decProv ) ); } else if ( object instanceof PKCS8EncryptedPrivateKeyInfo ) { // Encrypted key - we will use provided password try { final PKCS8EncryptedPrivateKeyInfo encryptedInfo = (PKCS8EncryptedPrivateKeyInfo) object; final InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build( passPhrase.toCharArray() ); final PrivateKeyInfo privateKeyInfo = encryptedInfo.decryptPrivateKeyInfo( provider ); return converter.getPrivateKey( privateKeyInfo ); } catch ( PKCSException | OperatorCreationException e ) { throw new IOException( "Unable to decrypt private key.", e ); } } else if ( object instanceof PrivateKeyInfo ) { return converter.getPrivateKey( (PrivateKeyInfo) object ); } else { // Unencrypted key - no password needed kp = converter.getKeyPair( (PEMKeyPair) object ); } return kp.getPrivate(); } }