以字符串形式存储/转换加密密钥和IV [英] Storing/Converting the encryption key and IV as strings

查看:74
本文介绍了以字符串形式存储/转换加密密钥和IV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究许多不同的C#加密示例.在大多数示例中,加密密钥和初始化向量(IV)作为字节数组传递到加密/解密方法中.

I have been looking at a lot of different C# encryption examples. In most examples the encryption Key as well as the Initialization Vector (IV) are passed into the encryption/decryption methods as an array of bytes.

我想将Key和IV存储为字符串.硬件安全模块中的密钥,SQL Server数据库中的IV作为nvarchar.

I would like to store the Key and IV as strings. The Key in a Hardware Security Module and the IV as an nvarchar in the SQL Server database.

我一直遇到有关如何正确地将Key和IV转换为字符串的问题.一些示例说使用Base64编码,而其他示例使用 Encoding.UTF8 .

I keep running into propblems on how to properly convert the Key and the IV as string. Some examples say to use Base64 Encoding while other examples use Encoding.UTF8.

这里是一个生成IV并将其转换为Base64字符串的示例...

Here is an example that generates an IV and converts it to a Base64 string...

using (var aesProvider = new AesCryptoServiceProvider())
{
    aesProvider.GenerateIV();
    var ivBase64 = Convert.ToBase64String(aesProvider.IV);
    return ivBase64;
}

但是,当我将IV的此字符串表示形式传递给加密方法,然后将其转换回字节数组时,以下代码失败,表明IV的大小不正确.

However, when I pass this string representation of the IV into the encryption method and then convert it back to a byte array the following code fails saying the IV is not the proper size.

byte[] initVectorBytes = Encoding.UTF8.GetBytes(initializationVector);`
// intermediate code excluded for brevity
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);

是否存在在字节数组和字符串表示形式之间来回转换加密密钥和IV的标准方法?

Is there a standard way of converting an encryption Key and IV back and forth between a byte array and String representation?

推荐答案

您不能将二进制数据转换为UTF-8并再次转换.某些二进制序列不是有效的UTF-8字符,当您转换为UTF-8时,数据将丢失.相当于将某些字符设置为?"在两种编码之间进行转换时.

You cannot convert binary data to UTF-8 and back again. Some binary sequences are not valid UTF-8 characters and when you convert to UTF-8 that data is lost. It's the equivalent of some characters getting set to '?' when converting between encodings.

您可以改为使用二进制数据的base64编码转换为文本,然后使用base64解码以获取原始二进制.

You can instead use base64 encoding of binary data to text, and then base64 decode to get back the original binary.

尝试将其转换为UTF-8,例如:"\ x00?\ xdc \ x80"(这是四个字节:0、63、220、128).它不会编码为UTF-8-无效.

Try converting this to UTF-8, for example: "\x00?\xdc\x80" (that's four bytes: 0, 63, 220, 128). It won't encode to UTF-8 -- it's not valid.

标准方法是使用Base-64编码-如何我如何编码和解码base64字符串?

The standard way is using Base-64 encoding - How do I encode and decode a base64 string?

这篇关于以字符串形式存储/转换加密密钥和IV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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