Han*_*ans 5 javascript c# encryption cryptography bouncycastle
我正在尝试在JavaScript中使用RSA加密,然后在C#中对其进行解密。在JavaScript中,我正在使用jsencrypt库。在C#中,我使用API“充气城堡”。当我用相同的语言进行加密/解密时,一切正常。解密时会得到正确的文本。当我尝试用C#解密用JavaScript加密的内容时,我什么也收不到。我确信两者之间的键是相同的。代码示例如下。任何有关如何解决此问题的帮助将不胜感激。
的JavaScript
//using jsencrypt.min.js
var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#input').val());
Run Code Online (Sandbox Code Playgroud)
将我从JavaScript“加密”中获得的值用于C#中的“ encyp”
AsymmetricCipherKeyPair KeyParameterPrivate;
byte[] cipheredBytes = Convert.FromBase64String(encyp);
string privateKeyFileName = @"C:\private.pem";
using (var fileStream2 = File.OpenText(privateKeyFileName))
{
PemReader pemReader2 = new Org.BouncyCastle.OpenSsl.PemReader(fileStream2);
KeyParameterPrivate = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)pemReader2.ReadObject();
}
IAsymmetricBlockCipher cipher2 = new Org.BouncyCastle.Crypto.Engines.RsaEngine();
RsaKeyParameters privateKey2 = (RsaKeyParameters)KeyParameterPrivate.Private;
//cipher.Init(false, publicKey4);
cipher2.Init(false, privateKey2);
byte[] deciphered = cipher2.ProcessBlock(cipheredBytes, 0, cipheredBytes.Length);
string decipheredText = utf8enc.GetString(deciphered);
Run Code Online (Sandbox Code Playgroud)
为什么你要用 BC 来折磨自己呢?
这里最简单的解密方法是:
// store is a X509Store pointing to the correct store on the target machine
// You have to ensure that the security principal for your app has access to the private key to decrypt
X509Certificate2 cert = store.Certificates.Find(X509FindType.FindByThumbprint, "sha1hash", false)[0];
var prov = (RSACryptoServiceProvider)cert.PrivateKey;
var decipheredText = Encoding.UTF8.GetString(prov.Decrypt(Convert.FromBase64String(target), false));
Run Code Online (Sandbox Code Playgroud)
显然,您可以从文件或任何其他方式获取 X509Certificate2,例如X509Certificate2 cert = new X509Certificate2(@"C:\someCert.pfx", "somePass");
如果您遵循了 jsencrypt 教程,请使用此 openssl 命令从您拥有的 pems 中获取 pfx:
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.pem -in publicKey.pem
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1229 次 |
| 最近记录: |