程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> WP8.1 RSA 加解密實例(導入公鑰私鑰)

WP8.1 RSA 加解密實例(導入公鑰私鑰)

編輯:C#基礎知識

因項目上需要用到,之前在WP8.0的環境上調試通過,現在在開發8.1時發現已不支持原來的加密庫,所以無法使用以前的方法,不得已,去尋找windows命名空間下RSA的加解密方法,經過幾天的嘗試,將解決方案貼出來,看能否幫助碰到如此類型的問題的同學.

本示例的應且場景,服務器端返回RSA的公鑰私鑰,客戶端導入公鑰及私鑰

 

服務端:

            System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(xmlPrivatelKey);//此處為XML格式的私鑰,如           

            //<RSAKeyValue><Modulus>.........Mk=</Modulus><Exponent>AQAB</Exponent><P>....../.....LGAAE=</D></RSAKeyValue>

            byte[] data1 = rsa.ExportCspBlob(false);
            byte[] data2 = rsa.ExportCspBlob(true);

            String pubkey = System.Convert.ToBase64String(data1);
            string privKey = System.Convert.ToBase64String(data2);

 

WP8.1:

   public static byte[] Encrypt(byte[] data, string publicKey)
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(data, 0, data.Length);
            AsymmetricKeyAlgorithmProvider asymmetricAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm("RSA_PKCS1");
            try
            {
                // 根據算法名稱實例化一個非對稱算法提供程序
                CryptographicKey key = asymmetricAlgorithm.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey), CryptographicPublicKeyBlobType.Capi1PublicKey);
                IBuffer encrypted = CryptographicEngine.Encrypt(key, buffer, null);

                // 加密後的結果
                return encrypted.ToArray();
            }
            catch (Exception er)
            {
                return new byte[0];
            }
        }
        public static byte[] Decrypt(byte[] data, string publicKey, string privateKey)
        {
            IBuffer buffer = WindowsRuntimeBufferExtensions.AsBuffer(data, 0, data.Length);
            // 根據算法名稱實例化一個非對稱算法提供程序
            AsymmetricKeyAlgorithmProvider asymmetricAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            try
            {
                CryptographicKey pubkey = asymmetricAlgorithm.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey), CryptographicPublicKeyBlobType.Capi1PublicKey);
                // 導入公鑰私鑰對
                CryptographicKey keyPair2 = asymmetricAlgorithm.ImportKeyPair(CryptographicBuffer.DecodeFromBase64String(privateKey), CryptographicPrivateKeyBlobType.Capi1PrivateKey);

                // 解密數據(通過私鑰)
                IBuffer decrypted = CryptographicEngine.Decrypt(keyPair2, buffer, null);
                return decrypted.ToArray();
            }
            catch (Exception er)
            {
                return new byte[0];
            }

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