Google云端存储签名URL在何处放置私钥文件

时间:2014-08-21 19:17:45

标签: java google-app-engine google-cloud-storage

我使用下面的Java代码生成签名的URL。错误说

  

我们计算的请求签名与您的签名不符   提供。检查您的Google密钥和签名方法。

我的课程如下。

public class DsGCSSignedURL {

    private static final int EXPIRATION_TIME = 20;
    private static final String BASE_URL = "https://storage.googleapis.com";
    private static final String BUCKET = "barkpark";
    private static final String FOLDER = "public";


    private final AppIdentityService identityService = AppIdentityServiceFactory.getAppIdentityService();

    public String getSignedUrl(final String httpVerb, final String fileName) throws Exception {
        final long expiration = expiration();
        final String unsigned = stringToSign(expiration, fileName, httpVerb);

        final String signature = sign(unsigned);

        return new StringBuilder(BASE_URL).append("/")
                .append(BUCKET)
                .append("/")
                .append(FOLDER)
                .append("/")
                .append(fileName)
                .append("?GoogleAccessId=")
                .append(clientId())
                .append("&Expires=")
                .append(expiration)
                .append("&Signature=")
                .append(URLEncoder.encode(signature, "UTF-8")).toString();
    }

    private static long expiration() {
        final long unitMil = 1000l;
        final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, EXPIRATION_TIME);
        final long expiration = calendar.getTimeInMillis() / unitMil;
        return expiration;
    }

    private String stringToSign(final long expiration, String filename, String httpVerb) {
        final String contentType = "";
        final String contentMD5 = "";
        final String canonicalizedExtensionHeaders = "";
        final String canonicalizedResource = "/" + BUCKET + "/" + FOLDER + "/" + filename;
        final String stringToSign = httpVerb + "\n" + contentMD5 + "\n" + contentType + "\n"
                + expiration + "\n" + canonicalizedExtensionHeaders + canonicalizedResource;


        return stringToSign;
    }

    protected String sign(final String stringToSign) throws UnsupportedEncodingException {
        final SigningResult signingResult = identityService.signForApp(stringToSign.getBytes());
        final String encodedSignature = new String(Base64.encodeBase64(signingResult.getSignature(), false), "UTF-8");

        return encodedSignature;
    }

    protected String clientId() {
        return "something@developer.gserviceaccount.com";
    }
}

0 个答案:

没有答案