[英]RSA Encode with Crypto++ and Decode with c# RSACryptoServiceProvider
早上好,
我有一個客戶端服務器應用程序通過UDP套接字進行通信。 我想使用RSA(對密鑰進行編碼)和AES對通信進行編碼,以對數據報進行編碼。
客戶端使用C ++,服務器端使用C#
我目前正在嘗試使用RSA將AES IV密鑰編碼,但是在c#中解碼時出現錯誤:
異常類型: System.Security.Cryptography.CryptographicException
異常消息: Cryptography_OAEPDecoding
這是我的編碼代碼(客戶端,c ++) [編輯]將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#解碼時,它不起作用。
謝謝,抱歉我的英語不好。
BigInteger.ToByteArray將值返回為little-endian 。
雖然RSAParameters
領域確實是大端(如解釋在這里 )。
您可以嘗試類似:
Modulus = n.ToByteArray().Reverse().ToArray()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.