- import java.security.InvalidKeyException;
- import java.security.NoSuchAlgorithmException;
- import javax.crypto.Mac;
- import javax.crypto.spec.SecretKeySpec;
- import org.apache.commons.lang.StringUtils;
- public class Test2 {
- private static final String HMAC_SHA1 = "HmacSHA1";
- private static final char[] Digit = { '0', '1', '2', '3', '4', '5', '6',
- '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
- final static String encodedPutPolicy = "eyJzY29wZSI6Im15LWJ1Y2tldDpzdW5mbG93ZXIuanBnIiwiZGVhZGxpbmUiOjE0NTE0OTEyMDAsInJldHVybkJvZHkiOiJ7XCJuYW1lXCI6JChmbmFtZSksXCJzaXplXCI6JChmc2l6ZSksXCJ3XCI6JChpbWFnZUluZm8ud2lkdGgpLFwiaFwiOiQoaW1hZ2VJbmZvLmhlaWdodCksXCJoYXNoXCI6JChldGFnKX0ifQ==";
- final static String SecretKey = "MY_SECRET_KEY";
- final static String AccessKey = "MY_ACCESS_KEY";
- public static void main(String[] args) throws InvalidKeyException,
- NoSuchAlgorithmException {
- byte[] sign = HMACSHA1Util.getSignatureBytes(encodedPutPolicy,
- SecretKey);
- // base64 编码
- String encodedSign_1 = encode(sign);
- // 编码后进行URL 安全转换
- String encodedSign_2 = StringUtils.replace(encodedSign_1, "+", "-");
- String encodedSign_3 = StringUtils.replace(encodedSign_2, "/", "_");
- String result = "wQ4ofysef1R7IKnrziqtomqyDvI=";
- System.out.println(encodedSign_3);
- System.out.println(result);
- }
- @SuppressWarnings("restriction")
- public static final String encode(byte[] bs) {
- if (null == bs) {
- throw new NullPointerException("bs");
- } else {
- return new sun.misc.BASE64Encoder().encode(bs);
- }
- }
- public static byte[] getSignatureBytes(String data, String key)
- throws InvalidKeyException, NoSuchAlgorithmException {
- byte[] keyBytes = key.getBytes();
- SecretKeySpec signingKey = new SecretKeySpec(keyBytes, HMAC_SHA1);
- Mac mac = Mac.getInstance(HMAC_SHA1);
- mac.init(signingKey);
- byte[] rawHmac = mac.doFinal(data.getBytes());
- StringBuilder sb = new StringBuilder();
- for (byte b : rawHmac) {
- sb.append(byteToHexString(b));
- }
- return rawHmac;
- }
- private static String byteToHexString(byte ib) {
- char[] ob = new char[2];
- ob[0] = Digit[(ib >>> 4) & 0X0f];
- ob[1] = Digit[ib & 0X0F];
- String s = new String(ob);
- return s;
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0808201614927.html
来源: http://www.codesnippet.cn/detail/0808201614927.html