简体   繁体   中英

MachineKey.Encode output is hex how do i set it do base64?

I'm trying to match the viewstate encryption in my code, my issue is that the output of MachineKey.Encode is hex encoded and not base64 encoded. My code is:

        var plaintextBytes = Encoding.UTF8.GetBytes("Hello");
        var encryptedValue = MachineKey.Encode(plaintextBytes, MachineKeyProtection.All);
        EncryptedData.Text = encryptedValue;

        var decryptedBytes = MachineKey.Decode(encryptedValue, MachineKeyProtection.All);
        DecryptedData.Text = Encoding.UTF8.GetString(decryptedBytes);

Do you have any idea how i can make that code output a base64 encoded string just like the viewstate data is encrypted?

First off, consider using MachineKey.Protect and .Unprotect, as Encode and Decode are obsolete.

Protect returns a byte[], which you can just pass to Convert.ToBase64String

 byte[] encryptedValue = MachineKey.Protect(Encoding.UTF8.GetBytes("Hello"), "Some reason or another");
 string encryptedUTF8 = Convert.ToBase64String(encryptedValue);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM