Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

encryption - C# Org.BouncyCastle.Crypto.InvalidCipherTextException: 'mac check in GCM failed'

Im trying to code a Chrome Cookie Decryptor in C#. Im using System.Data.Sqlite to read the DB and Im using Org.Bouncycastle to decrypt the encrypted_value in %AppData%LocalGoogleChromeUser DataDefaultCookies (Chorme's Cookie DB) with the Key stored in C:UsersUserAppDataLocalGoogleChromeUser DataLocal State

My Code is:

public static string Decrypt_AES_256_GCM(byte[] msg, byte[] key)
{
    if (key == null || key.Length != 256 / 8)
        throw new ArgumentException($"Key needs to be 256 bit!", "key");
    if (msg == null || msg.Length == 0)
        throw new ArgumentException("Message required!", "message");

    using (var cipherStream = new MemoryStream(msg))
    using (var cipherReader = new BinaryReader(cipherStream))
    {
        cipherReader.ReadBytes(3);
        var cipher = new GcmBlockCipher(new AesEngine());
        cipher.Init(false, new AeadParameters(new KeyParameter(key), 128, cipherReader.ReadBytes(96 / 8), msg));
        var cipherText = cipherReader.ReadBytes(msg.Length);
        var plainText = new byte[cipher.GetOutputSize(cipherText.Length)];
        try
        {
            int len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
            cipher.DoFinal(plainText, len);
        }
        catch (InvalidCipherTextException)
        {
            return null;
        }
        return Encoding.Default.GetString(plainText);
    }
}

This is the Code for the Key:

public byte[] GetKey()
{
    string keyFileText = File.ReadAllText(ChromeKeyPath); // reads the file (string)

    var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(keyFileText), new System.Xml.XmlDictionaryReaderQuotas());
    var root = XElement.Load(jsonReader);
    string encryptedKey = root.XPathSelectElement("//os_crypt/encrypted_key").Value;

    return ProtectedData.Unprotect(Convert.FromBase64String(encryptedKey).Skip(5).ToArray(), null, DataProtectionScope.LocalMachine); // decrypts the key and returns a byte Array
}

(I got the Code from https://stackoverflow.com/a/60611673/12955591)

However i get this Error: enter image description here

The Error was thrown here: cipher.DoFinal(plainText, len);

Can someone please help me understand the error?

question from:https://stackoverflow.com/questions/65889216/c-sharp-org-bouncycastle-crypto-invalidciphertextexception-mac-check-in-gcm-fa

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...