How do I encrypt a string in vb.net using Rijndael

2019-01-20 11:26发布

问题:

I use the following code to initialize encryption...

 Dim symmetricKey As New System.Security.Cryptography.RijndaelManaged()
 With symmetricKey
   .Key = Encoding.ASCII.GetBytes(Key)
   .IV = Encoding.ASCII.GetBytes(IV)
   .Mode = CipherMode.CBC
   .BlockSize = 128 
   .KeySize = 128 
   .Padding = PaddingMode.PKCS7
End With

The requirement is to use PKCS5. Padding modes in vb.net only include

  • ANSIX923
  • ISO10126
  • None
  • PKCS7
  • Zeros

So I don't think there is a method for PKCS5. Is there any way to add it, or do I need to write an encryption method myself? If so - how do I write that? Is there a reliable DLL that will support it?

回答1:

PKCS7 padding and PKCS5 padding are the same thing. In this context they are synonyms.

EDIT:

The PKCS#7 padding is described in the PKCS#7 spec in section 10.3. PKCS#5 padding is described in the PKCS#5 spec in section 6.1.1 step 4. As you can see by examination, the padding algorithms are identical.



回答2:

I guess that you need someone else to read your encrypted data, and then only understand that kind of padding.

As you probably know, PKCS5 is explained as:

PKCS#5 padding works as follows: the bytes remaining to fill a block are assigned a number, which is the number of bytes that were added to fill the block. For instance, if we have an 16-byte block, and only 11 bytes are filled, then we have 5 bytes to pad. Those 5 bytes are all assigned the value "5", for the 5 bytes of padding.

Well, you have your info - encode the string to byte[], extend it so it is aligned to 16 bytes, and fill the rest according to the recipe. Then, encrypt with Padding.None.

Guess it shouldn't be so troublesome. Anyway, there is no string encryption, so since you encode the stuff to byte[] anyway, ...

string message="lorem ipsum and stuff";
byte[] result=Text.Encode(message);
int packets=result.Length/16;
int paddingSize=16-(result.Length-(packets*16));
if (paddingSize!=16) 
{
    byte[] newbuffer=new byte[result.Length+paddingSize];
    packets.CopyTo(newbuffer);
    for (int n=result.Length;n<newbuffer.Length;n++)
    {
        newbuffer[n]=16-paddingsize;
    }
}
//  then, encrypt result or newbuffer, depending on if padding is 16 or not

NOTE: code is out of my head, it's not runable at all...