使用 Java 创建 URL 签名 - Amazon CloudFront

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Java 创建 URL 签名

除了以下代码示例外,您还可以使用 AWS SDK for Java(版本 1)中的CloudFrontUrlSigner实用程序类来创建CloudFront 签名 URL

有关更多示例,请参阅 SDK 代码示例代码库中的使用 S AWS DK 创建签名网址和 Cookie。AWS

注意

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

以下示例说明如何创建 CloudFront 签名 URL。您必须将 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 = "a1b2c3d4e5f6g7.cloudfront.net"; String privateKeyFilePath = "/path/to/rsa-private-key.der"; String s3ObjectKey = "s3/object/key.txt"; String policyResourcePath = "https://" + 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( "https://" + 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, 0.0.0.0/0 means everyone) "0.0.0.0/0", // 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 "https://" + 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);

另请参见: