Java SHA256/Base64轉.NET(C#)實現---(華為雲雲市場.NET版本加密方式)


前言:

  工作需要,對接華為雲應用市場的 API 接口,由於維護團隊都是 .NET 所以用 .NET 來開發。

  簡單了解一下 SHA256 加密算法,本質就是一個 Hash,與 MD5 相比就是計算量大一些,具體的沒時間細化。

 

一、Java SHA256 加密算法實現代碼  (最終以 Base64 方式進行簽名驗證)

 1 /**
 2 *
 3 * hamcSHA256加密算法
 4 * @param macKey 秘鑰key
 5 * @param macData 加密內容-響應消息體
 6 * @return 加密密文
 7 * @throws NoSuchAlgorithmException
 8 * @throws InvalidKeyException
 9 * @throws IllegalStateException
10 * @throws UnsupportedEncodingException
11 */
12 public static byte[] hmacSHA256(String macKey, String macData) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException {
13 
14     SecretKeySpec secret = new SecretKeySpec(macKey.getBytes(),  "HmacSHA256");
15     Mac mac = Mac.getInstance("HmacSHA256");
16     mac.init(secret);
17 
18     byte[] doFinal = mac.doFinal(macData.getBytes("UTF-8"));
19     return doFinal;
20 }
 1 /**
 2 *
 3 * 字節數組轉字符串
 4 * @param bytes 字節數組
 5 * @return 字符串
 6 */
 7 public static String base_64(byte[] bytes)
 8 {
 9      return new String(Base64.encodeBase64(bytes));
10 }

 

二、.NET SHA256 加密算法實現代碼

/// <summary>
/// hamcSHA256加密實現
/// </summary>
/// <returns>The token.</returns>
/// <param name="secret">Secret.</param>
/// <param name="message">Message.</param>
public static string CreateToken(string secret, string message)
{
     var encoding = new System.Text.ASCIIEncoding();
     byte[] keyByte = encoding.GetBytes(secret);
// 注意:如果是中文注意轉換編碼格式
byte[] messageBytes = encoding.GetBytes(message); using (var hmacsha256 = new HMACSHA256(keyByte)) { byte[] hashmessage = hmacsha256.ComputeHash(messageBytes); // 注意:Java (u127)與.NET byte(255) 存儲方式不同,所以需要轉換一下。 sbyte[] sb = new sbyte[hashmessage.Length]; for (int i = 0; i < hashmessage.Length; i++) { sb[i] = hashmessage[i] < 127 ? (sbyte)hashmessage[i] : (sbyte)(hashmessage[i] - 256); } byte[] unsignedByteArray = (byte[])(Array)sb; return Convert.ToBase64String(unsignedByteArray); } }

 

問題總結:

  1、轉 byte[] 數組,注意編碼格式;

  2、Java 中的 byte 與 .NET 中的 byte 存儲方式不同,Java 是 -127~127、.NET 是 0~2555

  3、轉換 Base64 同樣,如果不進行轉換結果會不一致,采用 sbyte[] 進行一輪轉換再 Base64;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM