早上好
我有一个客户端服务器应用程序通过UDP套接字进行通信。 我想使用RSA(对密钥进行编码)和AES对通信进行编码,以对数据报进行编码。
客户端使用C ++,服务器端使用C#
我目前正在尝试使用RSA对AES IV密钥进行编码,但是在c#中解码时出现错误:
异常类型: System.Security.Cryptography.CryptographicException
异常消息:密码学_OAEP解码
这是我的编码代码(客户端,c ++) [EDIT]将RSAES_PKCS1v15_Encryptor更改为RSAES_OAEP_SHA_Encryptor
const CryptoPP::Integer n("107289343054719278577597018805838066296333011963085747309982087864392842699433873606133118875978275304651444098131280023618603357722259282514858925191134541966986361546234507079678544203468616135436686852577772762581654429498496768721214543879181421353486700409082948114039206485653595743465270256058198245113.");
const CryptoPP::Integer e("17.");
[...]
void Crypto::CryptRSA(const std::string & bufferIn, std::string & bufferOut, const CryptoPP::Integer &n, const CryptoPP::Integer &e)
{
CryptoPP::AutoSeededRandomPool rnd;
CryptoPP::RSA::PublicKey pubKey;
pubKey.Initialize(n, e);
CryptoPP::RSAES_OAEP_SHA_Encryptor encryptor(pubKey);
size_t ecl = encryptor.CiphertextLength(bufferIn.size());
CryptoPP::SecByteBlock ciphertext(ecl);
encryptor.Encrypt(rnd, (CryptoPP::byte*)bufferIn.c_str(), bufferIn.size(), ciphertext);
bufferOut = std::string((char*)ciphertext.data(), ecl);
}
这是我的解码代码(服务器端。C#)
private static string _keyN = "107289343054719278577597018805838066296333011963085747309982087864392842699433873606133118875978275304651444098131280023618603357722259282514858925191134541966986361546234507079678544203468616135436686852577772762581654429498496768721214543879181421353486700409082948114039206485653595743465270256058198245113";
private static string _keyE = "17";
private static string _keyD = "50489102613985542860045655908629678257097887982628586969403335465596631858557116991121467706342717790424208987355896481702872168339886721183463023619357421741798172532326737925480536247565713413538718832057918801452980775480097195493999319542331774866185094818177243836015292183598722700529776296282728256145";
[...]
public static byte[] DecryptRSA(byte[] encrypted)
{
BigInteger n, e, d;
BigInteger.TryParse(_keyN, out n);
BigInteger.TryParse(_keyE, out e);
BigInteger.TryParse(_keyD, out d);
CspParameters csp = new CspParameters();
csp.KeyContainerName = "RSA Test (OK to Delete)";
csp.ProviderType = 1;
csp.KeyNumber = 1;
var rsa = new RSACryptoServiceProvider(csp);
rsa.PersistKeyInCsp = false;
var param = new RSAParameters()
{
Modulus = n.ToByteArray().Skip(1).ToArray(),
Exponent = e.ToByteArray().Skip(1).ToArray(),
D = d.ToByteArray().Skip(1).ToArray(),
};
rsa.ImportParameters(param);
return rsa.Decrypt(encrypted.ToArray(), true);
}
所以,我想知道我在代码中做错了什么。
在c ++中,我可以对我的数据报进行编码和解码,但是当我尝试使用c#解码时,它不起作用。
谢谢你,我的英语不好。
答案 0 :(得分:0)
BigInteger.ToByteArray以 little-endian 的形式返回值。
尽管RSAParameters
字段的确是big-endian(如here所述)。
您可以尝试以下方法:
Modulus = n.ToByteArray().Reverse().ToArray()