You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

305 lines
9.4 KiB

4 years ago
4 years ago
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "crypto/rand"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. math_rand "math/rand"
  11. "net/http"
  12. "net/url"
  13. "os"
  14. "time"
  15. "github.com/tencentyun/cos-go-sdk-v5"
  16. "github.com/tencentyun/cos-go-sdk-v5/crypto"
  17. "github.com/tencentyun/cos-go-sdk-v5/debug"
  18. )
  19. func log_status(err error) {
  20. if err == nil {
  21. return
  22. }
  23. if cos.IsNotFoundError(err) {
  24. // WARN
  25. fmt.Println("WARN: Resource is not existed")
  26. } else if e, ok := cos.IsCOSError(err); ok {
  27. fmt.Printf("ERROR: Code: %v\n", e.Code)
  28. fmt.Printf("ERROR: Message: %v\n", e.Message)
  29. fmt.Printf("ERROR: Resource: %v\n", e.Resource)
  30. fmt.Printf("ERROR: RequestId: %v\n", e.RequestID)
  31. // ERROR
  32. } else {
  33. fmt.Printf("ERROR: %v\n", err)
  34. // ERROR
  35. }
  36. os.Exit(1)
  37. }
  38. func simple_put_object() {
  39. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  40. b := &cos.BaseURL{BucketURL: u}
  41. c := cos.NewClient(b, &http.Client{
  42. Transport: &cos.AuthorizationTransport{
  43. SecretID: os.Getenv("COS_SECRETID"),
  44. SecretKey: os.Getenv("COS_SECRETKEY"),
  45. Transport: &debug.DebugRequestTransport{
  46. RequestHeader: true,
  47. RequestBody: false,
  48. ResponseHeader: true,
  49. ResponseBody: false,
  50. },
  51. },
  52. })
  53. // Case1 上传对象
  54. name := "test/example2"
  55. fmt.Println("============== simple_put_object ======================")
  56. // 该标识信息唯一确认一个主加密密钥, 解密时,需要传入相同的标识信息
  57. materialDesc := make(map[string]string)
  58. materialDesc["desc"] = "<material information of your master encrypt key>"
  59. // 创建KMS客户端
  60. kmsclient, _ := coscrypto.NewKMSClient(c.GetCredential(), "ap-guangzhou")
  61. // 创建KMS主加密密钥,标识信息和主密钥一一对应
  62. kmsID := os.Getenv("KMSID")
  63. masterCipher, _ := coscrypto.CreateMasterKMS(kmsclient, kmsID, materialDesc)
  64. // 创建加密客户端
  65. client := coscrypto.NewCryptoClient(c, masterCipher)
  66. contentLength := 1024*1024*10 + 1
  67. originData := make([]byte, contentLength)
  68. _, err := rand.Read(originData)
  69. f := bytes.NewReader(originData)
  70. // 加密上传
  71. _, err = client.Object.Put(context.Background(), name, f, nil)
  72. log_status(err)
  73. math_rand.Seed(time.Now().UnixNano())
  74. rangeStart := math_rand.Intn(contentLength)
  75. rangeEnd := rangeStart + math_rand.Intn(contentLength-rangeStart)
  76. opt := &cos.ObjectGetOptions{
  77. Range: fmt.Sprintf("bytes=%v-%v", rangeStart, rangeEnd),
  78. }
  79. // 解密下载
  80. resp, err := client.Object.Get(context.Background(), name, opt)
  81. log_status(err)
  82. defer resp.Body.Close()
  83. decryptedData, _ := ioutil.ReadAll(resp.Body)
  84. if bytes.Compare(decryptedData, originData[rangeStart:rangeEnd+1]) != 0 {
  85. fmt.Println("Error: encryptedData != originData")
  86. }
  87. }
  88. func simple_put_object_from_file() {
  89. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  90. b := &cos.BaseURL{BucketURL: u}
  91. c := cos.NewClient(b, &http.Client{
  92. Transport: &cos.AuthorizationTransport{
  93. SecretID: os.Getenv("COS_SECRETID"),
  94. SecretKey: os.Getenv("COS_SECRETKEY"),
  95. Transport: &debug.DebugRequestTransport{
  96. RequestHeader: true,
  97. RequestBody: false,
  98. ResponseHeader: true,
  99. ResponseBody: false,
  100. },
  101. },
  102. })
  103. // Case1 上传对象
  104. name := "test/example1"
  105. fmt.Println("============== simple_put_object_from_file ======================")
  106. // 该标识信息唯一确认一个主加密密钥, 解密时,需要传入相同的标识信息
  107. materialDesc := make(map[string]string)
  108. materialDesc["desc"] = "<material information of your master encrypt key>"
  109. // 创建KMS客户端
  110. kmsclient, _ := coscrypto.NewKMSClient(c.GetCredential(), "ap-guangzhou")
  111. // 创建KMS主加密密钥,标识信息和主密钥一一对应
  112. kmsID := os.Getenv("KMSID")
  113. masterCipher, _ := coscrypto.CreateMasterKMS(kmsclient, kmsID, materialDesc)
  114. // 创建加密客户端
  115. client := coscrypto.NewCryptoClient(c, masterCipher)
  116. filepath := "test"
  117. fd, err := os.Open(filepath)
  118. log_status(err)
  119. defer fd.Close()
  120. m := md5.New()
  121. io.Copy(m, fd)
  122. originDataMD5 := m.Sum(nil)
  123. // 加密上传
  124. _, err = client.Object.PutFromFile(context.Background(), name, filepath, nil)
  125. log_status(err)
  126. // 解密下载
  127. _, err = client.Object.GetToFile(context.Background(), name, "./test.download", nil)
  128. log_status(err)
  129. fd, err = os.Open("./test.download")
  130. log_status(err)
  131. defer fd.Close()
  132. m = md5.New()
  133. io.Copy(m, fd)
  134. decryptedDataMD5 := m.Sum(nil)
  135. if bytes.Compare(decryptedDataMD5, originDataMD5) != 0 {
  136. fmt.Println("Error: encryptedData != originData")
  137. }
  138. }
  139. func multi_put_object() {
  140. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  141. b := &cos.BaseURL{BucketURL: u}
  142. c := cos.NewClient(b, &http.Client{
  143. Transport: &cos.AuthorizationTransport{
  144. SecretID: os.Getenv("COS_SECRETID"),
  145. SecretKey: os.Getenv("COS_SECRETKEY"),
  146. Transport: &debug.DebugRequestTransport{
  147. RequestHeader: true,
  148. RequestBody: false,
  149. ResponseHeader: true,
  150. ResponseBody: false,
  151. },
  152. },
  153. })
  154. // Case1 上传对象
  155. name := "test/example1"
  156. fmt.Println("============== multi_put_object ======================")
  157. // 该标识信息唯一确认一个主加密密钥, 解密时,需要传入相同的标识信息
  158. materialDesc := make(map[string]string)
  159. materialDesc["desc"] = "<material information of your master encrypt key>"
  160. // 创建KMS客户端
  161. kmsclient, _ := coscrypto.NewKMSClient(c.GetCredential(), "ap-guangzhou")
  162. // 创建KMS主加密密钥,标识信息和主密钥一一对应
  163. kmsID := os.Getenv("KMSID")
  164. masterCipher, _ := coscrypto.CreateMasterKMS(kmsclient, kmsID, materialDesc)
  165. // 创建加密客户端
  166. client := coscrypto.NewCryptoClient(c, masterCipher)
  167. contentLength := int64(1024*1024*10 + 1)
  168. originData := make([]byte, contentLength)
  169. _, err := rand.Read(originData)
  170. log_status(err)
  171. // 分块上传
  172. cryptoCtx := coscrypto.CryptoContext{
  173. DataSize: contentLength,
  174. // 每个分块需要16字节对齐
  175. PartSize: (contentLength / 16 / 3) * 16,
  176. }
  177. v, _, err := client.Object.InitiateMultipartUpload(context.Background(), name, nil, &cryptoCtx)
  178. log_status(err)
  179. // 切分数据
  180. chunks, _, err := cos.SplitSizeIntoChunks(contentLength, cryptoCtx.PartSize)
  181. log_status(err)
  182. optcom := &cos.CompleteMultipartUploadOptions{}
  183. for _, chunk := range chunks {
  184. opt := &cos.ObjectUploadPartOptions{
  185. ContentLength: chunk.Size,
  186. }
  187. f := bytes.NewReader(originData[chunk.OffSet : chunk.OffSet+chunk.Size])
  188. resp, err := client.Object.UploadPart(context.Background(), name, v.UploadID, chunk.Number, f, opt, &cryptoCtx)
  189. log_status(err)
  190. optcom.Parts = append(optcom.Parts, cos.Object{
  191. PartNumber: chunk.Number, ETag: resp.Header.Get("ETag"),
  192. })
  193. }
  194. _, _, err = client.Object.CompleteMultipartUpload(context.Background(), name, v.UploadID, optcom)
  195. log_status(err)
  196. resp, err := client.Object.Get(context.Background(), name, nil)
  197. log_status(err)
  198. defer resp.Body.Close()
  199. decryptedData, _ := ioutil.ReadAll(resp.Body)
  200. if bytes.Compare(decryptedData, originData) != 0 {
  201. fmt.Println("Error: encryptedData != originData")
  202. }
  203. }
  204. func multi_put_object_from_file() {
  205. u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")
  206. b := &cos.BaseURL{BucketURL: u}
  207. c := cos.NewClient(b, &http.Client{
  208. Transport: &cos.AuthorizationTransport{
  209. SecretID: os.Getenv("COS_SECRETID"),
  210. SecretKey: os.Getenv("COS_SECRETKEY"),
  211. Transport: &debug.DebugRequestTransport{
  212. RequestHeader: true,
  213. RequestBody: false,
  214. ResponseHeader: true,
  215. ResponseBody: false,
  216. },
  217. },
  218. })
  219. // Case1 上传对象
  220. name := "test/example1"
  221. fmt.Println("============== multi_put_object_from_file ======================")
  222. // 该标识信息唯一确认一个主加密密钥, 解密时,需要传入相同的标识信息
  223. materialDesc := make(map[string]string)
  224. materialDesc["desc"] = "<material information of your master encrypt key>"
  225. // 创建KMS客户端
  226. kmsclient, _ := coscrypto.NewKMSClient(c.GetCredential(), "ap-guangzhou")
  227. // 创建KMS主加密密钥,标识信息和主密钥一一对应
  228. kmsID := os.Getenv("KMSID")
  229. masterCipher, _ := coscrypto.CreateMasterKMS(kmsclient, kmsID, materialDesc)
  230. // 创建加密客户端
  231. client := coscrypto.NewCryptoClient(c, masterCipher)
  232. filepath := "test"
  233. stat, err := os.Stat(filepath)
  234. log_status(err)
  235. contentLength := stat.Size()
  236. // 分块上传
  237. cryptoCtx := coscrypto.CryptoContext{
  238. DataSize: contentLength,
  239. // 每个分块需要16字节对齐
  240. PartSize: (contentLength / 16 / 3) * 16,
  241. }
  242. // 切分数据
  243. _, chunks, _, err := cos.SplitFileIntoChunks(filepath, cryptoCtx.PartSize)
  244. log_status(err)
  245. // init mulitupload
  246. v, _, err := client.Object.InitiateMultipartUpload(context.Background(), name, nil, &cryptoCtx)
  247. log_status(err)
  248. // part upload
  249. optcom := &cos.CompleteMultipartUploadOptions{}
  250. for _, chunk := range chunks {
  251. fd, err := os.Open(filepath)
  252. log_status(err)
  253. opt := &cos.ObjectUploadPartOptions{
  254. ContentLength: chunk.Size,
  255. }
  256. fd.Seek(chunk.OffSet, os.SEEK_SET)
  257. resp, err := client.Object.UploadPart(context.Background(), name, v.UploadID, chunk.Number, cos.LimitReadCloser(fd, chunk.Size), opt, &cryptoCtx)
  258. log_status(err)
  259. optcom.Parts = append(optcom.Parts, cos.Object{
  260. PartNumber: chunk.Number, ETag: resp.Header.Get("ETag"),
  261. })
  262. }
  263. // complete upload
  264. _, _, err = client.Object.CompleteMultipartUpload(context.Background(), name, v.UploadID, optcom)
  265. log_status(err)
  266. _, err = client.Object.GetToFile(context.Background(), name, "test.download", nil)
  267. log_status(err)
  268. }
  269. func main() {
  270. simple_put_object()
  271. simple_put_object_from_file()
  272. multi_put_object()
  273. multi_put_object_from_file()
  274. }