C#BouncyCastle RSA加密和解密 [英] C# BouncyCastle RSA Encryption and Decryption

查看:120
本文介绍了C#BouncyCastle RSA加密和解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于使用BouncyCastle进行RSA加密和解密的主题很多,但是我遇到了一些意外的行为.

There are many topics on RSA Encryption and Decryption using BouncyCastle, however I'm encountering some unexpected behaviour.

我正在尝试使用大小为64字节的私钥对64字节的数据块进行加密

I'm attempting to encrypt a 64 byte data blocking using a private key of size 64 bytes

我按以下方式计算RSA加密:

I compute the RSA Encryption as followings:

public byte[] Encrypt(byte[] data, AsymmetricKeyParameter key)
{
    var engine = new RsaEngine();
    engine.Init(true, key);
    var blockSize = engine.GetInputBlockSize();
    return engine.ProcessBlock(data, 0, blockSize );
}

我使用如下公钥计算解密

I compute the decryption using a public key as follows

public byte[] Decrypt(byte[] data, AsymmetricKeyParameter key)
{
    var engine = new RsaEngine();
    engine.Init(false, key);
    var blockSize = engine.GetInputBlockSize();
    return engine.ProcessBlock(data, 0, blockSize );
}

我发现的是,当我使用64字节的私钥对64个数据进行加密时,我会得到一个64字节的加密dataBlock.

What I'm finding is that when I encrypt my 64 data using a 64 byte Private Key I get back a 64 byte encrypted dataBlock.

但是,当我使用64字节公共密钥对64字节数组进行解码时,我会得到一个62字节大小的数据块.奇怪的是62字节数组中包含的值等于64字节原始数组(预加密)的值,但是解码后的数组缺少原始数据的第一个索引和最后一个索引.

However when I decode the 64 byte array using a 64 byte public key I get back a data block of size 62 bytes. What is stranger is that the values contained in the 62 byte array equal the values of the 64 byte original array (pre encryption) however the decoded array is missing the first index of the original data and the final index.

我尝试使用不同的键和不同的数据集,并且发生相同的事情.

I've tried using different keys and different sets of data and the same thing happens.

我一定做错了,但看不到.

I must be doing something wrong, but I can't see it.

干杯.

推荐答案

您弄错了基本概念.

  1. 512位RSA非常弱,至少使用1024位
  2. 私钥不用于加密.用于解密和签名.公钥用于加密和验证.
  3. 填充对于RSA安全至关重要.典型的填充方案需要几十个字节.
  4. 即使使用RSA教科书,RSA也只能处理小于模数的值.因此,512位模数不能对任意64字节/512位值进行操作.但是只有511位.

您应该退后一步,并描述您实际想要实现的目标,以便我们找到适合您需求的方案.只有在那之后,您才需要担心它的实现.

You should take a step back, and describe what you actually want to achieve, so we can find a scheme that fits your needs. Only after that you should worry about implementing it.

这篇关于C#BouncyCastle RSA加密和解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆