[英]Successfully RSA Encrypting data in C#
我正在嘗試在我的 C# 程序中實現RSA 加密。
這是我的代碼:
using System;
using System.Security.Cryptography;
string dataToEncrypt = "Data to Encrypt here";
string modulus= "Public Key here";
string exponent= "Public Key Kxpiry here";
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo.Modulus = Encoding.UTF8.GetBytes(modulus);
RSAKeyInfo.D = Encoding.UTF8.GetBytes(dataToEncrypt);
RSAKeyInfo.Exponent = Encoding.UTF8.GetBytes(exponent);
RSA.ImportParameters(RSAKeyInfo);
我收到此錯誤代碼:
System.Security.Cryptography.CryptographicException: 'Bad Data.'
這一行給出了錯誤: RSA.ImportParameters(RSAKeyInfo);
其他信息:
我錯過了什么/做錯了什么?
RSA 密鑰生成是一個非常具體的過程,它依賴於或兩個(或更多)素數。 您不能只是為 RSA 選擇隨機值來保證安全。 再說一次,RSA 在加密過程中依賴於模取冪,這可能仍然“有效”,即生成不安全的答案。
然而,CSP(加密服務提供商)可能會帶來額外的限制。 例如,Microsoft CSP 對密鑰大小有以下限制:
Windows CSP 為 Windows 8.1 之前的 Windows 版本啟用 384 到 16384 位的密鑰大小,為 Windows 8.1 啟用 512 到 16384 位的密鑰大小。
由於密鑰大小被指定為模數的大小。 此外,密鑰大小也必須是 8 的倍數。 這意味着字節數組中的最高有效位必須設置為 1,而 UTF-8 則不是這種情況。
此外,對公共指數也可能有限制; 對於 Windows CSP,它需要小於 32 位。 通常它只是簡單地設置為值 010001 十六進制(65537 或費馬的第五個質數,稱為 F4)。
RSA的CNG 實現似乎更靈活,因此如果您想測試 RSA 的某些細節,也可以嘗試這樣做。
但是,最終您需要使用 RSA 密鑰對生成程序來創建有效的 RSA 密鑰對; 沒有其他東西是安全的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.