Amazon CloudFront
开发人员指南 (API 版本 2016-09-29)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 AWS 服务入门

使用 Java 创建 URL 签名

Amazon S3 和 CloudFront 的开源 Java 工具包提供有关在 Java 中开发 CloudFront 的示例代码和信息。有关私有分配的信息,请转到程序员指南:代码示例中的“私有分配”。

还可以通过使用适用于 Java 的 AWS 开发工具包中的 CloudFrontUrlSigner 类来创建签名 URL。有关更多信息,请参阅 AWS SDK for Java API Reference 中的 UrlSigner 类


创建 URL 签名只是使用签名 URL 提供私有内容过程的一部分。有关整个过程的更多信息,请参阅 使用签名 URL

以下方法来自于 Amazon S3 和 CloudFront 的 Java 开源工具包。您必须将 PEM 格式的私有密钥转换为 DER 格式以便 Java 实现可使用它。

例 Java 策略和签名加密方法

// Signed URLs for a private distribution // Note that Java only supports SSL certificates in DER format, // so you will need to convert your PEM-formatted file to DER format. // To do this, you can use openssl: // openssl pkcs8 -topk8 -nocrypt -in origin.pem -inform PEM -out new.der // -outform DER // So the encoder works correctly, you should also add the bouncy castle jar // to your project and then add the provider. Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); String distributionDomain = ""; String privateKeyFilePath = "/path/to/rsa-private-key.der"; String s3ObjectKey = "s3/object/key.txt"; String policyResourcePath = "http://" + distributionDomain + "/" + s3ObjectKey; // Convert your DER file into a byte array. byte[] derPrivateKey = ServiceUtils.readInputStreamToBytes(new FileInputStream(privateKeyFilePath)); // Generate a "canned" signed URL to allow access to a // specific distribution and file String signedUrlCanned = CloudFrontService.signUrlCanned( "http://" + distributionDomain + "/" + s3ObjectKey, // Resource URL or Path keyPairId, // Certificate identifier, // an active trusted signer for the distribution derPrivateKey, // DER Private key data ServiceUtils.parseIso8601Date("2011-11-14T22:20:00.000Z") // DateLessThan ); System.out.println(signedUrlCanned); // Build a policy document to define custom restrictions for a signed URL. String policy = CloudFrontService.buildPolicyForSignedUrl( // Resource path (optional, can include '*' and '?' wildcards) policyResourcePath, // DateLessThan ServiceUtils.parseIso8601Date("2011-11-14T22:20:00.000Z"), // CIDR IP address restriction (optional, means everyone) "", // DateGreaterThan (optional) ServiceUtils.parseIso8601Date("2011-10-16T06:31:56.000Z") ); // Generate a signed URL using a custom policy document. String signedUrl = CloudFrontService.signUrl( // Resource URL or Path "http://" + distributionDomain + "/" + s3ObjectKey, // Certificate identifier, an active trusted signer for the distribution keyPairId, // DER Private key data derPrivateKey, // Access control policy policy ); System.out.println(signedUrl);