欢迎您来到腾讯云!积分商城

腾讯云腾讯云论坛

 找回密码
 立即注册
忘了密码?

扫一扫,访问微社区

快捷导航
搜索
查看: 240|回复: 0

[经验分享] COS兼容aws java sdk客户端加密操作指导

[复制链接]

8

主题

0

好友

370

积分

程序猿[LV2]

Rank: 2Rank: 2

云币
950
威望
370
发表于 2017-11-30 19:47:26 |显示全部楼层 |未分类
1.SDK 名称版本:
aws-java-sdk-v1.11.156

2.接口兼容概述
使用 java sdk 进行客户端加密,首先需要对sdk进行兼容设置。cos 后台有条件兼容了 aws sdk,一般 sdk 需要做以下四个方面的修改,而 java 默认就使用了 virtual style,因此只需要修改下面的1和3部分;
1. 使用 aws v2 签名
2. 使用 virtual style 而非 path style
3. 设置 cos 的 endpoint
4. bucket 名字为 bucket-appid

例如生成一个 aws client 对象的代码如下:
  1.     String sk = "ciivKvnnrMvSvQpMAWuIz12pThGGlWRW";
  2.     String ak = "AKID15IsskiBQKTZbAo6WhgcBqVls9SmuG00";
  3.     BasicAWSCredentials cred = new BasicAWSCredentials(ak, sk);
  4.     ClientConfiguration config = new ClientConfiguration();
  5.     // 设置aws v2签名
  6.     config.setSignerOverride("S3SignerType");
  7.     AmazonS3 s3client = new AmazonS3Client(cred, config);
  8.     // 设置cos的endpoint,以华东(cn-east)举例
  9.     s3client.setEndpoint("cn-east.myqcloud.com");
复制代码
3.客户端加密使用示例
3.1.获取 aws-java-sdk-v1.11.156
下载并安装 aws-java-sdk-v1.11.156。
代码路径:
https://github.com/aws/aws-sdk-java

3.2.使用示例
使用sdk进行客户端数据加密上传和下载
  • CryptoDemo.java源码
  1. package crypto_test;
  2. import java.io.ByteArrayInputStream;
  3. import java.util.Arrays;
  4. import java.util.Iterator;
  5. import java.util.UUID;
  6. import javax.crypto.SecretKey;
  7. import org.apache.commons.io.IOUtils;
  8. import org.joda.time.DateTime;
  9. import org.joda.time.format.DateTimeFormat;
  10. import org.junit.Assert;
  11. import com.amazonaws.auth.BasicAWSCredentials;
  12. import com.amazonaws.auth.profile.ProfileCredentialsProvider;
  13. import com.amazonaws.services.s3.AmazonS3;
  14. import com.amazonaws.services.s3.AmazonS3EncryptionClient;
  15. import com.amazonaws.services.s3.model.EncryptionMaterials;
  16. import com.amazonaws.services.s3.model.ListVersionsRequest;
  17. import com.amazonaws.services.s3.model.ObjectListing;
  18. import com.amazonaws.services.s3.model.ObjectMetadata;
  19. import com.amazonaws.services.s3.model.PutObjectRequest;
  20. import com.amazonaws.services.s3.model.S3Object;
  21. import com.amazonaws.services.s3.model.S3ObjectSummary;
  22. import com.amazonaws.services.s3.model.S3VersionSummary;
  23. import com.amazonaws.services.s3.model.StaticEncryptionMaterialsProvider;
  24. import com.amazonaws.services.s3.model.VersionListing;

  25. public class CryptoDemo {
  26.     private static final String masterKeyDir = System.getProperty("java.io.tmpdir");
  27.     private static final String bucketName = "s3bucket-1253666666";
  28.     private static final String objectKey = "encrypted.data";

  29.     public static void main(String[] args) throws Exception {
  30.         SecretKey mySymmetricKey = GenerateSymmetricMasterKey
  31.                 .loadSymmetricAESKey(masterKeyDir, "AES");

  32.         EncryptionMaterials encryptionMaterials = new EncryptionMaterials(
  33.                 mySymmetricKey);
  34.         String sk = "BasdfSBpasdfgCGasdfIQIasdpsdfkz";
  35.         String ak = "AsdfsdfsdHi3gwsdfsdfAiTsdfsdfBsdfsdf5zsdfsE";
  36.         BasicAWSCredentials credentials = new BasicAWSCredentials(ak, sk);
  37.         AmazonS3EncryptionClient encryptionClient = new AmazonS3EncryptionClient(
  38.                         credentials,
  39.                 new StaticEncryptionMaterialsProvider(encryptionMaterials));
  40.         encryptionClient.setEndpoint("cn-east.myqcloud.com");
  41.         // Create the bucket
  42.         //encryptionClient.createBucket(bucketName);
  43.         System.out.println("bucket already created: " +bucketName);
  44.         
  45.         // Upload object using the encryption client.
  46.         byte[] plaintext = "Hello World, S3 Client-side Encryption Using Symmetric Master Key!"
  47.                 .getBytes();
  48.         System.out.println("plaintext's length: " + plaintext.length);
  49.         encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey,
  50.                 new ByteArrayInputStream(plaintext), new ObjectMetadata()));

  51.         // Download the object.
  52.         S3Object downloadedObject = encryptionClient.getObject(bucketName,
  53.                 objectKey);
  54.         byte[] decrypted = IOUtils.toByteArray(downloadedObject
  55.                 .getObjectContent());
  56.         
  57.         // Verify same data.
  58.         Assert.assertTrue(Arrays.equals(plaintext, decrypted));
  59.         System.out.println("download file matched the plain text!");
  60.         deleteBucketAndAllContents(encryptionClient);
  61.     }

  62.     private static void deleteBucketAndAllContents(AmazonS3 client) {
  63.         System.out.println("Deleting S3 bucket: " + bucketName);
  64.         ObjectListing objectListing = client.listObjects(bucketName);

  65.         while (true) {
  66.             for ( Iterator<?> iterator = objectListing.getObjectSummaries().iterator(); iterator.hasNext(); ) {
  67.                 S3ObjectSummary objectSummary = (S3ObjectSummary) iterator.next();
  68.                 client.deleteObject(bucketName, objectSummary.getKey());
  69.             }

  70.             if (objectListing.isTruncated()) {
  71.                 objectListing = client.listNextBatchOfObjects(objectListing);
  72.             } else {
  73.                 break;
  74.             }
  75.         };
  76.         VersionListing list = client.listVersions(new ListVersionsRequest().withBucketName(bucketName));
  77.         for ( Iterator<?> iterator = list.getVersionSummaries().iterator(); iterator.hasNext(); ) {
  78.             S3VersionSummary s = (S3VersionSummary)iterator.next();
  79.             client.deleteVersion(bucketName, s.getKey(), s.getVersionId());
  80.         }
  81.         client.deleteBucket(bucketName);
  82.     }
  83. }
复制代码
  • GenerateSymmetricMasterKey.java源码
  1. package crypto_test;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.security.InvalidKeyException;
  7. import java.security.NoSuchAlgorithmException;
  8. import java.security.spec.InvalidKeySpecException;
  9. import java.security.spec.X509EncodedKeySpec;
  10. import java.util.Arrays;
  11. import javax.crypto.KeyGenerator;
  12. import javax.crypto.SecretKey;
  13. import javax.crypto.spec.SecretKeySpec;
  14. import javax.crypto.Cipher;
  15. import org.junit.Assert;

  16. public class GenerateSymmetricMasterKey {

  17.     private static final String keyDir  = System.getProperty("java.io.tmpdir");
  18.     private static final String keyName = "secret.key";
  19.    
  20.     public static void main(String[] args) throws Exception {
  21.             System.out.println("AES max key len:" + Cipher.getMaxAllowedKeyLength("AES"));
  22.         //Generate symmetric 256 bit AES key.
  23.         KeyGenerator symKeyGenerator = KeyGenerator.getInstance("AES");
  24.         symKeyGenerator.init(256);
  25.         SecretKey symKey = symKeyGenerator.generateKey();

  26.         //Save key.
  27.         saveSymmetricKey(keyDir, symKey);
  28.         
  29.         //Load key.
  30.         SecretKey symKeyLoaded = loadSymmetricAESKey(keyDir, "AES");           
  31.         Assert.assertTrue(Arrays.equals(symKey.getEncoded(), symKeyLoaded.getEncoded()));
  32.         System.out.println("symKey: " + (new String(symKey.getEncoded())));
  33.         System.out.println("symKeyLoaded:" + (new String(symKeyLoaded.getEncoded())));
  34.     }

  35.     public static void saveSymmetricKey(String path, SecretKey secretKey)
  36.         throws IOException {
  37.         X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
  38.                 secretKey.getEncoded());
  39.         FileOutputStream keyfos = new FileOutputStream(path + "/" + keyName);
  40.         keyfos.write(x509EncodedKeySpec.getEncoded());
  41.         keyfos.close();
  42.     }
  43.    
  44.     public static SecretKey loadSymmetricAESKey(String path, String algorithm)
  45.         throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException{
  46.         //Read private key from file.
  47.         File keyFile = new File(path + "/" + keyName);
  48.         FileInputStream keyfis = new FileInputStream(keyFile);
  49.         byte[] encodedPrivateKey = new byte[(int)keyFile.length()];
  50.         keyfis.read(encodedPrivateKey);
  51.         keyfis.close();

  52.         //Generate secret key.
  53.         return new SecretKeySpec(encodedPrivateKey, "AES");
  54.     }
  55. }
复制代码
您需要登录后才可以回帖 登录 | 立即注册
您需要登录后才可以发帖 QQ登录

联系我们|腾讯云平台|积分商城|腾讯云官方论坛    

GMT+8, 2018-5-21 20:48 , Processed in 1.163192 second(s), 29 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部