摘要:本文為翻譯和轉載自以下是顯示如何使用的最佳投票示例。這些示例是從開源項目中提取的。您可以對您喜歡的示例進行投票,您的投票將在我們的系統中使用,以生成更多好的示例。示例十九生成證書并存為格式和格式
本文為翻譯和轉載自 :https://www.programcreek.com/...
以下是顯示如何使用 org.bouncycastle.openssl.PEMWriter 的最佳投票示例。 這些示例是從開源項目中提取的。 您可以對您喜歡的示例進行投票,您的投票將在我們的系統中使用,以生成更多好的示例。示例一 保存密鑰和證書到文件中
/** * 保存私鑰和證書至文件 * @throws Exception */ protected void saveKeyPairAndCertificateToFile() throws Exception { if(localPrivateKeyFile==null){ LOGGER.info("not saving private key nor certificate"); return; } //Encode in PEM format, the format prefered by openssl // if(false){ // PEMWriter pemWriter=new PEMWriter(new FileWriter(localPrivateKeyFile)); // pemWriter.writeObject(localPrivateECKey); // pemWriter.close(); // } // else{ String keyText = "-----BEGIN EC PRIVATE KEY----- " + Base64.encode(Unpooled.wrappedBuffer(localPrivateECKey.getEncoded()), true).toString(CharsetUtil.US_ASCII) + " -----END EC PRIVATE KEY----- "; Files.write(keyText, localPrivateKeyFile, CharsetUtil.US_ASCII); Files.write(localId.toString(), new File(localPrivateKeyFile.getParentFile(), "localPublic.hash"), CharsetUtil.US_ASCII); // } PEMWriter certificateWriter=new PEMWriter(new FileWriter(localCertificateFile)); certificateWriter.writeObject(cert); certificateWriter.close(); LOGGER.info("Saved to "+localCertificateFile.getAbsolutePath()); }示例二 :對私鑰進行加密
/** * 加密私鑰 * * @param key 私鑰對象 * @param algorithm 密鑰算法 * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws IOException */ private void encryptedTest(PrivateKey key, ASN1ObjectIdentifier algorithm) throws NoSuchProviderException, NoSuchAlgorithmException, IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut), "BC"); PKCS8Generator pkcs8 = new PKCS8Generator(key, algorithm, "BC"); pkcs8.setPassword("hello".toCharArray()); pWrt.writeObject(pkcs8); pWrt.close(); PEMReader pRd = new PEMReader(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())), new PasswordFinder() { public char[] getPassword() { return "hello".toCharArray(); } }); PrivateKey rdKey = (PrivateKey) pRd.readObject(); assertEquals(key, rdKey); }示例三 轉換 rsa 的私鑰為 pem 字符串
/** * 轉換 rsa的私鑰為 pem 字符串 * * @param rsaKeyPair RSA 類型keypair * @return PEM string */ public static String getPEMStringFromRSAKeyPair(RSAKeyPair rsaKeyPair) { StringWriter pemStrWriter = new StringWriter(); PEMWriter pemWriter = new PEMWriter(pemStrWriter); try { KeyPair keyPair = new KeyPair(rsaKeyPair.getPublic(), rsaKeyPair.getPrivate()); //pemWriter.writeObject(keyPair); pemWriter.writeObject(keyPair.getPrivate()); //pemWriter.flush(); pemWriter.close(); } catch (IOException e) { log.warning("Caught exception:" + e.getMessage()); return ""; } return pemStrWriter.toString(); }示例四 將 pem 數據對象轉換成 pem 格式文件數據
/** * 將pem 數據對象轉換成 pem格式文件數據 * @param object * @return * @throws IOException */ public static byte[] toPem(Object object) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try (PEMWriter writer = new PEMWriter(new OutputStreamWriter(outputStream))) { writer.writeObject(object); writer.flush(); return outputStream.toByteArray(); } }示例五 將多份 certificate 對象寫入文件
private void writeCertificate(Certificate... certificates) throws IOException { final PEMWriter writer = new PEMWriter(new FileWriter(destfile)); for (final Certificate c : certificates) { writer.writeObject(c); } writer.close(); }示例六 將 X509Certificate 轉換成 pem 格式數據
public String x509CertificateToPem(final X509Certificate cert) throws IOException { final StringWriter sw = new StringWriter(); try (final PEMWriter pw = new PEMWriter(sw)) { pw.writeObject(cert); } return sw.toString(); }示例七 將 rsa 私鑰對象轉換為 PEM 格式數據
public String rsaPrivateKeyToPem(final PrivateKey key) throws IOException { final PemObject pemObject = new PemObject(CCS_RSA_PRIVATE_KEY, key.getEncoded()); final StringWriter sw = new StringWriter(); try (final PEMWriter pw = new PEMWriter(sw)) { pw.writeObject(pemObject); } return sw.toString(); }示例八 將私鑰、證書文件等轉換為 PEM 數據
private static byte[] getPemBytes(Object... objects) throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (PEMWriter pemWriter = new PEMWriter(new OutputStreamWriter(byteArrayOutputStream, UTF_8))) { for (Object object : objects) { pemWriter.writeObject(object); } } return byteArrayOutputStream.toByteArray(); }示例九 將 X509Certificate 轉換為 PEM 數據
private static String toPem(X509Certificate certificate) throws IOException { StringWriter stringWriter = new StringWriter(); PEMWriter pemWriter = new PEMWriter(stringWriter, BouncyCastleProvider.PROVIDER_NAME); pemWriter.writeObject(certificate); pemWriter.close(); return stringWriter.toString(); }示例十 將多個 證書數據 寫入文件
private void writeCertificate(Certificate... certificates) throws IOException { final PEMWriter writer = new PEMWriter(new FileWriter(destfile)); for (final Certificate c : certificates) { writer.writeObject(c); } writer.close(); }示例十一 將 keyPair 轉換成 Pem 格式
private String keyPairToString(KeyPair keyPair) { StringWriter stringWriter = new StringWriter(); PEMWriter pemWriter = new PEMWriter(stringWriter); try { pemWriter.writeObject(keyPair); pemWriter.flush(); pemWriter.close(); } catch (IOException e) { throw new RuntimeException("Unexpected IOException: " + e.getMessage(), e); } return stringWriter.getBuffer().toString(); }示例十二 將私鑰轉換為 PEM 格式的 String
private static String getInPemFormat(PrivateKey privateKey) throws IOException { final StringWriter stringWriter = new StringWriter(); final PEMWriter pemWriter = new PEMWriter(stringWriter); pemWriter.writeObject(privateKey); pemWriter.flush(); pemWriter.close(); return stringWriter.toString(); }示例十三 將 X509Certificate 轉換為 PEM 格式的字符串
public String convertToPEMString(X509Certificate x509Cert) throws IOException { StringWriter sw = new StringWriter(); try (PEMWriter pw = new PEMWriter(sw)) { pw.writeObject(x509Cert); } return sw.toString(); }示例十四 私鑰的讀寫測試
private void doWriteReadTest( PrivateKey akp, String provider) throws IOException { StringWriter sw = new StringWriter(); PEMWriter pw = new PEMWriter(sw, provider); pw.writeObject(akp); pw.close(); String data = sw.toString(); PEMReader pr = new PEMReader(new StringReader(data)); Object o = pr.readObject(); if (o == null || !(o instanceof KeyPair)) { fail("Didn"t find OpenSSL key"); } KeyPair kp = (KeyPair) o; PrivateKey privKey = kp.getPrivate(); if (!akp.equals(privKey)) { fail("Failed to read back test"); } }示例十五 對私鑰進行加密和解密測試
private void encryptedTestNew(PrivateKey key, ASN1ObjectIdentifier algorithm) throws NoSuchProviderException, NoSuchAlgorithmException, IOException, OperatorCreationException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); PEMWriter pWrt = new PEMWriter(new OutputStreamWriter(bOut), "BC"); JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(algorithm); encryptorBuilder.setProvider("BC"); encryptorBuilder.setPasssword("hello".toCharArray()); PKCS8Generator pkcs8 = new JcaPKCS8Generator(key, encryptorBuilder.build()); pWrt.writeObject(pkcs8); pWrt.close(); PEMReader pRd = new PEMReader(new InputStreamReader(new ByteArrayInputStream(bOut.toByteArray())), new PasswordFinder() { public char[] getPassword() { return "hello".toCharArray(); } }); PrivateKey rdKey = (PrivateKey)pRd.readObject(); assertEquals(key, rdKey); }示例十六 生成證書測試
public void test000GenerateCertificate() { String cn = "www.example.it"; String keystoreFile = "guanxi_idp_cert.jks"; String keystorePassword = "changeit"; String privateKeyPassword = "changeit"; String privateKeyAlias = "www.example.it"; Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyStore ks = null; try { ks = KeyStore.getInstance("JKS"); ks.load(null, null); // KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable示例十七 獲取 PKCS#10 PEM 字符串和加密的 PKCS#8 PEM 字符串attrs = new Hashtable (); Vector ordering = new Vector (); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, 10); Date validTo = new Date(); validTo.setTime(cal.getTime().getTime()); // validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); //x509.setSignatureAlgorithm("SHA1withDSA"); x509.setSignatureAlgorithm("SHA256withRSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "/tmp/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(IDP_RFC_CERT)); pemWriter.writeObject(cert[0]); pemWriter.close(); } catch (Exception se) { se.printStackTrace(System.err); } }
public String[] getPkcs10_Pkcs8_AsPemStrings(X500Name subject, String email, String pw) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, OperatorCreationException, PKCSException { // Create a PKCS10 cert signing request KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(2048); KeyPair kp = kpg.genKeyPair(); PrivateKey priKey = kp.getPrivate(); // X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE); // x500NameBld.addRDN(BCStyle.C, csrRequestValidationConfigParams.getCountryOID()); // x500NameBld.addRDN(BCStyle.O, csrRequestValidationConfigParams.getOrgNameOID()); // x500NameBld.addRDN(BCStyle.OU, ou); // x500NameBld.addRDN(BCStyle.L, loc); // x500NameBld.addRDN(BCStyle.CN, cn); // X500Name subject = x500NameBld.build(); PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic()); ExtensionsGenerator extGen = new ExtensionsGenerator(); if(email != null){ extGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, email))); } requestBuilder.addAttribute( PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()); String sigName = "SHA1withRSA"; PKCS10CertificationRequest req1 = requestBuilder.build( new JcaContentSignerBuilder(sigName).setProvider("BC").build(kp.getPrivate())); if (req1.isSignatureValid(new JcaContentVerifierProviderBuilder().setProvider("BC").build(kp.getPublic()))) { //log.info(sigName + ": PKCS#10 request verified."); } else { //log.error(sigName + ": Failed verify check."); throw new RuntimeException(sigName + ": Failed verify check."); } StringWriter writer = new StringWriter(); PEMWriter pemWrite = new PEMWriter(writer); pemWrite.writeObject(req1); pemWrite.close(); String csr = writer.toString(); JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_3DES); SecureRandom random = new SecureRandom(); encryptorBuilder.setRandom(random); encryptorBuilder.setPasssword(pw.toCharArray()); OutputEncryptor oe = encryptorBuilder.build(); JcaPKCS8Generator pkcs8GeneratorEnc = new JcaPKCS8Generator(priKey, oe); // Output encrypted private key pkcs8 PEM string (todo use later api) PemObject pkcs8PemEnc = pkcs8GeneratorEnc.generate(); StringWriter writer2 = new StringWriter(); PEMWriter pemWrite2 = new PEMWriter(writer2); pemWrite2.writeObject(pkcs8PemEnc); pemWrite2.close(); String pkcs8StrEnc = writer2.toString(); String[] pems = new String[2]; pems[0] = csr; pems[1] = pkcs8StrEnc; return pems; }示例十八 測試用 ForgeJS 創建的三重 des PKCS8 私鑰可以用 BC 解密。
public void decryptForgePkcs8PrivateKeyPem_PBEWithSHA1AndDESede() throws Exception { // http://bouncy-castle.1462172.n4.nabble.com/Help-with-EncryptedPrivateKeyInfo-td1468363.html // https://community.oracle.com/thread/1530354?start=0&tstart=0 Security.addProvider(new BouncyCastleProvider()); //PEMParser keyPemParser = new PEMParser(new StringReader(getPkcs8ForgePriKeyPem_PBEWithMD5AndDES())); //String passwd = "1234567890"; PEMParser keyPemParser = new PEMParser(new StringReader(getPkcs8ForgePriKeyPem_EncryptedWithPBEWithSHA1AndDESede())); String passwd = "password"; PemObject keyObj = keyPemParser.readPemObject(); byte[] keyBytes = keyObj.getContent(); EncryptedPrivateKeyInfo encryptPKInfo = new EncryptedPrivateKeyInfo(keyBytes); // 1.2.840.113549.1.5.13 == PBEWithMD5AndDES // 1.2.840.113549.1.12.1.3 == PBEWithSHA1AndDESede String algName = encryptPKInfo.getAlgName(); String algId = encryptPKInfo.getAlgParameters().getAlgorithm(); assertEquals("PBEWithSHA1AndDESede", algName); assertEquals("1.2.840.113549.1.12.1.3", algId); assertEquals("1.2.840.113549.1.12.1.3", PKCS8Generator.PBE_SHA1_3DES.getId()); // Decrypt private key Cipher cipher = Cipher.getInstance(algName); PBEKeySpec pbeKeySpec = new PBEKeySpec(passwd.toCharArray()); SecretKeyFactory secFac = SecretKeyFactory.getInstance(algName); Key pbeKey = secFac.generateSecret(pbeKeySpec); AlgorithmParameters algParams = encryptPKInfo.getAlgParameters(); cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams); KeySpec pkcs8KeySpec = encryptPKInfo.getKeySpec(cipher); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey priKeyDecryptedBC = kf.generatePrivate(pkcs8KeySpec); // Compare decrypted private key with a version that was decrypted using // openssl and assert that they are the same. JcaPKCS8Generator pkcs8GeneratorNoEnc = new JcaPKCS8Generator(priKeyDecryptedBC, null); PemObject pkcs8PemDecryptedBC = pkcs8GeneratorNoEnc.generate(); StringWriter writer3 = new StringWriter(); PEMWriter pemWrite3 = new PEMWriter(writer3); pemWrite3.writeObject(pkcs8PemDecryptedBC); pemWrite3.close(); String pkcs8StrDecryptedBC = writer3.toString().trim().replaceAll(" ", " ");; String pkcs8StrDecryptedOpenSSL = getPkcs8ForgePriKeyPem_DecryptedWithOpenSSL().trim().replaceAll(" ", " ");; //System.out.println("["+pkcs8StrNoEncBC+"]"); //System.out.println("["+pkcs8StrNoEncOpenssL+"]"); assertTrue(pkcs8StrDecryptedBC.equals(pkcs8StrDecryptedOpenSSL)); }示例十九 生成ECDSA 證書并存為P12格式 和pem格式
public static void main(String[] args) throws Exception { if (args.length != 2) { System.err.println("Usage: GenTrustAnchorKeyStore keyStoreName keyStorePassword"); System.exit(1); } Security.addProvider(new BouncyCastleProvider()); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("ECDSA", "BC"); kpGen.initialize(new ECNamedCurveGenParameterSpec("secp256r1")); KeyPair kp = kpGen.generateKeyPair(); X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.C, "AU"); builder.addRDN(BCStyle.O, "Crypto Workshop Pty Ltd"); builder.addRDN(BCStyle.OU, "Ximix Node Test CA"); builder.addRDN(BCStyle.L, "Melbourne"); builder.addRDN(BCStyle.ST, "Victoria"); builder.addRDN(BCStyle.CN, "Trust Anchor"); Date startDate = new Date(System.currentTimeMillis() - 50000); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(kp.getPrivate()); X509v1CertificateBuilder certGen1 = new JcaX509v1CertificateBuilder(builder.build(), BigInteger.valueOf(1), startDate, new Date(System.currentTimeMillis() + 2 * YEAR),builder.build(), kp.getPublic()); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen1.build(sigGen)); KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC"); keyStore.load(null, null); keyStore.setKeyEntry("trust", kp.getPrivate(), null, new Certificate[] { cert }); keyStore.store(new FileOutputStream(args[0] + ".p12"), args[1].toCharArray()); PEMWriter pWrt = new PEMWriter(new FileWriter(args[0] + ".pem")); pWrt.writeObject(cert); pWrt.close(); }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72845.html
摘要:在之后,原來永久代的數據被分到了堆和元空間中。元空間存儲類的元信息,靜態變量和常量池等放入堆中。這樣能在一些場景中顯著提高性能,因為避免了在堆內存和堆外內存來回拷貝數據。 以下內容部分轉載于: CS-Notes showImg(http://ww1.sinaimg.cn/large/005NT19Ply1g385uooqv9j30kd0slmyw.jpg); 程序計數器(Program...
摘要:對字節碼文件進行解釋執行,把字節碼翻譯成相關平臺上的機器指令。使用命令可對字節碼文件以及配置文件進行打包可對一個由多個字節碼文件和配置文件等資源文件構成的項目進行打包。和不存在永久代這種說法。 Java技術體系 從廣義上講,Clojure、JRuby、Groovy等運行于Java虛擬機上的語言及其相關的程序都屬于Java技術體系中的一員。如果僅從傳統意義上來看,Sun官方所定義的Jav...
摘要:,這是標記配置文件集版本化的服務器端特性。要配置對稱密鑰,需要將設置為秘密字符串或使用環境變量將其排除在純文本配置文件之外。 Spring Cloud Config Server Spring Cloud Config Server為外部配置提供基于HTTP資源的API(名稱—值對或等效的YAML內容),通過使用@EnableConfigServer注解,服務器可嵌入Spring Bo...
摘要:解決的辦法在處理計算密集型任務時,使用多進程協程,發揮計算機多核的威力,而處理密集型,則可以使用多線程。至此,有關知識點的面試題就已告一段落,下次更新數據庫,方面面試題。 showImg(https://segmentfault.com/img/bVbuYzy?w=3484&h=2480); 閱讀本文大約需要 5 分鐘。 15.說一說 GIL 前面有提到由于 Python 基于 C 語...
閱讀 1382·2021-09-22 10:02
閱讀 1862·2021-09-08 09:35
閱讀 4044·2021-08-12 13:29
閱讀 2594·2019-08-30 15:55
閱讀 2257·2019-08-30 15:53
閱讀 2295·2019-08-29 17:13
閱讀 2753·2019-08-29 16:31
閱讀 2948·2019-08-29 12:24