如何在c#中为加密方法编写解密方法

发布于 2025-01-04 16:46:02 字数 2090 浏览 6 评论 0原文

我能够将如下所示的加密示例放在一起,但在解密过程中我得到无效数据(异常)。我应该如何解密

加密方法

public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
        {

            byte[] cryptoBytes = Encoding.UTF8.GetBytes(plainText);

            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;
                using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
                }
            }
            return Convert.ToBase64String(cryptoBytes);
        }

解密方法

 public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
        {
            byte[] decryptedByte;
            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;

                using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    byte[] cipherBytes = Convert.FromBase64String(cipherText);
                    decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);

                }
            }
            return Encoding.UTF8.GetString(decryptedByte);
        }

我认为问题出在这些方法内部的所有编码

示例数据

plainText = stackoverflow

base64encoded Key = B8Y/6doxwqU870C6jzYWhsr3hKSLokAOkkLCDiy+TS4= (应该很容易转换为字节不是吗)

base64encoded IV = NZIpD60eBmdsOFFhA2bfvw==

encryptedValue = 77+977+977+977+977+9Ce+/ve+/vQ3vv70F77+9UzHvv73vv70=< /code>

我提供相同的加密值、IV 和密钥解密到 Stackoverflow

I was able to put together a encryption sample like below but during decryption i get invalid data(Exception). How am i supposed to decrypt

Encryption Method

public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
        {

            byte[] cryptoBytes = Encoding.UTF8.GetBytes(plainText);

            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;
                using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
                }
            }
            return Convert.ToBase64String(cryptoBytes);
        }

Decryption Method

 public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
        {
            byte[] decryptedByte;
            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;

                using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    byte[] cipherBytes = Convert.FromBase64String(cipherText);
                    decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);

                }
            }
            return Encoding.UTF8.GetString(decryptedByte);
        }

i think the problem is with all the encoding that are going inside these methods

Sample Data

plainText = stackoverflow

base64encoded Key = B8Y/6doxwqU870C6jzYWhsr3hKSLokAOkkLCDiy+TS4=
(should be easy to convert to bytes ain't it)

base64encoded IV = NZIpD60eBmdsOFFhA2bfvw==

encryptedValue = 77+977+977+977+977+9Ce+/ve+/vQ3vv70F77+9UzHvv73vv70=

I provide same encrypted value , IV and Key to decrypt to Stackoverflow

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

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

发布评论

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

评论(3

坦然微笑 2025-01-11 16:46:02

我认为你的问题是你的静脉注射的长度,也许是关键。我记得 IV 应该是 16 个字节长,密钥有不同的选项,你应该查一下。

//测试:

        RijndaelManaged alg = new RijndaelManaged();

        alg.GenerateKey();
        alg.GenerateIV();

        byte[] key = alg.Key;
        byte[] iv = alg.IV;

        string text = "teststring";

        string encrypted = EncryptWithAes(text, key, iv);

        MessageBox.Show(encrypted);

        String result = DecryptAesCryptoString(encrypted, key, iv);

        MessageBox.Show(result);

I think your problem is the length of your IV and maybe the key. The IV should be 16 bytes long as i recall, the key has different options, you should look that up.

//TEST:

        RijndaelManaged alg = new RijndaelManaged();

        alg.GenerateKey();
        alg.GenerateIV();

        byte[] key = alg.Key;
        byte[] iv = alg.IV;

        string text = "teststring";

        string encrypted = EncryptWithAes(text, key, iv);

        MessageBox.Show(encrypted);

        String result = DecryptAesCryptoString(encrypted, key, iv);

        MessageBox.Show(result);
梨涡少年 2025-01-11 16:46:02

可悲的是,这肯定是由于编码问题造成的。现在解决了,如下

加密

public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
        {
            byte[] cryptoBytes = Convert.FromBase64String(plainText);
            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;
                using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
                }
            }
            return Convert.ToBase64String(cryptoBytes);
        }

解密

public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
{

    byte[] decryptedByte;
    using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
    {
        aesAlgorithm.Key = key;
        aesAlgorithm.IV = initiationVector;
        aesAlgorithm.Mode = CipherMode.ECB;
        using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);

        }
    }
    return Convert.ToBase64String(decryptedByte);
}

and sadly this was certainly due to the Encoding problem. Now solved it like below

Encryption

public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
        {
            byte[] cryptoBytes = Convert.FromBase64String(plainText);
            using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
            {
                aesAlgorithm.Key = key;
                aesAlgorithm.IV = initiationVector;
                aesAlgorithm.Mode = CipherMode.ECB;
                using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
                {
                    cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
                }
            }
            return Convert.ToBase64String(cryptoBytes);
        }

Decryption

public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
{

    byte[] decryptedByte;
    using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
    {
        aesAlgorithm.Key = key;
        aesAlgorithm.IV = initiationVector;
        aesAlgorithm.Mode = CipherMode.ECB;
        using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);

        }
    }
    return Convert.ToBase64String(decryptedByte);
}
萝莉病 2025-01-11 16:46:02

为什么你不尝试删除 Encoding 呢?
这是一个简单的实现

public class RijndaelSimpleTest
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        string   plainText          = "Hello, World!";    // original plaintext

        string   passPhrase         = "Pas5pr@se";        // can be any string
        string   saltValue          = "s@1tValue";        // can be any string
        string   hashAlgorithm      = "SHA1";             // can be "MD5"
        int      passwordIterations = 2;                  // can be any number
        string   initVector         = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
        int      keySize            = 256;                // can be 192 or 128

        Console.WriteLine(String.Format("Plaintext : {0}", plainText));

        string  cipherText = RijndaelSimple.Encrypt(plainText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Encrypted : {0}", cipherText));

        plainText          = RijndaelSimple.Decrypt(cipherText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Decrypted : {0}", plainText));
    }
}

Why you don't give a try by removing the Encoding ?
Here's a simple implementation :

public class RijndaelSimpleTest
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        string   plainText          = "Hello, World!";    // original plaintext

        string   passPhrase         = "Pas5pr@se";        // can be any string
        string   saltValue          = "s@1tValue";        // can be any string
        string   hashAlgorithm      = "SHA1";             // can be "MD5"
        int      passwordIterations = 2;                  // can be any number
        string   initVector         = "@1B2c3D4e5F6g7H8"; // must be 16 bytes
        int      keySize            = 256;                // can be 192 or 128

        Console.WriteLine(String.Format("Plaintext : {0}", plainText));

        string  cipherText = RijndaelSimple.Encrypt(plainText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

        Console.WriteLine(String.Format("Encrypted : {0}", cipherText));

        plainText          = RijndaelSimple.Decrypt(cipherText,
                                                    passPhrase,
                                                    saltValue,
                                                    hashAlgorithm,
                                                    passwordIterations,
                                                    initVector,
                                                    keySize);

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