web-dev-qa-db-ja.com

Javaを使用してX509証明書を作成する方法

Java言語を使用してX509証明書を作成し、それから公開鍵を抽出します。

私はインターネットを検索し、多くのコード例を見つけましたが、それらすべてにエラー(不明な変数または不明なタイプ)があるか、または「タイプ...からのメソッド...は非推奨です」などのような多くの警告があります。

たとえば、次のコードが機能しない理由:

PublicKey pk;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
String PKstr = pk.toString();
InputStream PKstream = new ByteArrayInputStream(PKstr.getBytes());
X509Certificate pkcert = (X509Certificate)cf.generateCertificate(PKstream);


純粋なJavaまたはBouncy Castleを使用して証明書を作成し、それから公開鍵を取得する方法を誰かに教えてもらえますか?

皆さんありがとう。

13
leyla moazami

JDKクラスのみを使用して証明書を生成することもできます。欠点は、Sun.security.x509パッケージの2つのクラスを使用する必要があることです。コードは次のようになります。

KeyStore keyStore = ... // your keystore

// generate the certificate
// first parameter  = Algorithm
// second parameter = signrature algorithm
// third parameter  = the provider to use to generate the keys (may be null or
//                    use the constructor without provider)
CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA", null);
// generate it with 2048 bits
certGen.generate(2048);

// prepare the validity of the certificate
long validSecs = (long) 365 * 24 * 60 * 60; // valid for one year
// add the certificate information, currently only valid for one year.
X509Certificate cert = certGen.getSelfCertificate(
   // enter your details according to your application
   new X500Name("CN=My Application,O=My Organisation,L=My City,C=DE"), validSecs);

// set the certificate and the key in the keystore
keyStore.setKeyEntry(certAlias, certGen.getPrivateKey(), null, 
                        new X509Certificate[] { cert });

キーストアから秘密キーを取得して、データを暗号化または復号化します。コードに基づく http://www.pixelstech.net/article/1408524957-Generate-cetrificate-in-Java----

27
iwan.z

はい、BouncyCastleを使用すると、2つの公開キー(証明書のキーとCAのキー)からX509証明書を作成できます ここ

結果の証明書をPEM here に変換します。

5
Pierre Carrier