用BC解密字符串

问题描述 投票:0回答:1

我有一个使用 Grails 6.1.2 编写的 Web 应用程序。我必须加密数据库中的几个字段,因此我决定使用基于著名的 jasypt 库的 grails-jasypt。它就像一个魅力。

现在我必须编写一个小型 C# 应用程序,并且需要访问数据库以读取其中一些加密字段。当然,从我拥有的属性中,我知道网络应用程序使用的密码和算法:

jasypt {
    algorithm = "PBEWITHSHA256AND256BITAES-CBC-BC"
    providerName = "BC"
    password = "my-strong-pwd"
    keyObtentionIterations = 1000 }

不幸的是,Grails 中的插件隐藏了所有用于加密字符串的代码,我只是在域中添加此映射,以确保加密和解密我需要的内容:

static mapping = { dbPassword type: GormEncryptedStringType } 

我用 C# 编写了这个静态函数来解密从数据库中获取的字符串:

 public static string Decrypt(string toDecrypt)
    {
        byte[] decoded = Convert.FromBase64String(toDecrypt);
        if (decoded == null || decoded.Length <= 16)
        {
            throw new ArgumentException("Bad input data", "toDecrypt");
        }

        byte[] salt = new byte[16];
        byte[] wrappedKey = new byte[decoded.Length - 16];
        Array.Copy(decoded, 0, salt, 0, 16);
        Array.Copy(decoded, 16, wrappedKey, 0, decoded.Length - 16);

        int iterationCount = 1000;
        string algName = "PBEWITHSHA256AND256BITAES-CBC-BC";

        PbeParametersGenerator generator = new Pkcs5S2ParametersGenerator(new Org.BouncyCastle.Crypto.Digests.Sha256Digest());
        generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(key.ToCharArray()), salt, iterationCount);

        ICipherParameters parameters = generator.GenerateDerivedParameters("AES", 256);

        IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CBC/NoPadding");
        cipher.Init(false, new ParametersWithIV(parameters, new byte[16])); // Assuming 16-byte IV

        byte[] keyText = cipher.DoFinal(wrappedKey);
        return Convert.ToBase64String(keyText);
    }

这有效,但字符串没有被正确解密,我对 BC 不太了解,我可能必须更改 GetCipher 字符串,但我不知道用什么。我尝试使用 AES/CBC/PKCS5Padding 添加填充,但出现“填充块损坏”

c# encryption grails bouncycastle jasypt
1个回答
0
投票

使用

PBEWITHSHA256AND256BITAES-CBC-BC
的解密执行不正确,以下实现有效:

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;

...

// input data
string algorithm = "PBEWITHSHA256AND256BITAES-CBC-BC";
int iterations = 1000;
string password = "dfglhkgfhljktypoio34537567--,dfd435";
string encryptedDataB64 = "Xw4VoIGs7FtD71gVwrDlCweSK7S/Z8ikg39rTxdiOcg=";

// separate salt and ciphertext
byte[] encryptedData = Convert.FromBase64String(encryptedDataB64);
byte[] salt = encryptedData[0..16];
byte[] ciphertext = encryptedData[16..];

// decrypt with PBEWITHSHA256AND256BITAES-CBC-BC
IBufferedCipher cipher = CipherUtilities.GetCipher(algorithm);
Asn1Encodable algParams = PbeUtilities.GenerateAlgorithmParameters(algorithm, salt, iterations);
ICipherParameters cipherParams = PbeUtilities.GenerateCipherParameters(algorithm, password.ToCharArray(), algParams);
cipher.Init(false, cipherParams);
byte[] decrypted = cipher.DoFinal(ciphertext);

// UTF-8 decode and output
Console.WriteLine(Encoding.UTF8.GetString(decrypted)); // Test1234$$
© www.soinside.com 2019 - 2024. All rights reserved.