我正在对angular 6和.net核心api端进行加密/解密请求/响应。我正在使用AES对angular中的数据进行加密,并使用RSA公钥对AES密钥进行加密,并将其发送到.net核心api。我创建了动作过滤器以解密请求,然后首先解密请求,我必须使用RSA私钥解密AES密钥,但是使用RSA私钥解密AES密钥时却给我一个错误:
- ex {Org.BouncyCastle.Crypto.InvalidCipherTextException:块不正确 在Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding.DecodeBlock处(字节[]输入,Int32 inOff,Int32 inLen) Phyzii.Core.Api.Security.RSA.Decrypt(String cipherText)}处的System.Exception {Org.BouncyCastle.Crypto.InvalidCipherTextException}
这是我在斜角端的RSA加密代码:
import JSEncrypt from 'jsencrypt';
encryptObj = new JSEncrypt();
transitionIn(data: any) {
this.aesSecretKey=this.makeUniqueKey(10);
console.log(this.aesSecretKey);
this.data.DATAOBJ = this.aesEncrypt(this.aesSecretKey, data);
this.encryptObj.setPublicKey(this.publicKeyClient);
this.data.KEY = this.encryptObj.encrypt(this.aesSecretKey);
return this.data;
}
这是我在C#端的RSA解密代码:
private static AsymmetricCipherKeyPair ReadPemFile(string flag)
{
string filePath = flag == "PUBLIC" ? "D:/Crypto/private_key.pem" : "D:/Crypto/private_key_server.pem";
AsymmetricCipherKeyPair keys;
using (var reader = File.OpenText(filePath))// file containing RSA PKCS1 private key
keys = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
AsymmetricKeyParameter private_key = keys.Private;
AsymmetricKeyParameter public_key = keys.Public;
return keys;
}
//cipherText = "gOItOryuGy0UXHfoNqo0omcXLIOS6dhLJas5zeDNA7MfvsHYwP4ccSWU9JwTrIRiYUq/NB9oRn62ZQ5ynDnsGXUmHfVT4oPxtQZE1fXTTMN5ycfgthegesmXoZMMcWxA/wnwjLAgE17MNaunKY307W+nyc3jEMT1QsWUoOBESo0="
public static string Decrypt(string cipherText)
{
try
{
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
AsymmetricCipherKeyPair keys = ReadPemFile("PRIVATE");
AsymmetricKeyParameter private_key = keys.Private;
// Pure mathematical RSA implementation
// RsaEngine eng = new RsaEngine();
// PKCS1 v1.5 paddings
// Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());
// PKCS1 OAEP paddings
Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(false, private_key);
int length = cipherTextBytes.Length;
int blockSize = eng.GetInputBlockSize();
List<byte> plainTextBytes = new List<byte>();
for (int chunkPosition = 0; chunkPosition < length; chunkPosition += blockSize)
{
int chunkSize = Math.Min(blockSize, length - chunkPosition);
plainTextBytes.AddRange(eng.ProcessBlock(cipherTextBytes, chunkPosition, chunkSize));
}
return Encoding.UTF8.GetString(plainTextBytes.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
并且如果我在Pkcs1Encoding Init中设置了true
Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(true, private_key);
然后它将以这种格式�����Ŧ���%�Rc��\u000e�\b\u0004����I�]&P~�+�뛡�^s�V�ʗ' \b��?Jv�F�ge\u001b�S���^�\u0002��v/|�vh�}�z�[A�}��\u0002u\\�Pp����\u0011k9\u001e\n�E\b�\u0003��\u001a#��}��y��\u000eTG�U\a�A_KV�\u007fs����?3���*/*\n\n~�w�Q��'��\a:���q��BH\u0004R�#c��'d�\u001f���\0 5\u007f���fs�<���\u0012\t����|�[\u0015\b+��8\u0003
解密数据。[�v����Ǹ��8ځ\u001cԞv�{=���@ -o \ u0004.I \u0014J�\ 0#4 `
这是不正确的, 可能是什么问题?