Java代碼:
/** * HmacSHA256算法,返回的結果始終是32位 * @param key 加密的鍵,可以是任何數據 * @param content 待加密的內容 * @return 加密后的內容 * @throws Exception */ public static byte[] hmacSHA256(byte[] key,byte[] content) throws Exception { Mac hmacSha256 = Mac.getInstance("HmacSHA256"); hmacSha256.init(new SecretKeySpec(key, 0, key.length, "HmacSHA256")); byte[] hmacSha256Bytes = hmacSha256.doFinal(content); return hmacSha256Bytes; }
C#代碼:
/// <summary> /// HmacSHA256算法,返回的結果始終是32位 /// </summary> /// <param name="key">加密的鍵,可以是任何數據</param> /// <param name="content">待加密的內容</param> /// <returns></returns> public static byte[] HmacSHA256(byte[] key, byte[] content) { using (var hmacsha256 = new HMACSHA256(key)) { byte[] hashmessage = hmacsha256.ComputeHash(content); return hashmessage; } }
無論數據的交互過程如何Base64怎么的都不重要,因為數據的傳輸和加密都是操作的byte[]。因此我們完全可以忽略掉Base64而直接對byte[]進行相關的操作。
