Skip to content

Instantly share code, notes, and snippets.

@perchouli
Created March 13, 2013 08:00
Show Gist options
  • Save perchouli/5150114 to your computer and use it in GitHub Desktop.
Save perchouli/5150114 to your computer and use it in GitHub Desktop.
JAVA生成多说Remote Auth
import net.sf.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
public class Remote {
public static String bytesToHex(byte[] bytes) {
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, InvalidKeyException, IllegalBlockSizeException {
Map userData = new HashMap();
userData.put("key", "用户在本站的ID");
userData.put("name", "用户名");
userData.put("email", "用户头像图片地址");
userData.put("url", "用户邮箱");
userData.put("avatar", "点击用户头像跳转的链接");
String duoshuoSecret = "多说密钥";
JSONObject jsonObject = JSONObject.fromObject(userData);
String message = (new BASE64Encoder()).encode( jsonObject.toString().getBytes());
String time = String.valueOf(System.currentTimeMillis()).substring(0,10);
SecretKey secret = new SecretKeySpec(duoshuoSecret.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(secret);
byte[] rawHmac = mac.doFinal((message + ' ' + time).getBytes());
String remoteAuth = message + ' ' + bytesToHex(rawHmac) + ' ' + time;
System.out.println(remoteAuth);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment