views:

494

answers:

2

Hi,

I'm trying to encrypt something simple, like int or long. Simplest way I found looks like:

int num = 2;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
byte[] numBytes = BitConverter.GetBytes(num);
byte[] encryptedBytes = rsa.Encrypt(numBytes, true);

Problem is, the encryptedBytes is 128 bytes long. How can I encrypt data (which I could still later decrypt) where the encrypted result is the same length in bytes as the input?

I know I can shorten the result if I define RSACryptoServiceProvider(512) or RSACryptoServiceProvider(384), but that's as low as it goes.

I need 4 or 8 bytes going in, and 4 or 8 bytes coming out (respectively)

Thanks!

*** Clarification:

I want to encrypt something small (ie 4 or 8 bytes) and obtain a result of a similar size. What's the simplest way to do it in C# while still using some key (with the built in libraries) rather than some mod and shift operations

A: 

That's not possible. RSA is a so-called block cipher (with variable block length).

The most well-known stream cipher is probably RC4, but .NET doesn't come with a built-in implementation. An algorithm with a small block size, like jonelf suggested, would probably be easiest. If the number of bytes isn't critical, I would use AES (block size 128 bits).

Is there a reason why you were originally looking at an asymmetric algorithm?

Thorarin
I should have clarified my question then. I want to encrypt something small (ie 4 or 8 bytes) and obtain a result of a similar size. What's the simplest way to do it in C# while still using some key (with the built in libraries) rather than some mod and shift operations
I must admit that I was looking into encrypting a number, and not remembering quite what it means, just use RSA (heck, it encrypts :)I'll look into the blowfish example...
+1  A: 

You could use Blowfish, it has a block size of 64 bits / 8 bytes. http://www.hotpixel.net/software.html#blowfishnet

Jonas Elfström
I'll look into this now.Thanks