我正在嘗試使用 BouncyCastle 創建一個 RSA 密鑰對,然后嘗試匯入生成的公鑰,我收到以下錯誤
AsnContentException: The provided data is tagged with 'Universal' class value '16', but it should have been 'Universal' class value '2'.
代碼如下
RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
AsymmetricCipherKeyPair keys = rsaKeyPairGenerator.GenerateKeyPair();
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
RSA publicRsaKey = RSA.Create();
publicRsaKey.ImportRSAPublicKey(serializedPublicBytes, out _);
有誰知道我為什么會得到這個?
uj5u.com熱心網友回復:
正如 James K. Polk 總統在評論中所描述的,匯出的公鑰serializedPublicBytes是 X.509/SPKI 格式的 DER 編碼密鑰,可以使用 匯入ImportSubjectPublicKeyInfo(),而ImportRSAPublicKey()需要 PKCS#1 格式的 DER 編碼公鑰。
為了完整性: PKCS#1 格式可以很容易地從publicKeyInfo發布的代碼中添加以下內容:
RsaPublicKeyStructure rsaPublicKey = RsaPublicKeyStructure.GetInstance(publicKeyInfo.ParsePublicKey());
byte[] pkcs1Der = rsaPublicKey.ToAsn1Object().GetDerEncoded();
這樣匯入也可以通過ImportRSAPublicKey()傳遞來完成pkcs1Der,或者如果需要 PKCS#1 格式的公鑰。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/485073.html
