Java Code Examples for org.bouncycastle.openssl.PEMParser#readObject()

The following examples show how to use org.bouncycastle.openssl.PEMParser#readObject() . 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: KeyReader.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
public PKCS8EncodedKeySpec readPrivateKey(FileInputStream fis, Optional<String> keyPassword)
        throws IOException {
    PEMParser keyReader = new PEMParser(new InputStreamReader(fis));

    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(keyPassword.get().toCharArray());

    Object keyPair = keyReader.readObject();
    keyReader.close();

    PrivateKeyInfo keyInfo;

    if (keyPair instanceof PEMEncryptedKeyPair) {
        PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptorProvider);
        keyInfo = decryptedKeyPair.getPrivateKeyInfo();
    } else {
        keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
    }

    return new PKCS8EncodedKeySpec(keyInfo.getEncoded());
}
 
Example 4
Source File: KeyReader.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
public PKCS8EncodedKeySpec readPrivateKey(FileInputStream fis, Optional<String> keyPassword)
        throws IOException {
    PEMParser keyReader = new PEMParser(new InputStreamReader(fis));

    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(keyPassword.get().toCharArray());

    Object keyPair = keyReader.readObject();
    keyReader.close();

    PrivateKeyInfo keyInfo;

    if (keyPair instanceof PEMEncryptedKeyPair) {
        PEMKeyPair decryptedKeyPair = ((PEMEncryptedKeyPair) keyPair).decryptKeyPair(decryptorProvider);
        keyInfo = decryptedKeyPair.getPrivateKeyInfo();
    } else {
        keyInfo = ((PEMKeyPair) keyPair).getPrivateKeyInfo();
    }

    return new PKCS8EncodedKeySpec(keyInfo.getEncoded());
}
 
Example 5
Source File: CertificateSupplierModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@PemFile
static ImmutableList<Object> providePemObjects(@Named("pemBytes") byte[] pemBytes) {
  PEMParser pemParser =
      new PEMParser(new InputStreamReader(new ByteArrayInputStream(pemBytes), UTF_8));
  ImmutableList.Builder<Object> listBuilder = new ImmutableList.Builder<>();
  Object obj;
  // PEMParser returns an object (private key, certificate, etc) each time readObject() is called,
  // until no more object is to be read from the file.
  while (true) {
    try {
      obj = pemParser.readObject();
      if (obj == null) {
        break;
      } else {
        listBuilder.add(obj);
      }
    } catch (IOException e) {
      throw new RuntimeException("Cannot parse PEM file correctly.", e);
    }
  }
  return listBuilder.build();
}
 
Example 6
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 7
Source File: CertificateTool.java    From peer-os with Apache License 2.0 6 votes vote down vote up
/**
 * Convert X509 certificate in PEM format to X509Certificate object
 *
 * @param x509InPem X509 certificate in PEM format
 *
 * @return {@code X509Certificate}
 */
public X509Certificate convertX509PemToCert( String x509InPem )
{
    try
    {
        PEMParser pemParser = new PEMParser( new StringReader( x509InPem ) );
        JcaX509CertificateConverter x509CertificateConverter = new JcaX509CertificateConverter();

        Object o = pemParser.readObject();
        return x509CertificateConverter.getCertificate( ( X509CertificateHolder ) o );
    }
    catch ( Exception e )
    {
        throw new ActionFailedException( "Failed to convert PEM to certificate", e );
    }
}
 
Example 8
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 9
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 10
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Return PrivateKey  from pem bytes.
 *
 * @param pemKey pem-encoded private key
 * @return
 */
public PrivateKey bytesToPrivateKey(byte[] pemKey) throws CryptoException {
    PrivateKey pk = null;
    CryptoException ce = null;

    try {
        PemReader pr = new PemReader(new StringReader(new String(pemKey)));
        PemObject po = pr.readPemObject();
        PEMParser pem = new PEMParser(new StringReader(new String(pemKey)));

        if (po.getType().equals("PRIVATE KEY")) {
            pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject());
        } else {
            logger.trace("Found private key with type " + po.getType());
            PEMKeyPair kp = (PEMKeyPair) pem.readObject();
            pk = new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo());
        }
    } catch (Exception e) {
        throw new CryptoException("Failed to convert private key bytes", e);
    }
    return pk;
}
 
Example 11
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 12
Source File: BasicKeyStore.java    From env-keystore with MIT License 5 votes vote down vote up
protected static X509Certificate parseCert(PEMParser parser) throws IOException, CertificateException {
  X509CertificateHolder certHolder = (X509CertificateHolder) parser.readObject();
  if (certHolder == null) {
    return null;
  }
  return new JcaX509CertificateConverter().getCertificate(certHolder);
}
 
Example 13
Source File: CertUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
public static PrivateKey readPrivateKeyPemString(String pemString) throws CertException {
    try {
        PEMParser pemParser = new PEMParser(new StringReader(pemString));
        Object readObject = pemParser.readObject();
        if (readObject instanceof PEMKeyPair) {
            PEMKeyPair key = (PEMKeyPair) readObject;
            return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getKeyPair(key)
                    .getPrivate();
        }
        throw new CertException("read privateKey failed");
    } catch (Exception e) {
        throw new CertException("read privateKey failed", e);
    }
}
 
Example 14
Source File: CertUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
/**
 * 明文pem格式私钥读取
 *
 * @param privateKeyPemPath
 * @return
 * @throws Exception
 */
public static PrivateKey readPrivateKeyPem(String privateKeyPemPath) throws CertException {
    try {
        PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(privateKeyPemPath)));
        Object readObject = pemParser.readObject();
        if (readObject instanceof PEMKeyPair) {
            PEMKeyPair key = (PEMKeyPair) readObject;
            return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getKeyPair(key)
                    .getPrivate();
        }
        throw new CertException("read privateKey failed");
    } catch (Exception e) {
        throw new CertException("read privateKey failed", e);
    }
}
 
Example 15
Source File: BouncyCastleSecurityProviderTool.java    From Dream-Catcher 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);
    }
}
 
Example 16
Source File: HttpsHelper.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static KeyStore createTrustStore(final String certPath)
        throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    Path caPath = Paths.get(certPath, "ca.pem");
    BufferedReader reader = Files.newBufferedReader(caPath, Charset.defaultCharset());

    PEMParser parser = new PEMParser(reader);
    X509CertificateHolder object = (X509CertificateHolder) parser.readObject();
    Certificate caCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(object);

    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(null);
    trustStore.setCertificateEntry("ca", caCert);
    return trustStore;
}
 
Example 17
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 18
Source File: CertUtils.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * judge is guomi cert.
 * @param pem pem inputStream
 * @return is guomi cert
 * @throws Exception -
 */
public static PEMKeyPair getPEM(InputStream pem) throws Exception {
    PEMParser pemRd = openPEMResource(pem);
    if (pemRd == null) {
        throw new Exception("Open pem error");
    }
    PEMKeyPair pemPair = (PEMKeyPair) pemRd.readObject();
    return pemPair;
}
 
Example 19
Source File: CryptoUtils.java    From fabric-java-block with GNU General Public License v3.0 4 votes vote down vote up
public static PrivateKey getPrivateKeyFromBytes(byte[] data) throws IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    final PEMParser pemParser = new PEMParser(new StringReader(new String(data)));
    PrivateKeyInfo pemPair = (PrivateKeyInfo) pemParser.readObject();
    return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);
}
 
Example 20
Source File: DefaultQCloudClient.java    From wakeup-qcloud-sdk with Apache License 2.0 4 votes vote down vote up
@Override
public boolean verifyUserSig(String identifier, String sig)throws QCloudException {
	try {
		Security.addProvider(new BouncyCastleProvider());
		
		//DeBaseUrl64 urlSig to json
		Base64 decoder = new Base64();

		byte [] compressBytes = Base64Url.base64DecodeUrl(sig.getBytes(Charset.forName("UTF-8")));
		
		//Decompression
		Inflater decompression =  new Inflater();
		decompression.setInput(compressBytes, 0, compressBytes.length);
		byte [] decompressBytes = new byte [1024];
		int decompressLength = decompression.inflate(decompressBytes);
		decompression.end();
		
		String jsonString = new String(Arrays.copyOfRange(decompressBytes, 0, decompressLength));
		
		//Get TLS.Sig from json
		JSONObject jsonObject= JSON.parseObject(jsonString);
		String sigTLS = jsonObject.getString("TLS.sig");
		
		//debase64 TLS.Sig to get serailString
		byte[] signatureBytes = decoder.decode(sigTLS.getBytes(Charset.forName("UTF-8")));
		
		String strSdkAppid = jsonObject.getString("TLS.sdk_appid");
		String sigTime = jsonObject.getString("TLS.time");
		String sigExpire = jsonObject.getString("TLS.expire_after");
		
		if (!imConfig.getSdkAppId().equals(strSdkAppid))
		{
			return false;
		}

		if ( System.currentTimeMillis()/1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) {
			return false;
		}
		
		//Get Serial String from json
		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:" + sigTime + "\n" + 
			"TLS.expire_after:" + sigExpire + "\n";
	
        Reader reader = new CharArrayReader(imConfig.getPublicKey().toCharArray());
        PEMParser  parser = new PEMParser(reader);
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        Object obj = parser.readObject();
        parser.close();
        PublicKey pubKeyStruct  = converter.getPublicKey((SubjectPublicKeyInfo) obj);

		Signature signature = Signature.getInstance("SHA256withECDSA","BC");
		signature.initVerify(pubKeyStruct);
		signature.update(SerialString.getBytes(Charset.forName("UTF-8")));
		return signature.verify(signatureBytes);
	}catch (Exception e) {
		throw new QCloudException(e);
	}
}