Bouncy castle AES加密中的编码类型和密钥问题

发布于 2024-11-05 15:44:29 字数 2985 浏览 0 评论 0原文

我正在使用 Bouncy Castle 加密库。我有一个 13 个字符的密钥,类似于 字符串键=“wergt543jusft”; 需要加密的文本为:string plain = "435625241526373";

我使用以下方法将其转换为 128 位密钥。

public string getKeyMessageDigest(string key)
{
    byte[] ByteData = Encoding.ASCII.GetBytes(key);

    //MD5 creating MD5 object.
    MD5 oMd5 = MD5.Create();
    byte[] HashData = oMd5.ComputeHash(ByteData);

    //convert byte array to hex format
    StringBuilder oSb = new StringBuilder();
    for (int x = 0; x < HashData.Length; x++)
    {
        //hexadecimal string value
        oSb.Append(HashData[x].ToString("x2"));
    }
    return Convert.ToString(oSb);
}

然后,我创建一个 AESEncryption 类的对象,我已定义

AESEncryption aes = new AESEncryption(Encoding.ASCII, new Pkcs7Padding());

该类 AESEncryption 有两种方法:

public string Encrypt(string plain, string key)
{
    string hashKey = getKeyMessageDigest(key);
    BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
    bcEngine.SetPadding(_padding);
    return bcEngine.Encrypt(plain, hashKey);
}

public string Decrypt(string plain, string key)
{
    string hashKey = getKeyMessageDigest(key);
    BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
    bcEngine.SetPadding(_padding);
    return bcEngine.Decrypt(plain, hashKey);
}

一切正常。

但是,当我将编码类型更改为 ASCII 以外的任何类型时,我收到错误“密钥长度不是 128/192/256 位。”。我在代码中进行了以下更改来更改编码类型:

public string getKeyMessageDigest(string key)
{
    byte[] ByteData = Encoding.UTF32.GetBytes(key);
    //MD5 creating MD5 object.
    MD5 oMd5 = MD5.Create();
    byte[] HashData = oMd5.ComputeHash(ByteData);

    //convert byte array to hex format
    StringBuilder oSb = new StringBuilder();
    for (int x = 0; x < HashData.Length; x++)
    {
        //hexadecimal string value
        oSb.Append(HashData[x].ToString("x2"));
    }
    return Convert.ToString(oSb);
}

并且

AESEncryption aes = new AESEncryption(Encoding.UTF32, new Pkcs7Padding());

代码的其余部分保持不变。有人可以指导一下吗?

预先感谢...

我正在点击链接: http://elian.co.uk/post/2009 /07/29/Bouncy-Castle-CSharp.aspx

我的目标是使用所有编码类型为变量 plian = "435625241526373" 生成加密字符串,例如: ASCII、BigEndianUnicode、Unicode、UTF32 UTF7,UTF8

[根据评论编辑] 该方法内部抛出异常:

private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{ 
    try 
    { 
        cipher = _padding == null ?
            new PaddedBufferedBlockCipher(_blockCipher) : 
            new PaddedBufferedBlockCipher(_blockCipher, _padding);

        byte[] keyByte = _encoding.GetBytes(key);
        _cipher.Init(forEncrypt, new KeyParameter(keyByte));
        return _cipher.DoFinal(input);

    }
    catch (Org.BouncyCastle.Crypto.CryptoException ex)
    {
        throw new CryptoException(ex.Message); 
    } 
} 

I am using Bouncy Castle crypto libraries. I have a 13 character key something like
string key = "wergt543jusft";
Text to be encrypted is: string plain = "435625241526373";

I convert it into 128 bit key using the following method.

public string getKeyMessageDigest(string key)
{
    byte[] ByteData = Encoding.ASCII.GetBytes(key);

    //MD5 creating MD5 object.
    MD5 oMd5 = MD5.Create();
    byte[] HashData = oMd5.ComputeHash(ByteData);

    //convert byte array to hex format
    StringBuilder oSb = new StringBuilder();
    for (int x = 0; x < HashData.Length; x++)
    {
        //hexadecimal string value
        oSb.Append(HashData[x].ToString("x2"));
    }
    return Convert.ToString(oSb);
}

Then, I create an object of AESEncryption class which I have defined

AESEncryption aes = new AESEncryption(Encoding.ASCII, new Pkcs7Padding());

Class AESEncryption has two methods:

public string Encrypt(string plain, string key)
{
    string hashKey = getKeyMessageDigest(key);
    BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
    bcEngine.SetPadding(_padding);
    return bcEngine.Encrypt(plain, hashKey);
}

public string Decrypt(string plain, string key)
{
    string hashKey = getKeyMessageDigest(key);
    BCEngine bcEngine = new BCEngine(new AesEngine(), _encoding);
    bcEngine.SetPadding(_padding);
    return bcEngine.Decrypt(plain, hashKey);
}

Everything works fine.

But, when I change the encoding type to anything other than ASCII, I get error "Key length not 128/192/256 bits.". I made the following chnages in my code to change the Encoding type:

public string getKeyMessageDigest(string key)
{
    byte[] ByteData = Encoding.UTF32.GetBytes(key);
    //MD5 creating MD5 object.
    MD5 oMd5 = MD5.Create();
    byte[] HashData = oMd5.ComputeHash(ByteData);

    //convert byte array to hex format
    StringBuilder oSb = new StringBuilder();
    for (int x = 0; x < HashData.Length; x++)
    {
        //hexadecimal string value
        oSb.Append(HashData[x].ToString("x2"));
    }
    return Convert.ToString(oSb);
}

AND

AESEncryption aes = new AESEncryption(Encoding.UTF32, new Pkcs7Padding());

Rest of the code remains the same. Can anyone please guide?

Thanks in advance...

I am following the link:
http://elian.co.uk/post/2009/07/29/Bouncy-Castle-CSharp.aspx

My aim is to generate the encrypted string for the variable plian = "435625241526373" using all encoding types such as:
ASCII,BigEndianUnicode,Unicode,UTF32
UTF7,UTF8

[Edit from comments]
The exception is thrown inside this method:

private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{ 
    try 
    { 
        cipher = _padding == null ?
            new PaddedBufferedBlockCipher(_blockCipher) : 
            new PaddedBufferedBlockCipher(_blockCipher, _padding);

        byte[] keyByte = _encoding.GetBytes(key);
        _cipher.Init(forEncrypt, new KeyParameter(keyByte));
        return _cipher.DoFinal(input);

    }
    catch (Org.BouncyCastle.Crypto.CryptoException ex)
    {
        throw new CryptoException(ex.Message); 
    } 
} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月亮是我掰弯的 2024-11-12 15:44:29

您需要确保您的密钥长度为 128/192/256 位。正如您在 EncryptDecrypt 方法中使用 getKeyMessageDigest 一样,您可以在 try/catch 子句中使用它创建密钥的 128 位哈希值:

private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{ 
    try 
    { 
        cipher = _padding == null ?
            new PaddedBufferedBlockCipher(_blockCipher) : 
            new PaddedBufferedBlockCipher(_blockCipher, _padding);

        // this line will make sure keyByte is 16 bytes long
        byte[] keyByte = getKeyMessageDigest(key);

        _cipher.Init(forEncrypt, new KeyParameter(keyByte));

        return _cipher.DoFinal(input);          
    }
    catch (Org.BouncyCastle.Crypto.CryptoException ex)
    {
        throw new CryptoException(ex.Message); 
    } 
} 

此外,您无需担心更改 getKeyMessageDigest 内的编码,传递编码只是为了确保实际数据的正确编码,而不是钥匙。

无论输入大小如何,MD5 哈希值始终包含 16 个字节。因此,唯一的问题是如果您使用 Encoding.GetBytes 来获取密钥,因为此方法针对不同的编码返回不同的数组长度。

You need to make sure that your key is 128/192/256 bits long. Just as you used getKeyMessageDigest inside Encrypt and Decrypt methods, you can use it inside the try/catch clause to create a 128-bit hash value of your key:

private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{ 
    try 
    { 
        cipher = _padding == null ?
            new PaddedBufferedBlockCipher(_blockCipher) : 
            new PaddedBufferedBlockCipher(_blockCipher, _padding);

        // this line will make sure keyByte is 16 bytes long
        byte[] keyByte = getKeyMessageDigest(key);

        _cipher.Init(forEncrypt, new KeyParameter(keyByte));

        return _cipher.DoFinal(input);          
    }
    catch (Org.BouncyCastle.Crypto.CryptoException ex)
    {
        throw new CryptoException(ex.Message); 
    } 
} 

Additionally, you don't need to worry about changing the encoding inside getKeyMessageDigest, encoding is passed around just to ensure correct encoding for the actual data, not the key.

MD5 hash always contains 16 bytes, regardless of the input size. So, the only problem is if you use Encoding.GetBytes to get the key, since this method returns different array lengths for different encodings.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文