Java Code Examples for org.bouncycastle.openssl.PEMParser#close()
The following examples show how to use
org.bouncycastle.openssl.PEMParser#close() .
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: OcspServerExample.java From netty-4.1.22 with Apache License 2.0 | 7 votes |
private static X509Certificate[] parseCertificates(Reader reader) throws Exception { JcaX509CertificateConverter converter = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()); List<X509Certificate> dst = new ArrayList<X509Certificate>(); PEMParser parser = new PEMParser(reader); try { X509CertificateHolder holder = null; while ((holder = (X509CertificateHolder) parser.readObject()) != null) { X509Certificate certificate = converter.getCertificate(holder); if (certificate == null) { continue; } dst.add(certificate); } } finally { parser.close(); } return dst.toArray(new X509Certificate[0]); }
Example 2
Source File: PrivateKeyProvider.java From XS2A-Sandbox with Apache License 2.0 | 6 votes |
/** * 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: CertUtil.java From littleca with Apache License 2.0 | 6 votes |
/** * 读取x509 证书 * * @param pemPath * @return */ public static X509Certificate readX509Cert(String savePath) throws CertException { try { if (null == savePath) { throw new CertException("save path can't be null"); } PEMParser pemParser = new PEMParser(new InputStreamReader(new FileInputStream(savePath))); Object readObject = pemParser.readObject(); if (readObject instanceof X509CertificateHolder) { X509CertificateHolder holder = (X509CertificateHolder) readObject; return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(holder); } pemParser.close(); throw new CertException(savePath + "file read format failed"); } catch (Exception e) { throw new CertException("read x509 cert failed", e); } }
Example 4
Source File: KeyReader.java From log4j2-elasticsearch with Apache License 2.0 | 6 votes |
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: KeyReader.java From log4j2-elasticsearch with Apache License 2.0 | 6 votes |
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 6
Source File: BasicKeyStore.java From env-keystore with MIT License | 6 votes |
protected static java.security.KeyStore createKeyStore(final Reader keyReader, final Reader certReader, final String password) throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { PrivateKey key = getPrivateKeyFromPEM(keyReader); keyReader.close(); PEMParser parser = new PEMParser(certReader); java.security.KeyStore ks = java.security.KeyStore.getInstance(DEFAULT_TYPE); ks.load(null); List<X509Certificate> certificates = new ArrayList<>(); X509Certificate certificate; while ((certificate = parseCert(parser)) != null) { certificates.add(certificate); } ks.setKeyEntry("alias", key, password.toCharArray(), certificates.toArray(new X509Certificate[]{})); parser.close(); return ks; }
Example 7
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 8
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 9
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 10
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 11
Source File: tls_sigature.java From tls-sig-api-java with MIT License | 4 votes |
public static CheckTLSSignatureResult CheckTLSSignatureEx( String sig, long sdkappid, String identifier, String publicKey) throws DataFormatException { CheckTLSSignatureResult result = new CheckTLSSignatureResult(); Security.addProvider(new BouncyCastleProvider()); byte [] compressBytes = base64_url.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= new JSONObject(jsonString); String sigTLS = jsonObject.getString("TLS.sig"); //debase64 TLS.Sig to get serailString byte[] signatureBytes = Base64.decode(sigTLS.getBytes(Charset.forName("UTF-8"))); try { String strSdkappid = jsonObject.getString("TLS.sdk_appid"); String sigTime = jsonObject.getString("TLS.time"); String sigExpire = jsonObject.getString("TLS.expire_after"); if (Integer.parseInt(strSdkappid) != sdkappid) { result.errMessage = new String( "sdkappid " + strSdkappid + " in tls sig not equal sdkappid " + sdkappid + " in request"); return result; } if ( System.currentTimeMillis()/1000 - Long.parseLong(sigTime) > Long.parseLong(sigExpire)) { result.errMessage = new String("TLS sig is out of date"); return result; } //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:" + sdkappid + "\n" + "TLS.time:" + sigTime + "\n" + "TLS.expire_after:" + sigExpire + "\n"; Reader reader = new CharArrayReader(publicKey.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"))); boolean bool = signature.verify(signatureBytes); result.expireTime = Integer.parseInt(sigExpire); result.initTime = Integer.parseInt(sigTime); result.verifyResult = bool; } catch(Exception e) { e.printStackTrace(); result.errMessage = "Failed in checking sig"; } return result; }
Example 12
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 13
Source File: DefaultQCloudClient.java From wakeup-qcloud-sdk with Apache License 2.0 | 4 votes |
@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); } }