服务端加密(SSE-C)

SSE-C即Server Side Encryption with Custom key,由服务端提供对象的加密功能,用户只需要在执行操作的时候带上加密密钥,由服务端来执行加密和解密操作。

生成加密密钥

服务端使用AES256加密算法,加密密钥由客户端提供,使用32位加密密钥

private void generateAESKey() {
	try {
		KeyGenerator generator = KeyGenerator.getInstance("AES");
		generator.init(256, new SecureRandom());
		customerKey = new SSECustomerKey(generator.generateKey());
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
}

上传文件

public void putObjectWithSSEC() throws AmazonClientException {
	System.out.println("putObjectWithSSEC");
	String key = "ExampleEnc.txt";
	String content = "1234";
	byte[] contentBytes = content.getBytes();
	InputStream is = new ByteArrayInputStream(contentBytes);
	ObjectMetadata meta = new ObjectMetadata();
	PutObjectRequest req = new PutObjectRequest(bucket, key, is, meta);
	req.withSSECustomerKey(customerKey);

	PutObjectResult ret = s3Client.putObject(req);
	System.out.println("putObjectWithSSEC: " + ret.getETag());
}

下载文件

public void getObjectWithSSEC() throws AmazonClientException {
	System.out.println("getObjectWithSSEC");
	try {
		String key = "ExampleEnc.txt";
		GetObjectRequest req = new GetObjectRequest(bucket, key);
		req.withSSECustomerKey(customerKey);
		S3Object object = s3Client.getObject(req);
		S3ObjectInputStream s3is = object.getObjectContent();
		String content = IOUtils.toString(s3is);
		System.out.println("getObjectWithSSEC: " + content);
	} catch (IOException e) {
		e.printStackTrace();
	}
}