1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Encoding { String data,key,method; private void setData(String data) {this.data = data;} //Base String啦 private void setKey(String key) {this.key = key;} //Secret Key 密鑰 private void setMethod(String method) {this.method = method;} //加密方式,向plurk請求時應為"HMAC-SHA1" //建構子 - 先行把變量設置好 public Encoding(String data, String key, String method) { setData(data); setKey(key); setMethod(method); } //正式計算部份 public String calculation() throws NoSuchAlgorithmException, InvalidKeyException { //這四行不要問在做啥...key+"&"是必要的,getBytes()就是把字串內容都變換成Byte SecretKeySpec skey = new SecretKeySpec((key+"&").getBytes(), method); Mac mac = Mac.getInstance(method); mac.init(skey); byte[] rawHmac = mac.doFinal(data.getBytes()); //這裡是把加密後的編碼變換回字串,以Base64的算法(這裡Android和Java的method不一,自己調整) return (Base64.encodeToString(rawHmac,Base64.DEFAULT)); } } |
Direct link: https://paste.plurk.com/show/2248335