org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter Java Examples

The following examples show how to use org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter. 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: CertUtil.java    From littleca with Apache License 2.0 7 votes vote down vote up
/**
 * 密文pem格式私钥读取
 *
 * @param privateKeyPemPath
 * @param password
 * @return
 * @throws Exception
 */
public static PrivateKey readPrivateKeyPem(String privateKeyPemPath, String password) throws CertException {
    try {
        if (null == password) {
            throw new CertException("password can't be null ");
        }
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(privateKeyPemPath)));
        Object readObject = pemParser.readObject();
        if (readObject instanceof PEMEncryptedKeyPair) {
            PEMEncryptedKeyPair keyPair = (PEMEncryptedKeyPair) readObject;
            PEMDecryptorProvider keyDecryptorProvider = new BcPEMDecryptorProvider(password.toCharArray());
            PEMKeyPair decryptKeyPair = keyPair.decryptKeyPair(keyDecryptorProvider);
            return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getKeyPair(decryptKeyPair).getPrivate();
        }
        throw new CertException("read privateKey failed");
    } catch (Exception e) {
        throw new CertException("read privateKey failed", e);
    }
}
 
Example #2
Source File: PrivateKeyProvider.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
/**
 * Load private key from classpath.
 *
 * @param filename Name of the key file. Suffix should be .key
 * @return PrivateKey
 */
public PrivateKey getKeyFromClassPath(String filename) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    InputStream stream = loader.getResourceAsStream("certificates/" + filename);
    if (stream == null) {
        throw new CertificateException("Could not read private key from classpath:" + "certificates/" + filename);
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    try {
        Security.addProvider(new BouncyCastleProvider());
        PEMParser pp = new PEMParser(br);
        PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
        pp.close();
        return kp.getPrivate();
    } catch (IOException ex) {
        throw new CertificateException("Could not read private key from classpath", ex);
    }
}
 
Example #3
Source File: GPCrypto.java    From GlobalPlatformPro with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static PublicKey pem2PublicKey(InputStream in) throws IOException {
    try (PEMParser pem = new PEMParser(new InputStreamReader(in, StandardCharsets.US_ASCII))) {
        Object ohh = pem.readObject();
        if (ohh instanceof PEMKeyPair) {
            PEMKeyPair kp = (PEMKeyPair) ohh;
            return new JcaPEMKeyConverter().getKeyPair(kp).getPublic();
        } else if (ohh instanceof SubjectPublicKeyInfo) {
            return new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) ohh);
        } else if (ohh instanceof X509CertificateHolder) {
            X509CertificateHolder certHolder = (X509CertificateHolder) ohh;
            try {
                return new JcaX509CertificateConverter().getCertificate(certHolder).getPublicKey();
            } catch (CertificateException ce) {
                throw new IllegalArgumentException("Can not read PEM: " + ce.getMessage());
            }
        } else throw new IllegalArgumentException("Can not read PEM");
    }
}
 
Example #4
Source File: CertificateUtils.java    From docker-java with Apache License 2.0 6 votes vote down vote up
/**
 * Return private key ("key.pem") from Reader
 */
@CheckForNull
public static PrivateKey loadPrivateKey(final Reader reader) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException {
    try (PEMParser pemParser = new PEMParser(reader)) {
        Object readObject = pemParser.readObject();
        while (readObject != null) {
            PrivateKeyInfo privateKeyInfo = getPrivateKeyInfoOrNull(readObject);
            if (privateKeyInfo != null) {
                return new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
            }
            readObject = pemParser.readObject();
        }
    }

    return null;
}
 
Example #5
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static PrivateKey handleECKey(InputStream keyInputStream) throws IOException {
  // Let's wrap the code to a callable inner class to avoid NoClassDef when loading this class.
  try {
    return new Callable<PrivateKey>() {
      @Override
      public PrivateKey call() {
        try {
          if (Security.getProvider("BC") == null) {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
          }
          PEMKeyPair keys = (PEMKeyPair) new PEMParser(new InputStreamReader(keyInputStream)).readObject();
          return new
            JcaPEMKeyConverter().
            getKeyPair(keys).
            getPrivate();
        } catch (IOException exception) {
          exception.printStackTrace();
        }
        return null;
      }
    }.call();
  } catch (NoClassDefFoundError e) {
    throw new KubernetesClientException("JcaPEMKeyConverter is provided by BouncyCastle, an optional dependency. To use support for EC Keys you must explicitly add this dependency to classpath.");
  }
}
 
Example #6
Source File: DKIMSign.java    From james-project with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: OpenSslPubUtil.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Load an unencrypted OpenSSL public key from the stream. The encoding of
 * the public key may be PEM or DER.
 *
 * @param pkData BA to load the unencrypted public key from
 * @return The public key
 * @throws CryptoException
 *             Problem encountered while loading the public key
 * @throws IOException
 *             An I/O error occurred
 */
public static PublicKey load(byte[] pkData) throws CryptoException, IOException {

	// Check if stream is PEM encoded
	PemInfo pemInfo = PemUtil.decode(pkData);

	if (pemInfo != null) {
		// It is - get DER from PEM
		pkData = pemInfo.getContent();
	}

	try {
		// DER-encoded subjectPublicKeyInfo structure - the OpenSSL format
		SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(pkData);
		return new JcaPEMKeyConverter().getPublicKey(publicKeyInfo);
	} catch (Exception ex) {
		throw new CryptoException(res.getString("NoLoadOpenSslPublicKey.exception.message"), ex);
	}
}
 
Example #8
Source File: JwtCreatorCallout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 6 votes vote down vote up
private static PrivateKey generatePrivateKey(PrivateKeyInfo info)
    throws InvalidKeySpecException, GeneralSecurityException, NoSuchAlgorithmException, IOException, PEMException
{
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
    PEMParser pr = new PEMParser(new StringReader(new String(info.keyBytes, StandardCharsets.UTF_8)));
    Object o = pr.readObject();

    if (o == null || !((o instanceof PEMKeyPair) || (o instanceof PEMEncryptedKeyPair))) {
        throw new IllegalStateException("Didn't find OpenSSL key");
    }
    KeyPair kp;
    if (o instanceof PEMEncryptedKeyPair) {
        JcePEMDecryptorProviderBuilder bcDecProvider = new JcePEMDecryptorProviderBuilder().setProvider("BC");
        char[] charArray = info.password.toCharArray();
        PEMDecryptorProvider decProv = bcDecProvider.build(charArray);
        kp = converter.getKeyPair(((PEMEncryptedKeyPair)o).decryptKeyPair(decProv));
    }
    else {
        kp = converter.getKeyPair((PEMKeyPair)o);
    }

    PrivateKey privKey = kp.getPrivate();
    return privKey;
}
 
Example #9
Source File: CertificateSupplierModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@PemFile
static PrivateKey providePemPrivateKey(@PemFile ImmutableList<Object> pemObjects) {
  JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
  Function<PEMKeyPair, PrivateKey> privateKeyConverter =
      pemKeyPair -> {
        try {
          return converter.getKeyPair(pemKeyPair).getPrivate();
        } catch (PEMException e) {
          throw new RuntimeException(
              String.format("Error converting private key: %s", pemKeyPair), e);
        }
      };
  ImmutableList<PrivateKey> privateKeys =
      filterAndConvert(pemObjects, PEMKeyPair.class, privateKeyConverter);
  checkState(
      privateKeys.size() == 1,
      "The pem file must contain exactly one private key, but %s keys are found",
      privateKeys.size());
  return privateKeys.get(0);
}
 
Example #10
Source File: PrivateKeyConverter.java    From jlogstash-input-plugin with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: BasicKeyStore.java    From env-keystore with MIT License 6 votes vote down vote up
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 #12
Source File: SSLFactory.java    From ts-reaktive with MIT License 6 votes vote down vote up
/**
 * 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 #13
Source File: EntPayServiceImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
private String encryptRSA(File publicKeyFile, String srcString) throws WxPayException {
  try {
    Security.addProvider(new BouncyCastleProvider());
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
    try (PEMParser reader = new PEMParser(new FileReader(publicKeyFile))) {
      final PublicKey publicKey = new JcaPEMKeyConverter().setProvider("BC")
        .getPublicKey((SubjectPublicKeyInfo) reader.readObject());

      cipher.init(Cipher.ENCRYPT_MODE, publicKey);
      byte[] encrypt = cipher.doFinal(srcString.getBytes());
      return Base64.encodeBase64String(encrypt);
    }
  } catch (Exception e) {
    throw new WxPayException("加密出错", e);
  }
}
 
Example #14
Source File: PublicKeyReader.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Optional<PublicKey> publicKeyFrom(PEMParser reader) {
    try {
        Object readPEM = reader.readObject();
        if (readPEM instanceof SubjectPublicKeyInfo) {
            return Optional.of(new JcaPEMKeyConverter().getPublicKey((SubjectPublicKeyInfo) readPEM));
        }
        LOGGER.warn("Key is not an instance of SubjectPublicKeyInfo but of {}", readPEM);
        return Optional.empty();
    } catch (IOException e) {
        LOGGER.warn("Error when reading the PEM file", e);
        return Optional.empty();
    }
}
 
Example #15
Source File: TlsUtils.java    From nomad-java-sdk with Mozilla Public License 2.0 5 votes vote down vote up
private static PrivateKey loadPemKey(final String path) throws IOException {
    try (final FileInputStream in = new FileInputStream(path)) {
        try (final InputStreamReader reader = new InputStreamReader(in, US_ASCII)) {
            try (PEMParser parser = new PEMParser(reader)) {
                Object key = parser.readObject();
                if (key instanceof PEMKeyPair) {
                    return new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) key).getPrivate();
                } else if (key instanceof PrivateKeyInfo) {
                    return new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) key);
                } else throw new IOException("unsupported private key format");
            }
        }
    }
}
 
Example #16
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String extractX509CSRPublicKey(PKCS10CertificationRequest certReq) {

        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        PublicKey publicKey;
        try {
            publicKey = pemConverter.getPublicKey(certReq.getSubjectPublicKeyInfo());
            ///CLOVER:OFF
        } catch (PEMException ex) {
            LOG.error("extractX509CSRPublicKey: unable to get public key: {}", ex.getMessage());
            return null;
        }
        ///CLOVER:ON
        return convertToPEMFormat(publicKey);
    }
 
Example #17
Source File: SslKeyStore.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private static PrivateKey fromPkcs1(byte[] content) throws Exception {
   JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
   converter.setProvider("BC");
   PEMParser pemParser = new PEMParser(new StringReader(new String(content)));

   return converter.getKeyPair((PEMKeyPair) pemParser.readObject()).getPrivate();
}
 
Example #18
Source File: OpenSslPvkUtilTest.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("privateKeys")
public void checkCompatibilityWithBC(PrivateKey privateKey) throws Exception {
	String key = OpenSslPvkUtil.getPem(privateKey);
	try (PEMParser pemParser = new PEMParser(new StringReader(key))) {
		Object obj = pemParser.readObject();
		assertThat(obj).isInstanceOf(PEMKeyPair.class);
		KeyPair keyPair = new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) obj);
		assertThat(keyPair.getPrivate()).isEqualTo(privateKey);
	}
}
 
Example #19
Source File: CsrImpl.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
public CsrImpl(final PKCS10CertificationRequest request) {
  dn = new BcX500NameDnImpl(request.getSubject());
  try {
    publicKey = new JcaPEMKeyConverter().getPublicKey(request.getSubjectPublicKeyInfo());
  } catch (final PEMException e) {
    throw new CaException(e);
  }
}
 
Example #20
Source File: AccessTokenRetrieverServiceImpl.java    From okta-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #21
Source File: EncryptionUtils.java    From snowflake-kafka-connector with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: TlsHelperTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static KeyPair loadKeyPair(Reader reader) throws IOException {
    try (PEMParser pemParser = new PEMParser(reader)) {
        Object object = pemParser.readObject();
        assertEquals(PEMKeyPair.class, object.getClass());
        return new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) object);
    }
}
 
Example #23
Source File: BouncyCastleSecurityProviderTool.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@Override
public PrivateKey decodePemEncodedPrivateKey(Reader privateKeyReader, String password) {
    try (PEMParser pemParser = new PEMParser(privateKeyReader)) {
        Object keyPair = pemParser.readObject();

        // retrieve the PrivateKeyInfo from the returned keyPair object. if the key is encrypted, it needs to be
        // decrypted using the specified password first.
        PrivateKeyInfo keyInfo;
        if (keyPair instanceof PEMEncryptedKeyPair) {
            if (password == null) {
                throw new ImportException("Unable to import private key. Key is encrypted, but no password was provided.");
            }

            PEMDecryptorProvider decryptor = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());

            PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptor);

            keyInfo = decryptedKeyPair.getPrivateKeyInfo();
        } else {
            keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
        }

        return new JcaPEMKeyConverter().getPrivateKey(keyInfo);
    } catch (IOException e) {
        throw new ImportException("Unable to read PEM-encoded PrivateKey", e);
    }
}
 
Example #24
Source File: AzureKeyVaultClientAuthenticator.java    From ranger with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: KafkaClientKeystores.java    From kafka-helmsman with MIT License 5 votes vote down vote up
/**
 * 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 #26
Source File: GPCrypto.java    From GlobalPlatformPro with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static PrivateKey pem2PrivateKey(InputStream in) throws IOException {
    try (PEMParser pem = new PEMParser(new InputStreamReader(in, StandardCharsets.US_ASCII))) {
        Object ohh = pem.readObject();
        if (ohh instanceof PEMKeyPair) {
            PEMKeyPair kp = (PEMKeyPair) ohh;
            return new JcaPEMKeyConverter().getKeyPair(kp).getPrivate();
        } else if (ohh instanceof PrivateKeyInfo) {
            return new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) ohh);
        } else throw new IllegalArgumentException("Can not read PEM");
    }
}
 
Example #27
Source File: NetconfSessionMinaImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Deprecated
private void startSession() throws IOException {
    final ConnectFuture connectFuture;
    connectFuture = client.connect(deviceInfo.name(),
            deviceInfo.ip().toString(),
            deviceInfo.port())
            .verify(connectTimeout, TimeUnit.SECONDS);
    session = connectFuture.getSession();
    //Using the device ssh key if possible
    if (deviceInfo.getKey() != null) {
        try (PEMParser pemParser = new PEMParser(new CharArrayReader(deviceInfo.getKey()))) {
            JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
            try {
                KeyPair kp = converter.getKeyPair((PEMKeyPair) pemParser.readObject());
                session.addPublicKeyIdentity(kp);
            } catch (IOException e) {
                throw new NetconfException("Failed to authenticate session with device " +
                        deviceInfo + "check key to be a valid key", e);
            }
        }
    } else {
        session.addPasswordIdentity(deviceInfo.password());
    }
    session.auth().verify(connectTimeout, TimeUnit.SECONDS);
    Set<ClientSession.ClientSessionEvent> event = session.waitFor(
            ImmutableSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH,
                    ClientSession.ClientSessionEvent.CLOSED,
                    ClientSession.ClientSessionEvent.AUTHED), 0);

    if (!event.contains(ClientSession.ClientSessionEvent.AUTHED)) {
        log.debug("Session closed {} {}", event, session.isClosed());
        throw new NetconfException("Failed to authenticate session with device " +
                deviceInfo + "check the user/pwd or key");
    }
    openChannel();
}
 
Example #28
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static KeyPair fromPrivateKeyPem(String privateKeyContent) {
    BufferedReader br = new BufferedReader(new StringReader(privateKeyContent));
    Security.addProvider(new BouncyCastleProvider());
    try (PEMParser pp = new PEMParser(br)) {
        PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        return new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
    } catch (IOException e) {
        LOGGER.info("Cannot parse KeyPair from private key pem content, skip it. {}", e.getMessage(), e);
    }
    return null;
}
 
Example #29
Source File: TlsHelperTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static KeyPair loadKeyPair(Reader reader) throws IOException {
    try (PEMParser pemParser = new PEMParser(reader)) {
        Object object = pemParser.readObject();
        assertEquals(PEMKeyPair.class, object.getClass());
        return new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) object);
    }
}
 
Example #30
Source File: BouncyCastleSecurityProviderTool.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public PrivateKey decodePemEncodedPrivateKey(Reader privateKeyReader, String password) {
    try (PEMParser pemParser = new PEMParser(privateKeyReader)) {
        Object keyPair = pemParser.readObject();

        // retrieve the PrivateKeyInfo from the returned keyPair object. if the key is encrypted, it needs to be
        // decrypted using the specified password first.
        PrivateKeyInfo keyInfo;
        if (keyPair instanceof PEMEncryptedKeyPair) {
            if (password == null) {
                throw new ImportException("Unable to import private key. Key is encrypted, but no password was provided.");
            }

            PEMDecryptorProvider decryptor = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());

            PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptor);

            keyInfo = decryptedKeyPair.getPrivateKeyInfo();
        } else {
            keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
        }

        return new JcaPEMKeyConverter().getPrivateKey(keyInfo);
    } catch (IOException e) {
        throw new ImportException("Unable to read PEM-encoded PrivateKey", e);
    }
}