对象存储签名生成

2021-04-27 17:08:00 浏览数 (1)

代码语言:java复制
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;


public class Authorization {
    private static final Charset UTF8 = StandardCharsets.UTF_8;;
    private static final String SecretId="";
    private static final String SecretKey="";
    private static final String StartTimestamp = Long.toString(System.currentTimeMillis()/1000L);
    private static final String EndTimestamp = Long.toString(System.currentTimeMillis()/1000L   30);
    private static final String KeyTime= StartTimestamp   ";"   EndTimestamp;
    public static String HmacSHA1(String key, String msg) throws Exception {
       byte[] data = key.getBytes(UTF8);
       Mac mac = Mac.getInstance("HmacSHA1");
       SecretKeySpec secretKeySpec = new SecretKeySpec(data, mac.getAlgorithm());
       mac.init(secretKeySpec);
       byte[] HmacSha1 = mac.doFinal(msg.getBytes(UTF8));
       StringBuilder stringBuilder = new StringBuilder("");
        for (int i = 0; i < HmacSha1.length; i  ) {
            int v = HmacSha1[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
    public static String HttpString(String HttpMethod, String UriPathname, String HttpParameters, String HttpHeaders)throws Exception{
        return HttpMethod   "n"   UriPathname   "n"   HttpParameters   "n"   HttpHeaders   "n";
    }
    public static String SHA1(String StringToSign) throws Exception{
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        messageDigest.update(StringToSign.getBytes(UTF8));
        byte[] md = messageDigest.digest();
        int j = md.length;
        char buf[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i  ) {
            byte byte0 = md[i];
            buf[k  ] = hexDigits[byte0 >>> 4 & 0xf];
            buf[k  ] = hexDigits[byte0 & 0xf];
        }
        return new String(buf);
    }
    public static String Sign(String HttpMethod, String UriPathname) throws Exception{
        String SignKey =  HmacSHA1(SecretKey, KeyTime);
        String HttpStrings = HttpString(HttpMethod, UriPathname, "", "");
        String StringToSign = "sha1n" KeyTime "n" SHA1(HttpStrings) "n";
        String Signature = HmacSHA1(SignKey, StringToSign);
        String Authorization = String.format("q-sign-algorithm=%s&q-ak=%s&q-sign-time=%s&q-key-time=%s&q-header-list=%s&q-url-param-list=%s&q-signature=%s", "sha1", SecretId, KeyTime, KeyTime,"","",Signature);
        return Authorization;
    }
}

0 人点赞