繁体   English   中英

替换 AWS Java SDK2 中的 CloudFrontUrlSigner

[英]Replacement for CloudFrontUrlSigner in AWS Java SDK2

我使用 Java 11。由于 AWS Java SDK2 支持 Java 11,我使用 SDK2。 如何为 s3 密钥创建云前端 url。 我可以得到很多 SDK 1.x 版本的例子,但不能得到 SDK2 的例子。 这是在 1.x 中生成 url 的方式

CloudFrontUrlSigner.getSignedURLWithCannedPolicy(url, keyPairId, privateKey, expires)

SDK 2.x 版本中是否有任何替代方法或替代方法

我认为它还没有实施。 与此同时,从旧版本中翻录代码来做同样的事情是相当容易的。

这是来自https://github.com/dashpradeep99/aws-sdk-java-code/blob/master/aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/util/SignerUtils .java

https://github.com/dashpradeep99/aws-sdk-java-code/blob/master/aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/CloudFrontUrlSigner.java

import software.amazon.awssdk.core.exception.SdkException;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Date;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class AwsUtils {

  private static final SecureRandom srand = new SecureRandom();

  /**
   * Generates a signed url that expires after given date.
   * @param resourceUrlOrPath The url.
   * @param keyPairId The keypair id used to sign.
   * @param privateKey The private key.
   * @param dateLessThan The expire date/time.
   * @return A valid cloudwatch url.
   * @throws SdkException If any errors occur during the signing process.
   */
  public static String getSignedUrlWithCannedPolicy(String resourceUrlOrPath,
                                                    String keyPairId,
                                                    PrivateKey privateKey,
                                                    Date dateLessThan) throws SdkException {
    try {
      String cannedPolicy = buildCannedPolicy(resourceUrlOrPath, dateLessThan);
      byte[] signatureBytes = signWithSha1Rsa(cannedPolicy.getBytes(StandardCharsets.UTF_8), privateKey);
      String urlSafeSignature = makeBytesUrlSafe(signatureBytes);
      return resourceUrlOrPath
          + (resourceUrlOrPath.indexOf('?') >= 0 ? "&" : "?")
          + "Expires=" + MILLISECONDS.toSeconds(dateLessThan.getTime())
          + "&Signature=" + urlSafeSignature
          + "&Key-Pair-Id=" + keyPairId;
    } catch (InvalidKeyException e) {
      throw SdkException.create("Couldn't sign url", e);
    }
  }

  /**
   * Returns a "canned" policy for the given parameters.
   * For more information, see <a href=
   * "http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-urls-overview.html"
   * >Overview of Signed URLs</a>.
   * @param resourceUrlOrPath The resource to grant access.
   * @param dateLessThan The expiration time.
   * @return the aws policy as a string.
   */
  public static String buildCannedPolicy(String resourceUrlOrPath,
                                         Date dateLessThan) {
    return "{\"Statement\":[{\"Resource\":\""
        + resourceUrlOrPath
        + "\",\"Condition\":{\"DateLessThan\":{\"AWS:EpochTime\":"
        + MILLISECONDS.toSeconds(dateLessThan.getTime())
        + "}}}]}";
  }

  /**
   * Signs the data given with the private key given, using the SHA1withRSA
   * algorithm provided by bouncy castle.
   * @param dataToSign The data to sign.
   * @param privateKey The private key.
   * @return A signature.
   * @throws InvalidKeyException if an invalid key was provided.
   */
  public static byte[] signWithSha1Rsa(byte[] dataToSign,
                                       PrivateKey privateKey) throws InvalidKeyException {
    Signature signature;
    try {
      signature = Signature.getInstance("SHA1withRSA");
      signature.initSign(privateKey, srand);
      signature.update(dataToSign);
      return signature.sign();
    } catch (NoSuchAlgorithmException | SignatureException e) {
      throw new IllegalStateException(e);
    }
  }

  /**
   * Converts the given data to be safe for use in signed URLs for a private
   * distribution by using specialized Base64 encoding.
   * @param bytes The bytes
   */
  public static String makeBytesUrlSafe(byte[] bytes) {
    byte[] encoded = java.util.Base64.getEncoder().encode(bytes);

    for (int i = 0; i < encoded.length; i++) {
      switch (encoded[i]) {
        case '+':
          encoded[i] = '-';
          continue;
        case '=':
          encoded[i] = '_';
          continue;
        case '/':
          encoded[i] = '~';
          continue;
        default:
          continue;
      }
    }
    return new String(encoded, StandardCharsets.UTF_8);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM