本人小白,求帮忙
把Java代码翻译成C#的
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.Formatter;
import java.util.Random;
/**
计算dd.config的签名参数
**/
public class DdConfigSign {
/**
// 字节数组转化成十六进制字符串
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
/**
public static String getRandomStr(int count) {
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
好多年没写java了,不过大致能明白要做什么,不保证代码是对的,你可以参考下
using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;
public class DdConfigSign {
public static string sign(string jsticket, string nonceStr, long timeStamp, string url) {
string plain = "jsapi_ticket=" + jsticket + "&noncestr=" + nonceStr + "×tamp=" + timeStamp
+ "&url=" + decodeUrl(url);
try {
//对字符串进行sha256加密,输出十六进制小写字符串
byte[] hash = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(plain));
return BitConverter.ToString(hash).Replace("-", "").ToLower();
} catch (Exception e) {
throw new Exception(e.ToString());
}
}
/// <summary>
/// 对url的query中的值进行urlDecode
/// </summary>
private static string decodeUrl(string url) {
string[] ss = url.Split('?');
StringBuilder sb = new StringBuilder();
sb.Append(ss[0]);
sb.Append("?");
foreach (var query in ss[1].Split('&')) {
if (query.Length > 0 && query.Contains("=")) {
string[] kv = query.Split('=');
if (kv.Length == 2) {
sb.Append(kv[0] + "=" + HttpUtility.UrlDecode(kv[1], Encoding.UTF8));
}
}
}
return sb.ToString();
}
/// <summary>
/// 获得指定长度的随机字符串
/// </summary>
public static string getRandomStr(int count) {
string baseStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder();
Random rd = new Random();
for (int i = 0; i < count; i++) {
sb.Append(baseStr[rd.Next(0, baseStr.Length)]);
}
return sb.ToString();
}
}
卧槽,不讲武德,我还想着挣几个豆呢
感谢大神,高效