与16字节的Rijndael初始化向量 [英] Rijndael initialization vector with 16 bytes

查看:222
本文介绍了与16字节的Rijndael初始化向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不得不信用卡号码进行加密,并存储在数据库中为字符串。我做了以下

I have to credit card number to be encrypted and stored in database as a string. I do the following

RijndaelManaged rijMan = new RijndaelManaged();
byte[] encrypt = Encrypt(txtCredit.Text, rijMan.Key, rijMan.IV);
string card = Convert.ToBase64String(encrypt);
string key = Convert.ToBase64String(rijMan.Key);
string iv = Convert.ToBase64String(rijMan.IV);

这就是加密功能:

and this is encrypt function:

public static byte[] Encrypt(string message, byte[] key, byte[] iv)
{
    byte[] encrypted;
    using (RijndaelManaged rijMan = new RijndaelManaged())
    {
        rijMan.Key = key;
        rijMan.IV = iv;
        ICryptoTransform encrypt = rijMan.CreateEncryptor(rijMan.Key, rijMan.IV);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cs))
                {
                    sw.Write(message);
                }
                encrypted = ms.ToArray();
            }
        }
    }
    return encrypted;
}

和我他们都存储在数据库中。这似乎是罚款。但是,当我回到检索数据库,从串并使用 System.Text.Encoding.UTF8.GetBytes(串)转换为字节,它抛出一个异常

And i store them all in database. This seems to be fine. But when i retrieve back the string from database and use System.Text.Encoding.UTF8.GetBytes(string) to convert to byte, it throws an exception

指定初始化向量(IV)不为这种算法的块大小匹配

Specified initialization vector (IV) does not match the block size for this algorithm.

是否有可能产生四使得它是16个字节?在此先感谢您的答复。

Is it possible to generate the IV such that it is 16 bytes ? Thanks in advance for the reply

推荐答案

在您的文章的顶部使用的是BASE64算法,以四字节转换为字符串

In the top of your post you are using BASE64 algorithm to convert IV bytes to string

string ivString = Convert.ToBase64String(rijMan.IV);

,然后在您的文章的底部,你正在使用UTF8编码读取字符串转换成字节数组

and then in the bottom of your post you are using UTF8 encoding to read string into byte array

byte[] iv = System.Text.Encoding.UTF8.GetBytes(ivString);

但你应该再次使用BASE64算法:

but you should use BASE64 algorithm again:

byte[] iv = Convert.FromBase64String(ivString);

BTW:我希望你不存储在同一个数据库加密的信用卡号码AES密钥(rijMan.Key),因为这将使整个加密完全没用

BTW: I hope you are not storing AES key (rijMan.Key) in the same database as your encrypted credit card number because that would make whole encryption completely useless.

这篇关于与16字节的Rijndael初始化向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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