服务端加密(SSE-C)

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

生成加密密钥

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

private string RandomString(int len)
{
	string s = "123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
	string reValue = string.Empty;
	Random rnd = new Random();
	while (reValue.Length < len)
	{
		string s1 = s[rnd.Next(0, s.Length)].ToString();
		if (reValue.IndexOf(s1) == -1) reValue += s1;
	}
	return reValue;
}

// this.customKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(RandomString(32)));

上传文件

public void putObject()
{
	Console.Out.WriteLine("putObject");
	var key = "ExampleEnc.txt";
	var req = new PutObjectRequest()
	{
		BucketName = bucket,
		Key = key,
		ContentBody = "123",
		ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
		ServerSideEncryptionCustomerProvidedKey = customKey,
	};
	var res = this.s3Client.PutObject(req);
	Console.Out.WriteLine("putObject: {0}", res.ETag);
}

下载文件

public void getObject()
{
	Console.Out.WriteLine("getObject");
	var key = "ExampleEnc.txt";
	var req = new GetObjectRequest()
	{
		BucketName = bucket,
		Key = key,
		ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
		ServerSideEncryptionCustomerProvidedKey = customKey,
	};

	var res = this.s3Client.GetObject(req);
	Stream stream = res.ResponseStream;
	StreamReader sr = new StreamReader(stream);
	string str = sr.ReadToEnd();
	Console.Out.WriteLine("getobject: {0}", str);
}