限制是什么对于可以使用rsacryptoserviceprovider(C#)加密/解密的各种字符串?
以下是我对RSA加密和解密方法的实现,我基于Microsoft文档。
public string Encrypt(string plainText)
{
rsaCsp.ImportParameters(publicKey);
byte[] data = Encoding.UTF8.GetBytes(plainText);
byte[] cypher = rsaCsp.Encrypt(data, fOAEP: true);
string cypherText = Convert.ToBase64String(cypher);
return cypherText;
}
public string Decrypt(string cypherText)
{
rsaCsp.ImportParameters(privateKey);
byte[] data = Convert.FromBase64String(cypherText);
byte[] decrypted = rsaCsp.Decrypt(data, fOAEP: true);
string plainText = Encoding.UTF8.GetString(decrypted);
return plainText;
}
我正在注入密钥和提供商,以便我可以重复使用特定的密钥,以便我什至可以解密程序的其他执行中加密的字符串。 (例如:我在测试中加密并保存在数据库中,在另一个测试中,我在数据库中搜索了加密的字符串和解密)。如果我允许自动生成公共钥匙和私钥,则不可能。
private readonly RSAParameters privateKey;
private readonly RSAParameters publicKey;
private readonly RSACryptoServiceProvider rsaCsp;
public RsaCryptoService(
RSACryptoServiceProvider rsaCsp,
RSAParameters privateKey,
RSAParameters publicKey)
{
this.rsaCsp = rsaCsp;
this.privateKey = privateKey;
this.publicKey = publicKey;
}
以下是依赖关系的构造:
public static void InjectRsaCryptoService(this IServiceCollection services, string userName = "default", int keySize = 2048)
{
Services = services;
RsaKeyPair rsaKeyPair = SecuritySettings.RsaKeys.SingleOrDefault(p => p.UserName == userName);
if (rsaKeyPair == null)
throw new lsilvpin_securityException(
$"O usuário {userName} não está autorizado a utilizar as ferramentas de segurança.");
RSAParameters privateKey = rsaKeyPair.PrivateKey.AsParameter();
RSAParameters publicKey = rsaKeyPair.PublicKey.AsParameter();
RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(keySize);
rsaCsp.ImportParameters(publicKey);
rsaCsp.ImportParameters(privateKey);
Services.AddTransient(sp =>
{
IRsaCryptoService rsa = new RsaCryptoService(rsaCsp, privateKey, publicKey);
return rsa;
});
}
一开始我认为它工作正常,但是要安全起见,我决定进行性能测试,将随机字符串发送到被加密和解密。
这是我的性能测试:
[Fact]
public void TestRsaCryptionPerformance()
{
for (int i = 0; i < 1000; i++)
{
var plainText = RandomWordGenerator.Next(new RandomWordParameters(WordMaxLength: 495)) + "@eA8";
IRsaCryptoService rsa = Services
.BuildServiceProvider()
.GetRequiredService<IRsaCryptoService>();
string publicKey = rsa.GetPublicKey();
string cypherText = rsa.Encrypt(plainText);
string decrypted = rsa.Decrypt(cypherText);
Assert.True(!string.IsNullOrWhiteSpace(publicKey));
Assert.True(!string.IsNullOrWhiteSpace(cypherText));
Assert.True(!string.IsNullOrWhiteSpace(decrypted));
Assert.True(plainText.Equals(decrypted));
Debug.WriteLine($"PublicKey: {publicKey}");
Debug.WriteLine($"CypherText: {cypherText}");
Debug.WriteLine($"Decrypted: {decrypted}");
}
}
我正在使用以下方法生成100至499之间的随机单词:
public static string Next(RandomWordParameters? randomWordParameters = null)
{
randomWordParameters ??= new RandomWordParameters();
if (randomWordParameters.CharLowerBound <= 0 || randomWordParameters.CharUpperBound <= 0)
throw new RandomGeneratorException("Os limites inferior e superior devem ser positivos.");
if (randomWordParameters.CharLowerBound >= randomWordParameters.CharUpperBound)
throw new RandomGeneratorException("O limite inferior deve ser menor do que o limite superior.");
var rd_char = new Random();
var rd_length = new Random();
var wordLength = rd_length.Next(randomWordParameters.WordMinLength, randomWordParameters.WordMaxLength);
var sb = new StringBuilder();
int sourceNumber;
for (int i = 0; i < wordLength; i++)
{
sourceNumber = rd_char.Next(randomWordParameters.CharLowerBound, randomWordParameters.CharUpperBound);
sb.Append(Convert.ToChar(sourceNumber));
}
var word = sb.ToString();
return word;
}
注意:我使用通过传递33和33和33和33和126 to convert.tochar(int)方法。
当我运行1000个随机单词的循环时,我总是会发现一个引发以下例外的循环:
insenter.cryptography.cryptothrowhelper.windowscryptographicexception:“ comprimentoinválido。” (长度无效)
在测试中的字符串:a_bdh [(4/6-9m&gt;,9a_j/^t2gcsxo {{{{ w#j*!r! :nei7!vtfm8w.5q1,d?i9dr&gt; u {m0,$ yxp1cd] mc(gnd $){x [x [x [@l9c7e&gt; z() kckc%usv'] 958^} a2p(shun'= vr
? “ https://i.sstatic.net/lhfl2.png” rel =“ nofollow noreferrer”>
想在我正在实现的系统上使用RSA加密,但是任何人都不知道该问题来自何处?
我 密码模拟长度长度约为20,从弱到非常强的密码)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据KlausGütte和Topaco的评论,我对回应感到满意!
问题是由输入字符串的大小引起的,输入的限制是根据Klaus链接的问题的输入的大小,并且此大小取决于Topaco所述的加密密钥的大小!
链接引起澄清的链接: rsacryptoserviceprovider
链接链接到澄清输入尺寸限制: https://crypto.stackexchange.com/questions/42097/what--is-the-maximum-size-size-of-plaint-plaintext-message-for-rsa-rsa-oaep/42100# << /a> 42100
更具体地说:
img src =“ https://i.sstatic.net/un0an.png” alt =“在此处输入图像说明”>
在我的具体情况下,加密/decrypt方法接受的最大字符串长度为214 (长度)。用100K随机字符串进行测试,并且效果很好!但是,传递字符串大小&gt; = 215已经生成了“不良长度”例外。
长度&lt; = 214
失败
非常感谢您的帮助!
Based on comments from Klaus Gütte and Topaco, I'm satisfied with the response!
The problem is caused by the size of the input string, the limit of the input so is the size of the input according to the question linked by Klaus, and this size depends on the size configured for the encryption key as mentioned by Topaco!
Link to cause clarification: System.Security.Cryptography.CryptographicException : Bad length in RSACryptoserviceProvider
Link to clarify input size limit: https://crypto.stackexchange.com/questions/42097/what-is-the-maximum-size-of-the-plaintext-message-for-rsa-oaep/42100# 42100
More specifically: https://www.rfc-editor.org/rfc/rfc8017#section-7.1.1
Print RSAES-OAEP-ENCRYPT standars
In my specific case, the maximum length of strings accepted by the encrypt/decrypt methods was 214 (Length). Test with 100k random strings and it worked perfectly! However, passing a string size >= 215 already generates the "Bad length" exception.
Success with length <= 214
Fail with 215
Thanks a lot for the help guys!!