close

 

        private const string strKey = "Key";
        private const string strIV = "IV";

        public static string Encrypt(string message) 
        {
            if (string.IsNullOrEmpty(message))
            {
                return string.Empty;
            }

            var keyBuffer = CryptographicBuffer.ConvertStringToBinary(strKey, BinaryStringEncoding.Utf8);
            var ivBuffer = CryptographicBuffer.ConvertStringToBinary(strIV, BinaryStringEncoding.Utf8);
            var messageBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);

            var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.DesCbcPkcs7);
            var key = provider.CreateSymmetricKey(keyBuffer);
            var buffEncrypt = CryptographicEngine.Encrypt(key, messageBuffer, ivBuffer);

            return CryptographicBuffer.EncodeToBase64String(buffEncrypt);
        }

        public static string Decrypt(string encryptedBase64String)
        {
            if (string.IsNullOrEmpty(encryptedBase64String))
            {
                return string.Empty;
            }

            var buffer = CryptographicBuffer.ConvertStringToBinary(strKey, BinaryStringEncoding.Utf8);
            var ivBuffer = CryptographicBuffer.ConvertStringToBinary(strIV, BinaryStringEncoding.Utf8);

            var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.DesCbcPkcs7);
            var keyBuffer = provider.CreateSymmetricKey(buffer);
            
            var decryptedBuffer = CryptographicEngine.Decrypt(keyBuffer, CryptographicBuffer.DecodeFromBase64String(encryptedBase64String), ivBuffer);
            return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuffer);
        }

 

參考資料:

http://www.dotnetspeak.com/winrt/encrypting-and-decrypting-data-in-winrt-2/

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 小賢 的頭像
    小賢

    小賢的部落格

    小賢 發表在 痞客邦 留言(0) 人氣()