本人菜鳥一枚,大學裡憑興趣學了一點WP的皮毛,後來又幸運(或者不幸)的進了一家專注於Windows生態的公司做了一段時間的UWP。在博客園寫點自己遇到的東西,作為分享,也作為自己的備忘,如果有錯誤的地方,或者可以提升B格的地方,希望園子裡的大神們不吝賜教。
初進公司時,公司要做支付相關的業務,需要和支付寶、優易付、愛貝等支付渠道對接,對新手的我來說,加密或者是簽名簡直難到死,學校裡哪用過這個,OMG,只能迎著頭皮找資料。
這裡我想請教大家一個問題,就是如何學習。例如當你遇到一個陌生的東西,你是如何查找資料解決問題的?當我需要做加密的時候我的做法是打開百度搜索“WP 3des加密”,這樣找出來的結果基本都不能用。。。後來終於在博客園看到了兩篇相關的博客,我才知道原來要實現相關功能需要哪幾個類哪幾個方法,這個過程大概用了一周吧,效率超低。
解決我燃眉之急的兩篇博客分別是:
王磊:http://www.cnblogs.com/webabcd/archive/2013/06/03/3114657.html
老周:http://www.cnblogs.com/tcjiaan/p/4303918.html
看了這兩篇博客就知道該使用哪些類了,再接下來就相對簡單了。非常感謝兩位老師的分享和指導。
在RT應用中,涉及到加/解密的API都在以下幾個命名空間裡:
1、Windows.Security.Cryptography
2、Windows.Security.Cryptography.Core
3、Windows.Security.Cryptography.DataProtection
接下來分享一下我在項目中做過的幾個加密/簽名,進行了一下簡單的封裝,還望大家指點
1.3des加密

internal sealed class TripleDesEncryptHelper
{
//加/解密 第一步
//通過SymmetricKeyAlgorithmProvider的靜態方法OpenAlgorithm()得到一個SymmetricKeyAlgorithmProvider實例
//該方法參數是要使用的加/解密算法的名字
internal static SymmetricKeyAlgorithmProvider syprd = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesEcb);
/// <summary>
/// 加密函數
/// </summary>
/// <param name="data">需要加密的字符串</param>
/// <returns>返回加密後的結果</returns>
public static string Encrypt(string data, string key)
{
string encryptedData = null;
try
{
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
//這裡我自己寫了一個pkcs5對齊,不過後來有看到過C#pkcs5和pkcs7是一樣的說法,有待驗證
byte[] pkcs5databytes = pkcs5(dataBytes);
IBuffer databuffer = pkcs5databytes.AsBuffer();
byte[] keyBytes = Convert.FromBase64String(key);
IBuffer keybuffer = keyBytes.AsBuffer();
//構造CryptographicKey
CryptographicKey cryptographicKey = syprd.CreateSymmetricKey(keybuffer);
//加密
//Encrypt需要三個參數分別為加密使用的Key,需要加密的Data,以及向量IV
//Des加密中Ecb模式和Cbc模式的區別就在於是否必須使用向量IV
IBuffer cryptBuffer = CryptographicEngine.Encrypt(cryptographicKey, databuffer, null); **************/
byte[] enctyptedBytes = cryptBuffer.ToArray();
//進行base64編碼
encryptedData = Convert.ToBase64String(enctyptedBytes);
}
catch (Exception ex)
{
DebugHelper.Log("TripleDesEncryptHelper.Encrypt", ex.Message);
}
return encryptedData.Trim();
}
/// <summary>
/// 解密函數
/// </summary>
/// <param name="data">待解密的字符串</param>
/// <returns>解密後的數據</returns>
public static string Decrypt(string data, string key)
{
string decryptedData = null;
try
{
byte[] dataBytes = Convert.FromBase64String(data);
IBuffer dataBuffer = dataBytes.AsBuffer();
byte[] keyBytes = Convert.FromBase64String(key);
IBuffer keybuffer = keyBytes.AsBuffer();
CryptographicKey cryptographicKey = syprd.CreateSymmetricKey(keybuffer);
IBuffer decryptedBuffer = CryptographicEngine.Decrypt(cryptographicKey, dataBuffer, null);
decryptedData = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuffer);
//防止亂碼
var result = System.Text.RegularExpressions.Regex.Match(decryptedData, "[a-zA-Z0-9]*");
decryptedData = result.ToString();
}
catch (Exception ex)
{
DebugHelper.Log("TripleDesEncryptHelper.Decrypt", ex.Message);
}
return decryptedData;
}
/// <summary>
/// 把數據進行pkcs5對齊
/// </summary>
/// <param name="databytes">待處理的數據</param>
/// <returns></returns>
private static byte[] pkcs5(byte[] databytes)
{
byte[] newBytes = null;
int datalength = databytes.Length;
int blocksize = (int)syprd.BlockLength;
if (!(datalength % blocksize == 0))
{
int need = blocksize - (datalength % 8);
newBytes = new byte[datalength + need];
for (int i = 0; i < datalength; i++)
{
newBytes[i] = databytes[i];
}
byte xx = 0x0;
switch (need)
{
case 1:
xx = 0x1;
break;
case 2:
xx = 0x2;
break;
case 3:
xx = 0x3;
break;
case 4:
xx = 0x4;
break;
case 5:
xx = 0x5;
break;
case 6:
xx = 0x6;
break;
case 7:
xx = 0x7;
break;
}
for (int i = 0; i < need; i++)
{
newBytes[datalength + i] = xx;
}
}
else
{
newBytes = new byte[datalength + 8];
for (int i = 0; i < datalength; i++)
{
newBytes[i] = databytes[i];
}
byte xx = 0x8;
for (int i = 0; i < 8; i++)
{
newBytes[datalength + i] = xx;
}
}
return newBytes;
}
}
View Code
2. Sha1簽名
根據愛貝的要求,需要先將數據進行sha1 hash,再將hash後的數據進行sha1簽名

internal sealed class Sha1SignHelper
{
/// <summary>
/// 用sha1進行簽名
/// </summary>
/// <param name="data">需要簽名的數據</param>
/// <param name="key">簽名私鑰</param>
/// <returns></returns>
internal static string Sha1Sign(string data, string key)
{
string signedData = null;
IBuffer dataBuffer = Encoding.UTF8.GetBytes(data).AsBuffer();
try
{
AsymmetricKeyAlgorithmProvider asymmetricAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm("RSASIGN_PKCS1_SHA1");
//創建一個公鑰私鑰對
CryptographicKey KeyPair = asymmetricAlgorithm.ImportKeyPair(CryptographicBuffer.DecodeFromBase64String(key), CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey);
//哈希計算data
HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm(Windows.Security.Cryptography.Core.HashAlgorithmNames.Sha1);
IBuffer hashedData = provider.HashData(dataBuffer);
//簽名
IBuffer signedHashedBuffer = CryptographicEngine.SignHashedData(KeyPair, hashedData);
signedData = CryptographicBuffer.EncodeToBase64String(signedHashedBuffer);
}
catch (Exception ex)
{
DebugHelper.Log("Sha1SignHelper.Sha1Sign", ex.Message);
}
return signedData;
}
internal static bool Sha1VerifySignature(string oldText, string signature, string publicKey)
{
bool dataCorrect = false;
try
{
AsymmetricKeyAlgorithmProvider asymmetricAlgorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm("RSASIGN_PKCS1_SHA1");
//創建一個公鑰私鑰對
IBuffer pubKeyBuffer = Convert.FromBase64String(publicKey).AsBuffer();
CryptographicKey KeyPair = asymmetricAlgorithm.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey));
// 驗證簽名(通過公鑰)
IBuffer databuffer = CryptographicBuffer.ConvertStringToBinary(oldText, BinaryStringEncoding.Utf8); ;
dataCorrect = CryptographicEngine.VerifySignature(KeyPair, databuffer, Convert.FromBase64String(signature).AsBuffer());
}
catch (Exception ex)
{
DebugHelper.Log("Sha1SignHelper.Sha1VerifySignature", ex.Message);
}
return dataCorrect;
}
}
View Code
對接過支付寶的大神們應該比較熟悉,支付寶與愛貝的區別就在於支付寶是先md5哈希,再sha1簽名,可是我將
HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm(Windows.Security.Cryptography.Core.HashAlgorithmNames.Sha1);
改為
HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm(Windows.Security.Cryptography.Core.HashAlgorithmNames.Md5);
簽名後得到的數據卻始終與支付寶匹配不上,無奈只能在服務器上完成這一環節,有知道問題所在的大神們可以指點一下。
以上就是我在做支付時用到過的加密/簽名算法,自己封裝成了類以便使用。
做完這個項目後其實我對加密/簽名算法本身還是一頭霧水,並不理解算法的本質原理,只是完成了功能而已,所以過程中也遇到了幾個問題:
1.永遠sha1簽名的私鑰的格式 CryptographicKey KeyPair = asymmetricAlgorithm.ImportKeyPair(CryptographicBuffer.DecodeFromBase64String(key), CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey)中CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey和CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo的區別
2.pem格式密鑰和xml格式密鑰怎麼轉換
3.為什麼先md5哈希再rsa簽名始終和支付寶對不上?
如果有理解深入的大神,希望可以指點一下。
第一次寫博客,可能思路不清晰,望見諒!