开发者

Decrypted text from AES encryption has extra spaces

I'm trying to decrypt passwords that were stored in a database from a standard SqlMembershipProvider. In order to do this, I hacked together following console app:

    static void Main(string[] args)
    {
        const string encryptedPassword = @"wGZmgyql4prPIr7t1uaxa+RBRJC51qOPBO5ZkSskUtUCY1aBpqNifQGknEfWzky4";
        const string iv = @"Jc0RhfDog8SKvtF9aI+Zmw==";
        var password = Decrypt(encryptedPassword, iv);

        Console.WriteLine(password);
        Console.ReadKey();
    }

    public static string Decrypt(string toDecrypt, string iv)
    {
        var ivBytes = Convert.FromBase64String(iv);
        const string decryptKey = "DECRYPTION_KEY_HERE";
 开发者_如何学编程       var keyArray = StringToByteArray(decryptKey);
        var toEncryptArray = Convert.FromBase64String(toDecrypt);
        var rDel = new AesCryptoServiceProvider() { Key = keyArray, IV = ivBytes};
        var cTransform = rDel.CreateDecryptor();
        var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        return Encoding.UTF8.GetString(resultArray);
    }

    public static byte[] StringToByteArray(String hex)
    {
        var numberChars = hex.Length;
        var bytes = new byte[numberChars / 2];
        for (var i = 0; i < numberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        return bytes;
    }

This does indeed decrypt the text, however instead of the resulting text being something like "Password1", it's "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0P\0a\0s\0s\0w\0o\0r\0d\01\0" which writes to the console as a bunch of spaces, then "P a s s w o r d 1". Any ideas what I'm doing wrong?


I suspect that part of the problem might be that the original password was encoded as UTF-16 before encryption, and you're decoding it as UTF-8. Try changing the final line of your Decrypt method:

return Encoding.Unicode.GetString(resultArray);

That doesn't explain all those spurious leading zeros though. Very strange...

EDIT...

Actually, I seem to remember that SqlMembershipProvider prefixes the password bytes with a 16-byte salt before encryption, in which case you'll probably be able to get away with something like this:

return Encoding.Unicode.GetString(resultArray, 16, resultArray.Length - 16);

But that still doesn't explain why those 16 bytes are all zeros rather than a bunch of random values...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜