加密示例

更新时间: 2019-03-14 10:05

上传对象加密

以下代码展示了在上传对象时使用服务端加密功能:

  1. // 引入依赖包
  2. import (
  3. "fmt"
  4. "obs"
  5. )
  6.  
  7. var ak = "*** Provide your Access Key ***"
  8. var sk = "*** Provide your Secret Key ***"
  9. var endpoint = "https://your-endpoint"
  10.  
  11. // 创建ObsClient结构体
  12. var obsClient, _ = obs.New(ak, sk, endpoint)
  13.  
  14. func main() {
  15. input := &obs.PutFileInput{}
  16. input.Bucket = "bucketname"
  17. input.Key = "objectkey"
  18. input.SourceFile = "localfile"
  19. // 设置SSE-C算法加密对象
  20. input.SseHeader = &obs.SseCHeader{Encryption: "AES256", Key: "your base64-encoded sse-c key generated by AES-256 algorithm"}
  21. output, err := obsClient.PutFile(input)
  22. if err == nil {
  23. fmt.Printf("RequestId:%s\n", output.RequestId)
  24. } else if obsError, ok := err.(obs.ObsError); ok {
  25. fmt.Printf("Code:%s\n", obsError.Code)
  26. fmt.Printf("Message:%s\n", obsError.Message)
  27. }
  28.  
  29. input.Bucket = "bucketname"
  30. input.Key = "objectkey2"
  31. input.SourceFile = "localfile2"
  32. // 设置SSE-KMS算法加密对象
  33. input.SseHeader = &obs.SseKmsHeader{Encryption: "kms"}
  34. output, err = obsClient.PutFile(input)
  35. if err == nil {
  36. fmt.Printf("RequestId:%s\n", output.RequestId)
  37. } else if obsError, ok := err.(obs.ObsError); ok {
  38. fmt.Printf("Code:%s\n", obsError.Code)
  39. fmt.Printf("Message:%s\n", obsError.Message)
  40. }
  41. }

下载对象解密

以下代码展示了在下载对象时使用服务端解密功能:

  1. // 引入依赖包
  2. import (
  3. "fmt"
  4. "obs"
  5. )
  6.  
  7. var ak = "*** Provide your Access Key ***"
  8. var sk = "*** Provide your Secret Key ***"
  9. var endpoint = "https://your-endpoint"
  10.  
  11. // 创建ObsClient结构体
  12. var obsClient, _ = obs.New(ak, sk, endpoint)
  13.  
  14. func main() {
  15. input := &obs.GetObjectInput{}
  16. input.Bucket = "bucketname"
  17. input.Key = "objectkey"
  18. //设置SSE-C算法解密对象,此处的密钥必须和上传对象加密时使用的密钥一致
  19. input.SseHeader = &obs.SseCHeader{Encryption: "AES256", Key: "your base64-encoded sse-c key generated by AES-256 algorithm"}
  20. output, err := obsClient.GetObject(input)
  21. if err == nil {
  22. defer output.Body.Close()
  23. fmt.Printf("ETag:%s\n", output.ETag)
  24. } else if obsError, ok := err.(obs.ObsError); ok {
  25. fmt.Printf("Code:%s\n", obsError.Code)
  26. fmt.Printf("Message:%s\n", obsError.Message)
  27. }
  28. }

父主题:服务端加密