通用应用程序c#WP 8.1中的TripleDES加密

时间:2015-07-22 08:05:14

标签: c# windows-phone-8.1 win-universal-app tripledes

public static string tripleDESEncryptor(string toEncrypt, string keyString)
{

    var crypt = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesEcb);
    IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);
    IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(keyString, BinaryStringEncoding.Utf8);
    CryptographicKey key = crypt.CreateSymmetricKey(keyBuffer);            
    var sigBuffer = CryptographicEngine.Sign(key, buffer);  // throws exception here
    string signature = CryptographicBuffer.EncodeToBase64String(sigBuffer);
    return signature;
}

这会抛出一个InvalidCastException,我似乎无法弄清楚为什么或我做错了什么。

keyString长度为24。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

感谢您的帮助,这对我有用 -

public static string tripleDESEncryptor(string toEncrypt, string keyString)
{
   var crypt = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesEcbPkcs7);

            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);
            IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(keyString, BinaryStringEncoding.Utf8);

            CryptographicKey key = crypt.CreateSymmetricKey(keyBuffer);

            IBuffer signed = CryptographicEngine.Encrypt(key, buffer, null);

            string signature = CryptographicBuffer.EncodeToBase64String(signed);
            return signature;
}