我需要一个编码为DER格式的RSA公钥。
使用RSACryptoServiceProvider生成密钥对。
我正在寻找的是与java相当的c#:
PublicKey pubKey = myPair.getPublic();
byte[] keyBytes = pubKey.getEncoded();
我已经尝试过调查BouncyCastle,但是如果解决方案存在,那么我就会迷失方向。
答案 0 :(得分:4)
使用Bouncy Castle:
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
...
var generator = new RsaKeyPairGenerator ();
generator.Init (new KeyGenerationParameters (new SecureRandom (), 1024));
var keyPair = generator.GenerateKeyPair ();
RsaKeyParameters keyParam = (RsaKeyParameters)keyPair.Public;
var info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo (keyParam);
RsaBytes = info.GetEncoded ();
最后三行是使用RSA公钥并将其导出的行。
答案 1 :(得分:0)
我尝试使用上述 info.GetEncoded() 但结果,我无法使用它来验证使用相应私钥创建的签名。
对我有用的是将其转换为 X509Certificate2。
private bool VerifySignature(string stringContent, string stringSignature, X509Certificate2 x509PublicKey)
{
Int16 cbSignature = 0, cbCert = 0;
int cbData = 0;
CertBasicStruct sCert = new CertBasicStruct();
var pbCert = PublicKey.RawData;
cbCert = (Int16)pbCert.Length;
byte[] pbData = Encoding.UTF8.GetBytes(stringContent);
cbData = (Int16)pbData.Length;
byte[] pbSignature = Convert.FromBase64String(Signature);
cbSignature = (Int16)pbSignature.Length;
var rtn = DllImportService.DecodeCertificate(pbCert, cbCert, ref sCert);
var rtn_1 = DllImportService.VerifySignatureByCert(ref sCert, DllImportService.CKM_SHA256_RSA_PKCS, pbData, cbData, pbSignature, cbSignature);
if (rtn_1 == 0)
{
LogWndAppendLine("Signature is valid.");
return true;
}
else
{
LogWndAppendLine("Signature is invalid");
return false;
}
}
X509Certificate2.RawData 就是您要找的。p>