解码和编码字符串 - 对称算法的硬编码密钥

发布于 2024-11-25 06:17:12 字数 3482 浏览 1 评论 0原文

我写了下面的类来编码和解码字符串数据(一键对称算法):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace MyProject.Classes
{
    public static class SymmetricEncryption
    {
        private const string MyKey = "bla bla bla";

        private static string _AlgorithmName;
        public static string AlgorithmName
        {
            get { return _AlgorithmName; }
            set { _AlgorithmName = value; }
        }

        public static string EncryptData(string ClearData)
        {
            // Convert string ClearData to byte array
            byte[] ClearData_byte_Array = Encoding.UTF8.GetBytes(ClearData);

            // Now Create The Algorithm
            SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
            Algorithm.Key = Encoding.UTF8.GetBytes(MyKey);

            // Encrypt information
            MemoryStream Target = new MemoryStream();

            // Append IV
            Algorithm.GenerateIV();
            Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);

            // Encrypt Clear Data
            CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(ClearData_byte_Array, 0, ClearData_byte_Array.Length);
            cs.FlushFinalBlock();

            // Output
            byte[] Target_byte_Array = Target.ToArray();
            string Target_string = Convert.ToBase64String(Target_byte_Array);
            return Target_string;
        }

        public static string DecryptData(string EncryptedData)
        {
            byte[] EncryptedData_byte_Array = Convert.FromBase64String(EncryptedData);

            // Now Create The Algorithm
            SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
            Algorithm.Key = Encoding.UTF8.GetBytes(MyKey);

            // Decrypt information
            MemoryStream Target = new MemoryStream();

            // Read IV
            int ReadPos = 0;
            byte[] IV = new byte[Algorithm.IV.Length];
            Array.Copy(EncryptedData_byte_Array, IV, IV.Length);
            Algorithm.IV = IV;
            ReadPos += Algorithm.IV.Length;

            // Decrypt Encrypted Data
            CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(EncryptedData_byte_Array, ReadPos, EncryptedData_byte_Array.Length - ReadPos);
            cs.FlushFinalBlock();

            // Output
            byte[] Target_byte_Array = Target.ToArray();
            string Target_string = Encoding.UTF8.GetString(Target_byte_Array);
            return Target_string;
        }


    }
}

和用法如下:

protected void Page_Load(object sender, EventArgs e)
{
    SymmetricEncryptionUtility.AlgorithmName = "TripleDES";
    Response.Write(SymmetricEncryptionUtility.EncryptData("1234-4567-8910-2345"));
}

我有一些关于 MyKey 的问题 -> 我们如何为对称算法提供硬编码密钥并在上层使用它?

上层代码错误如下:

“/”应用程序中的服务器错误。
<小时>
 指定的密钥对于该算法来说不是有效的大小。 
    描述:在执行期间发生未处理的异常。

执行当前的网络请求。请检查堆栈跟踪 有关该错误及其起源的更多信息 代码。

 异常详细信息:

System.Security.Cryptography.CryptographyException:指定的密钥是 对于该算法来说不是有效的大小。

我该如何修复这个错误?

提前致谢

i wrote the below class for encoding and decoding string data (Symmetric Algorithm With One Key):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace MyProject.Classes
{
    public static class SymmetricEncryption
    {
        private const string MyKey = "bla bla bla";

        private static string _AlgorithmName;
        public static string AlgorithmName
        {
            get { return _AlgorithmName; }
            set { _AlgorithmName = value; }
        }

        public static string EncryptData(string ClearData)
        {
            // Convert string ClearData to byte array
            byte[] ClearData_byte_Array = Encoding.UTF8.GetBytes(ClearData);

            // Now Create The Algorithm
            SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
            Algorithm.Key = Encoding.UTF8.GetBytes(MyKey);

            // Encrypt information
            MemoryStream Target = new MemoryStream();

            // Append IV
            Algorithm.GenerateIV();
            Target.Write(Algorithm.IV, 0, Algorithm.IV.Length);

            // Encrypt Clear Data
            CryptoStream cs = new CryptoStream(Target, Algorithm.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(ClearData_byte_Array, 0, ClearData_byte_Array.Length);
            cs.FlushFinalBlock();

            // Output
            byte[] Target_byte_Array = Target.ToArray();
            string Target_string = Convert.ToBase64String(Target_byte_Array);
            return Target_string;
        }

        public static string DecryptData(string EncryptedData)
        {
            byte[] EncryptedData_byte_Array = Convert.FromBase64String(EncryptedData);

            // Now Create The Algorithm
            SymmetricAlgorithm Algorithm = SymmetricAlgorithm.Create(AlgorithmName);
            Algorithm.Key = Encoding.UTF8.GetBytes(MyKey);

            // Decrypt information
            MemoryStream Target = new MemoryStream();

            // Read IV
            int ReadPos = 0;
            byte[] IV = new byte[Algorithm.IV.Length];
            Array.Copy(EncryptedData_byte_Array, IV, IV.Length);
            Algorithm.IV = IV;
            ReadPos += Algorithm.IV.Length;

            // Decrypt Encrypted Data
            CryptoStream cs = new CryptoStream(Target, Algorithm.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(EncryptedData_byte_Array, ReadPos, EncryptedData_byte_Array.Length - ReadPos);
            cs.FlushFinalBlock();

            // Output
            byte[] Target_byte_Array = Target.ToArray();
            string Target_string = Encoding.UTF8.GetString(Target_byte_Array);
            return Target_string;
        }


    }
}

and usage like below :

protected void Page_Load(object sender, EventArgs e)
{
    SymmetricEncryptionUtility.AlgorithmName = "TripleDES";
    Response.Write(SymmetricEncryptionUtility.EncryptData("1234-4567-8910-2345"));
}

i have some problem about MyKey -> how can we have hard coded key for Symmetric Algorithms and use it in the upper class ?

the upper codes ERROR is like below :

    Server Error in '/' Application.

    Specified key is not a valid size for this algorithm. 
    Description: An unhandled exception occurred during the

execution of the current web request. Please review the stack trace
for more information about the error and where it originated in the
code.

    Exception Details:

System.Security.Cryptography.CryptographicException: Specified key is
not a valid size for this algorithm.

how can i fix this error ?

thanks in advance

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

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

发布评论

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

评论(2

痴骨ら 2024-12-02 06:17:12

您可以使用 System.Security.Cryptography.Rfc2898DeriveBytes 根据 string 密码和 byte[] 安全地为密钥生成正确的字节数> salt:

var helper = new Rfc2898DeriveBytes(password, salt);
algorithm.Key = helper.GetBytes(algorithm.KeySize / 8);

有关 Rfc2898DeriveBytes 以及如何使用它的更多信息,请查看其 MSDN 上的页面

You can use System.Security.Cryptography.Rfc2898DeriveBytes to securely generate the correct number of bytes for your key based on a string password and byte[] salt:

var helper = new Rfc2898DeriveBytes(password, salt);
algorithm.Key = helper.GetBytes(algorithm.KeySize / 8);

For more information about Rfc2898DeriveBytes and how to use it, check out its page on MSDN.

孤者何惧 2024-12-02 06:17:12

阅读错误并查看 TripleDES.Key

该算法支持从 128 位到 192 位的密钥长度(以 64 位为增量)。

这意味着例如

private const string MyKey = "bla bla bla blah";

可以工作。

您没有询问这一点,但我不确定将此类创建为静态是一个好主意。如果您在代码中的两个不同位置使用它,可能会导致意外结果,因为 AlgorithmName 是静态的。

另外,我认为拥有恒定的密钥但可变的算法是没有意义的,特别是因为不同的算法需要不同长度的密钥。

Read the error and look at the documentation for TripleDES.Key:

This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits.

That means for example

private const string MyKey = "bla bla bla blah";

would work.

You didn't ask about this, but I'm not sure creating this class as static is a good idea. If you used it from two different places in your code, it could result in unexpected results, because AlgorithmName is static.

Also, I don't think it makes sense to have a constant key but variable algorithm, especially since different algorithms require keys of different lengths.

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