摘要:本文為翻譯和轉(zhuǎn)載自以下是顯示如何使用的最佳投票示例。這些示例是從開(kāi)源項(xiàng)目中提取的。您可以對(duì)您喜歡的示例進(jìn)行投票,您的投票將在我們的系統(tǒng)中使用,以生成更多好的示例。示例十九生成證書(shū)并存為格式和格式
本文為翻譯和轉(zhuǎn)載自 :https://www.programcreek.com/...
以下是顯示如何使用 org.bouncycastle.openssl.PEMWriter 的最佳投票示例。 這些示例是從開(kāi)源項(xiàng)目中提取的。 您可以對(duì)您喜歡的示例進(jìn)行投票,您的投票將在我們的系統(tǒng)中使用,以生成更多好的示例。示例一 保存密鑰和證書(shū)到文件中
/** * 保存私鑰和證書(shū)至文件 * @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()); }示例二 :對(duì)私鑰進(jìn)行加密
/** * 加密私鑰 * * @param key 私鑰對(duì)象 * @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); }示例三 轉(zhuǎn)換 rsa 的私鑰為 pem 字符串
/** * 轉(zhuǎn)換 rsa的私鑰為 pem 字符串 * * @param rsaKeyPair RSA 類(lèi)型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 數(shù)據(jù)對(duì)象轉(zhuǎn)換成 pem 格式文件數(shù)據(jù)
/** * 將pem 數(shù)據(jù)對(duì)象轉(zhuǎn)換成 pem格式文件數(shù)據(jù) * @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 對(duì)象寫(xiě)入文件
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 轉(zhuǎn)換成 pem 格式數(shù)據(jù)
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 私鑰對(duì)象轉(zhuǎn)換為 PEM 格式數(shù)據(jù)
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(); }示例八 將私鑰、證書(shū)文件等轉(zhuǎn)換為 PEM 數(shù)據(jù)
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 轉(zhuǎn)換為 PEM 數(shù)據(jù)
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(); }示例十 將多個(gè) 證書(shū)數(shù)據(jù) 寫(xiě)入文件
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 轉(zhuǎn)換成 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(); }示例十二 將私鑰轉(zhuǎn)換為 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 轉(zhuǎn)換為 PEM 格式的字符串
public String convertToPEMString(X509Certificate x509Cert) throws IOException { StringWriter sw = new StringWriter(); try (PEMWriter pw = new PEMWriter(sw)) { pw.writeObject(x509Cert); } return sw.toString(); }示例十四 私鑰的讀寫(xiě)測(cè)試
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"); } }示例十五 對(duì)私鑰進(jìn)行加密和解密測(cè)試
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); }示例十六 生成證書(shū)測(cè)試
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; }示例十八 測(cè)試用 ForgeJS 創(chuàng)建的三重 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 證書(shū)并存為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(); }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.specialneedsforspecialkids.com/yun/72845.html
摘要:在之后,原來(lái)永久代的數(shù)據(jù)被分到了堆和元空間中。元空間存儲(chǔ)類(lèi)的元信息,靜態(tài)變量和常量池等放入堆中。這樣能在一些場(chǎng)景中顯著提高性能,因?yàn)楸苊饬嗽诙褍?nèi)存和堆外內(nèi)存來(lái)回拷貝數(shù)據(jù)。 以下內(nèi)容部分轉(zhuǎn)載于: CS-Notes showImg(http://ww1.sinaimg.cn/large/005NT19Ply1g385uooqv9j30kd0slmyw.jpg); 程序計(jì)數(shù)器(Program...
摘要:對(duì)字節(jié)碼文件進(jìn)行解釋執(zhí)行,把字節(jié)碼翻譯成相關(guān)平臺(tái)上的機(jī)器指令。使用命令可對(duì)字節(jié)碼文件以及配置文件進(jìn)行打包可對(duì)一個(gè)由多個(gè)字節(jié)碼文件和配置文件等資源文件構(gòu)成的項(xiàng)目進(jìn)行打包。和不存在永久代這種說(shuō)法。 Java技術(shù)體系 從廣義上講,Clojure、JRuby、Groovy等運(yùn)行于Java虛擬機(jī)上的語(yǔ)言及其相關(guān)的程序都屬于Java技術(shù)體系中的一員。如果僅從傳統(tǒng)意義上來(lái)看,Sun官方所定義的Jav...
摘要:,這是標(biāo)記配置文件集版本化的服務(wù)器端特性。要配置對(duì)稱(chēng)密鑰,需要將設(shè)置為秘密字符串或使用環(huán)境變量將其排除在純文本配置文件之外。 Spring Cloud Config Server Spring Cloud Config Server為外部配置提供基于HTTP資源的API(名稱(chēng)—值對(duì)或等效的YAML內(nèi)容),通過(guò)使用@EnableConfigServer注解,服務(wù)器可嵌入Spring Bo...
摘要:解決的辦法在處理計(jì)算密集型任務(wù)時(shí),使用多進(jìn)程協(xié)程,發(fā)揮計(jì)算機(jī)多核的威力,而處理密集型,則可以使用多線程。至此,有關(guān)知識(shí)點(diǎn)的面試題就已告一段落,下次更新數(shù)據(jù)庫(kù),方面面試題。 showImg(https://segmentfault.com/img/bVbuYzy?w=3484&h=2480); 閱讀本文大約需要 5 分鐘。 15.說(shuō)一說(shuō) GIL 前面有提到由于 Python 基于 C 語(yǔ)...
閱讀 1391·2021-09-22 10:02
閱讀 1916·2021-09-08 09:35
閱讀 4067·2021-08-12 13:29
閱讀 2612·2019-08-30 15:55
閱讀 2267·2019-08-30 15:53
閱讀 2306·2019-08-29 17:13
閱讀 2766·2019-08-29 16:31
閱讀 2958·2019-08-29 12:24