HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Encryption/decryption of data

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
encryptiondatadecryption

Problem

I'm trying to work with some encryption/decryption of data. It was some hard work for me to get it working with some buffers and what not.

This is the code I came up with:

```
public static string Encrypt(string dataToEncrypt, byte[] publicKeyInfo)
{
//// Our bytearray to hold all of our data after the encryption
byte[] encryptedBytes = new byte[0];
using (var rsa = new RSACryptoServiceProvider())
{
try
{
var encoder = new UTF8Encoding();

byte[] encryptThis = encoder.GetBytes(dataToEncrypt);

//// Importing the public key
rsa.ImportCspBlob(publicKeyInfo);

int blockSize = (rsa.KeySize / 8) - 32;

//// buffer to write byte sequence of the given block_size
byte[] buffer = new byte[blockSize];

byte[] encryptedBuffer = new byte[blockSize];

//// Initializing our encryptedBytes array to a suitable size, depending on the size of data to be encrypted
encryptedBytes = new byte[encryptThis.Length + blockSize - (encryptThis.Length % blockSize) + 32];

for (int i = 0; i encryptThis.Length && ((encryptThis.Length - i) % blockSize != 0))
{
buffer = new byte[encryptThis.Length - i];
blockSize = encryptThis.Length - i;
}

//// If the amount of bytes we need to decrypt isn't enough to fill out a block, only decrypt part of it
if (encryptThis.Length bytesToDecrypt.Length && ((bytesToDecrypt.Length - i) % blockSize != 0))
{
buffer = new byte[bytesToDecrypt.Length - i];
blockSize = bytesToDecrypt.Length - i;
}

//// If the amount of bytes we need to decrypt isn't enough to fill out a block, only decrypt part of it
if (bytesToDecrypt.Length < blockSize)
{
buffer = new byte[bytes

Solution

You're using RSA as a block cipher in ECB mode. That's not how it's usually used. Unless you have a very good reason to do otherwise, you should just do one RSA encryption, of a secure random key for a block cipher (i.e. AES), and then use that key to encrypt your message.

Since you're converting string to string, it's apparent that neither memory nor latency is an issue, so you could avoid a lot of messing around with byte[]s by using MemoryStream and CryptoStream. You can also use Encoding.UTF8 to simplify the en/decoding step slightly.

Context

StackExchange Code Review Q#6662, answer score: 4

Revisions (0)

No revisions yet.