Java SHA256/Base64转.NET(C#)实现---(华为云云市场.NET版本加密方式)

前言:算法

  工做须要,对接华为云应用市场的 API 接口,因为维护团队都是 .NET 因此用 .NET 来开发。数组

  简单了解一下 SHA256 加密算法,本质就是一个 Hash,与 MD5 相比就是计算量大一些,具体的没时间细化。编码

 

1、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 }

 

2、.NET SHA256 加密算法实现代码spa

/// <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); } }

 

问题总结:code

  一、转 byte[] 数组,注意编码格式;blog

  二、Java 中的 byte 与 .NET 中的 byte 存储方式不一样,Java 是 -127~12七、.NET 是 0~2555token

  三、转换 Base64 一样,若是不进行转换结果会不一致,采用 sbyte[] 进行一轮转换再 Base64;接口

相关文章
相关标签/搜索