程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> Windows 8 Store Apps學習(31) 加密解密: 哈希算法, 對稱算法

Windows 8 Store Apps學習(31) 加密解密: 哈希算法, 對稱算法

編輯:關於.NET

介紹

重新想象 Windows 8 Store Apps 之 加密解密

hash 算法(MD5, SHA1, SHA256, SHA384, SHA512)

hmac 算法(MD5, SHA1, SHA256, SHA384, SHA512)

本地數據的加密解密

對 稱算法(AES, DES, 3DES, RC2, RC4)

示例

1、演示如何使用 hash 算法(MD5, SHA1, SHA256, SHA384, SHA512)

Crypto/Hash.xaml.cs

/*
 * 演示如何使用 hash 算法(MD5, SHA1, SHA256, SHA384, SHA512)
 */
    
using System;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
    
namespace XamlDemo.Crypto
{
    public sealed partial class Hash : Page
    {
        public Hash()
        {
            this.InitializeComponent();
        }
    
        private void btnDemo_Click(object sender, RoutedEventArgs e)
        {
            string plainText = "i am webabcd";
    
            lblMsg.Text = "原文: " + plainText;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += Environment.NewLine;
    
            string[] algorithmNames = { "MD5", "SHA1", "SHA256", "SHA384", "SHA512" };
    
            foreach (var algorithmName in algorithmNames)
            {
                // 根據算法名稱實例化一個哈希算法提供程序
                HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(algorithmName);
                // hashAlgorithm.HashLength - 哈希後的值的長度,單位:字節
    
                // 原文的二進制數據
                IBuffer vector = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8);
    
                // 哈希二進制數據
                IBuffer digest = hashAlgorithm.HashData(vector);
    
                lblMsg.Text += algorithmName + ": " + CryptographicBuffer.EncodeToHexString(digest);
                lblMsg.Text += Environment.NewLine;
    
    
    
                // 創建一個可重用的 CryptographicHash 對象
                CryptographicHash reusableHash = hashAlgorithm.CreateHash();
                reusableHash.Append(CryptographicBuffer.ConvertStringToBinary("i ", BinaryStringEncoding.Utf8)); // 向 CryptographicHash 中追加需要哈希的二進制數據
                reusableHash.Append(CryptographicBuffer.ConvertStringToBinary("am ", BinaryStringEncoding.Utf8)); // 向 CryptographicHash 中追加需要哈希的二進制數據
                reusableHash.Append(CryptographicBuffer.ConvertStringToBinary("webabcd", BinaryStringEncoding.Utf8)); // 向 CryptographicHash 中追加需要哈希的二進制數據
    
                // 獲取哈希後的數據,然後清空 CryptographicHash 中的數據
                digest = reusableHash.GetValueAndReset();
    
                lblMsg.Text += algorithmName + ": " + CryptographicBuffer.EncodeToHexString(digest);
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += Environment.NewLine;
            }
        }
    }
}

2、演示如何使用 hmac 算法(HMAC_MD5, HMAC_SHA1, HMAC_SHA256, HMAC_SHA384, HMAC_SHA512 )

Crypto/Hmac.xaml.cs

/*
 * 演示如何使用 hmac 算法(HMAC_MD5, HMAC_SHA1, HMAC_SHA256, HMAC_SHA384, HMAC_SHA512)
 * 
 * 注:hmac 相當於帶密鑰的 hash,可以理解為將信息用密鑰加密後再哈希
 */
    
using System;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
    
namespace XamlDemo.Crypto
{
    public sealed partial class Hmac : Page
    {
        public Hmac()
        {
            this.InitializeComponent();
        }
    
        private void btnDemo_Click(object sender, RoutedEventArgs e)
        {
            string plainText = "i am webabcd";
    
            lblMsg.Text = "原文: " + plainText;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += Environment.NewLine;
    
            string[] algorithmNames = { "HMAC_MD5", "HMAC_SHA1", "HMAC_SHA256", "HMAC_SHA384", "HMAC_SHA512" };
    
            foreach (var algorithmName in algorithmNames)
            {
                // 根據算法名稱實例化一個 hmac 算法提供程序
                MacAlgorithmProvider hmacAlgorithm = MacAlgorithmProvider.OpenAlgorithm(algorithmName);
                // hmacAlgorithm.MacLength - hmac 後的值的長度,單位:字節
    
                // 創建一個用於 hmac 算法的隨機的 key
                IBuffer key = CryptographicBuffer.GenerateRandom(hmacAlgorithm.MacLength);
    
                // 根據 key 生成 CryptographicKey 對象
                CryptographicKey hmacKey = hmacAlgorithm.CreateKey(key);
    
                // 根據 hmacKey 簽名指定的內容
                IBuffer signature = CryptographicEngine.Sign(
                    hmacKey, // 簽名時所用的 key
                    CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8) // 需要簽名的內容
                );
    
                lblMsg.Text += algorithmName + ": " + CryptographicBuffer.EncodeToHexString(signature) + " (key: " + CryptographicBuffer.EncodeToHexString(key) + ")";
                lblMsg.Text += Environment.NewLine;
    
    
    
                // 驗證簽名
                bool isAuthenticated = CryptographicEngine.VerifySignature(
                    hmacKey, // 簽名時所用的 key
                    CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8), // 需要簽名的內容
                    signature // 簽名後的值
                );
    
                lblMsg.Text += "isAuthenticated: " + isAuthenticated;
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += Environment.NewLine;
            }
        }
    }
}

3、演示如何對本地數據進行加密和解密

Crypto/LocalCrypto.xaml.cs

/*
 * 演示如何對本地數據進行加密和解密
 */
    
using System;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.DataProtection;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
    
namespace XamlDemo.Crypto
{
    public sealed partial class LocalCryptoString : Page
    {
        public LocalCryptoString()
        {
            this.InitializeComponent();
        }
    
        private async void btnDemo_Click(object sender, RoutedEventArgs e)
        {
            string plainText = "i am webabcd";
    
            lblMsg.Text = "原文: " + plainText;
            lblMsg.Text += Environment.NewLine;
    
            // 實例化用於加密的 DataProtectionProvider - Local=user 用戶級別的本地加解密;LOCAL=machine - 機器級別的本地加解密
            DataProtectionProvider provider = new DataProtectionProvider("Local=user"); // "LOCAL=machine"
    
            // 原文的二進制數據
            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8);
    
            // 加密數據
            IBuffer encrypted = await provider.ProtectAsync(buffer);
            // provider.ProtectStreamAsync(); 加密 stream 類型的數據
    
            // 加密後的結果
            lblMsg.Text += "encrypted: " + CryptographicBuffer.EncodeToHexString(encrypted);
            lblMsg.Text += Environment.NewLine;
    
    
                
            // 實例化用於解密的 DataProtectionProvider
            DataProtectionProvider provider2 = new DataProtectionProvider();
    
            // 解密數據
            IBuffer decrypted = await provider2.UnprotectAsync(encrypted);
            // provider2.UnprotectStreamAsync(); // 解密 stream 類型的數據
    
            // 解密後的結果
            lblMsg.Text += "decrypted: " + CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decrypted);
            lblMsg.Text += Environment.NewLine;
        }
    
    }
}

4、演示如何使用對稱算法(AES, DES, 3DES, RC2, RC4)

Crypto/Symmetric.xaml.cs

/*
 * 演示如何使用對稱算法(AES, DES, 3DES, RC2, RC4)
 */
    
using System;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
    
namespace XamlDemo.Crypto
{
    public sealed partial class Symmetric : Page
    {
        public Symmetric()
        {
            this.InitializeComponent();
        }
    
        private void btnDemo_Click(object sender, RoutedEventArgs e)
        {
            // 本示例的原文為 16 個字節,是為了正常演示無填充時的加密
            // 什麼是填充:比如 aes 要求數據長度必須是 16 的倍數,如果不是則需要通過指定的填充模式來補全數據
            string plainText = "1234567812345678";
    
            lblMsg.Text = "原文: " + plainText;
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += Environment.NewLine;
    
            string[] algorithmNames = { "AES_CBC", "AES_ECB", "AES_CBC_PKCS7", "AES_ECB_PKCS7", "DES_CBC", "DES_ECB", "3DES_CBC", "3DES_ECB", "3DES_CBC_PKCS7", "3DES_ECB_PKCS7", "RC2_CBC", 

"RC2_ECB", "RC4" };
    
            foreach (var algorithmName in algorithmNames)
            {
                uint keySize = 128;
                if (algorithmName.StartsWith("AES")) // AES 算法密鑰長度 128 位
                    keySize = 128;
                else if (algorithmName.StartsWith("DES")) // DES 算法密鑰長度 64 位(56 位的密鑰加上 8 位奇偶校驗位)
                    keySize = 64;
                else if (algorithmName.StartsWith("3DES")) // 3DES 算法密鑰長度 192 位(3 重 DES)
                    keySize = 192;
                else if (algorithmName.StartsWith("RC2")) // RC2 算法密鑰長度可變
                    keySize = 128;
                else if (algorithmName.StartsWith("RC4")) // RC4 算法密鑰長度可變
                    keySize = 128;
    
                IBuffer buffer; // 原文
                IBuffer encrypted; // 加密後
                IBuffer decrypted; // 解密後
                IBuffer iv = null; // 向量(CBC 模式)
    
                // 根據算法名稱實例化一個對稱算法提供程序
                SymmetricKeyAlgorithmProvider symmetricAlgorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName);
    
                // 創建一個隨機密鑰 key
                IBuffer key = CryptographicBuffer.GenerateRandom(keySize / 8);
    
                // 根據 key 生成 CryptographicKey 對象
                CryptographicKey cryptoKey = symmetricAlgorithm.CreateSymmetricKey(key);
    
                // 如果是 CBC 模式則隨機生成一個向量
                if (algorithmName.Contains("CBC"))
                    iv = CryptographicBuffer.GenerateRandom(symmetricAlgorithm.BlockLength);
    
                // 將需要加密的數據轉換為 IBuffer 類型
                buffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8);
    
                try
                {
                    // 加密數據
                    encrypted = CryptographicEngine.Encrypt(cryptoKey, buffer, iv);
                }
                catch (Exception ex)
                {
                    lblMsg.Text += ex.ToString();
                    lblMsg.Text += Environment.NewLine;
                    return;
                }
    
                // 加密後的結果
                lblMsg.Text += algorithmName + " encrypted: " + CryptographicBuffer.EncodeToHexString(encrypted);
                lblMsg.Text += Environment.NewLine;
    
    
    
                CryptographicKey cryptoKey2 = symmetricAlgorithm.CreateSymmetricKey(key);
                try
                {
                    // 解密數據
                    decrypted = Windows.Security.Cryptography.Core.CryptographicEngine.Decrypt(cryptoKey2, encrypted, iv);
                }
                catch (Exception ex)
                {
                    lblMsg.Text += ex.ToString();
                    lblMsg.Text += Environment.NewLine;
                    return;
                }
    
                // 解密後的結果
                lblMsg.Text += algorithmName + " decrypted: " + CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decrypted);
                lblMsg.Text += Environment.NewLine;
                lblMsg.Text += Environment.NewLine;
            }
        }
    }
}

OK

[源碼下載]:http://files.cnblogs.com/webabcd/Windows8.rar

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved