全部产品
存储与CDN 数据库 安全 应用服务 数加·人工智能 数加·大数据基础服务 互联网中间件 视频服务 开发者工具 解决方案 物联网 钉钉智能硬件

JAVA SDK样例代码

更新时间:2017-06-07 13:26:11

样例代码

  1. package com.alibaba.samples;
  2. import java.util.*;
  3. import java.util.List;
  4. import com.aliyuncs.DefaultAcsClient;
  5. import com.aliyuncs.exceptions.ClientException;
  6. import com.aliyuncs.http.FormatType;
  7. import com.aliyuncs.http.MethodType;
  8. import com.aliyuncs.http.ProtocolType;
  9. //Current KMS SDK version:2016-01-20
  10. import com.aliyuncs.kms.model.v20160120.CreateKeyRequest;
  11. import com.aliyuncs.kms.model.v20160120.CreateKeyResponse;
  12. import com.aliyuncs.kms.model.v20160120.DecryptRequest;
  13. import com.aliyuncs.kms.model.v20160120.DecryptResponse;
  14. import com.aliyuncs.kms.model.v20160120.DescribeKeyRequest;
  15. import com.aliyuncs.kms.model.v20160120.DescribeKeyResponse;
  16. import com.aliyuncs.kms.model.v20160120.EncryptRequest;
  17. import com.aliyuncs.kms.model.v20160120.EncryptResponse;
  18. import com.aliyuncs.kms.model.v20160120.GenerateDataKeyRequest;
  19. import com.aliyuncs.kms.model.v20160120.GenerateDataKeyResponse;
  20. import com.aliyuncs.kms.model.v20160120.ListKeysRequest;
  21. import com.aliyuncs.kms.model.v20160120.ListKeysResponse;
  22. import com.aliyuncs.kms.model.v20160120.ListKeysResponse.Key;
  23. import com.aliyuncs.profile.DefaultProfile;
  24. import com.aliyuncs.profile.IClientProfile;
  25. public class kmsSample
  26. {
  27. static DefaultAcsClient kmsClient;
  28. private static DefaultAcsClient kmsClient(String regionId, String accessKeyId, String accessKeySecret) {
  29. /**
  30. * Construct an Aliyun Client:
  31. * Set RegionId, AccessKeyId and AccessKeySecret
  32. */
  33. IClientProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
  34. DefaultAcsClient client = new DefaultAcsClient(profile);
  35. return client;
  36. }
  37. private static CreateKeyResponse CreateKey(String keyDesc, String keyUsage) throws ClientException {
  38. final CreateKeyRequest ckReq = new CreateKeyRequest();
  39. ckReq.setProtocol(ProtocolType.HTTPS);
  40. ckReq.setAcceptFormat(FormatType.JSON);
  41. ckReq.setMethod(MethodType.POST);
  42. ckReq.setDescription(keyDesc);
  43. ckReq.setKeyUsage(keyUsage);
  44. final CreateKeyResponse response = kmsClient.getAcsResponse(ckReq);
  45. return response;
  46. }
  47. private static DescribeKeyResponse DescribeKey(String keyId) throws ClientException {
  48. final DescribeKeyRequest decKeyReq = new DescribeKeyRequest();
  49. decKeyReq.setProtocol(ProtocolType.HTTPS);
  50. decKeyReq.setAcceptFormat(FormatType.JSON);
  51. decKeyReq.setMethod(MethodType.POST);
  52. decKeyReq.setKeyId(keyId);
  53. final DescribeKeyResponse decKeyRes = kmsClient.getAcsResponse(decKeyReq);
  54. return decKeyRes;
  55. }
  56. private static ListKeysResponse ListKey(int pageNumber, int pageSize) throws ClientException {
  57. final ListKeysRequest listKeysReq = new ListKeysRequest();
  58. listKeysReq.setProtocol(ProtocolType.HTTPS);
  59. listKeysReq.setAcceptFormat(FormatType.JSON);
  60. listKeysReq.setMethod(MethodType.POST);
  61. listKeysReq.setPageNumber(pageNumber);
  62. listKeysReq.setPageSize(pageSize);
  63. final ListKeysResponse listKeysRes = kmsClient.getAcsResponse(listKeysReq);
  64. return listKeysRes;
  65. }
  66. private static GenerateDataKeyResponse GenerateDataKey(String keyId, String keyDesc, int numOfBytes) throws ClientException {
  67. final GenerateDataKeyRequest genDKReq = new GenerateDataKeyRequest();
  68. genDKReq.setProtocol(ProtocolType.HTTPS);
  69. genDKReq.setAcceptFormat(FormatType.JSON);
  70. genDKReq.setMethod(MethodType.POST);
  71. /**
  72. * Set parameter according to KMS openAPI document:
  73. * 1.KeyId
  74. * 2.KeyDescription
  75. * 3.NumberOfBytes
  76. */
  77. genDKReq.setKeySpec(keyDesc);
  78. genDKReq.setKeyId(keyId);
  79. genDKReq.setNumberOfBytes(numOfBytes);
  80. final GenerateDataKeyResponse genDKRes = kmsClient.getAcsResponse(genDKReq);
  81. return genDKRes;
  82. }
  83. private static EncryptResponse Encrypt(String keyId, String plainText) throws ClientException {
  84. final EncryptRequest encReq = new EncryptRequest();
  85. encReq.setProtocol(ProtocolType.HTTPS);
  86. encReq.setAcceptFormat(FormatType.JSON);
  87. encReq.setMethod(MethodType.POST);
  88. encReq.setKeyId(keyId);
  89. encReq.setPlaintext(plainText);
  90. final EncryptResponse encResponse = kmsClient.getAcsResponse(encReq);
  91. return encResponse;
  92. }
  93. private static DecryptResponse Decrypt(String cipherBlob) throws ClientException {
  94. final DecryptRequest decReq = new DecryptRequest();
  95. decReq.setProtocol(ProtocolType.HTTPS);
  96. decReq.setAcceptFormat(FormatType.JSON);
  97. decReq.setMethod(MethodType.POST);
  98. decReq.setCiphertextBlob(cipherBlob);
  99. final DecryptResponse decResponse = kmsClient.getAcsResponse(decReq);
  100. return decResponse;
  101. }
  102. public static void main(String[] args) {
  103. System.out.println("===========================================");
  104. System.out.println("Getting Started with KMS Service");
  105. System.out.println("===========================================\n");
  106. /**
  107. * RegionId: "cn-hangzhou" and "ap-southeast-1", eg. "cn-hangzhou"
  108. */
  109. String regionId = "cn-hangzhou";
  110. String accessKeyId = "*** Provide your AccessKeyId ***";
  111. String accessKeySecret = "*** Provide your AccessKeySecret ***";
  112. kmsClient = kmsClient(regionId, accessKeyId, accessKeySecret);
  113. String keyId = null;
  114. String plainText = "hello world";
  115. String cipherBlob = null;
  116. // /*Create a Key*/
  117. // try {
  118. // final CreateKeyResponse response = CreateKey("testkey", "ENCRYPT/DECRYPT");
  119. //
  120. // /**
  121. // * Parse response and do more further
  122. // */
  123. // System.out.println(response.getKeyMetadata());
  124. // CreateKeyResponse.KeyMetadata meta = response.getKeyMetadata();
  125. //
  126. // System.out.println("CreateTime: " + meta.getCreationDate());
  127. // System.out.println("Description: " + meta.getDescription());
  128. // System.out.println("KeyId: " + meta.getKeyId());
  129. // keyId = meta.getKeyId();
  130. // System.out.println("KeyState: " + meta.getKeyState());
  131. // System.out.println("KeyUsage: " + meta.getKeyUsage());
  132. //
  133. // System.out.println("===========================================");
  134. // System.out.println("Create MasterKey Success!");
  135. // System.out.println("===========================================\n");
  136. // } catch (ClientException eResponse) {
  137. // System.out.println("Failed.");
  138. // System.out.println("Error code: " + eResponse.getErrCode());
  139. // System.out.println("Error message: " + eResponse.getErrMsg());
  140. // }
  141. //
  142. /*List all MasterKeys in your account*/
  143. try {
  144. final ListKeysResponse listKeysRes = ListKey(1, 100);
  145. /**
  146. * Parse response and do more further
  147. */
  148. System.out.println("TotalCount: " + listKeysRes.getTotalCount());
  149. System.out.println("PageNumber: " + listKeysRes.getPageNumber());
  150. System.out.println("PageSize: " + listKeysRes.getPageSize());
  151. List<Key> keys = listKeysRes.getKeys();
  152. Iterator<Key> iterator = keys.iterator();
  153. while (iterator.hasNext()) {
  154. keyId = iterator.next().getKeyId();
  155. System.out.println("KeyId: " + keyId);
  156. }
  157. System.out.println("===========================================");
  158. System.out.println("List All MasterKeys success!\n");
  159. System.out.println("===========================================\n");
  160. } catch (ClientException eResponse) {
  161. System.out.println("Failed.");
  162. System.out.println("Error code: " + eResponse.getErrCode());
  163. System.out.println("Error message: " + eResponse.getErrMsg());
  164. }
  165. /*Describe the Key */
  166. try {
  167. final DescribeKeyResponse decKeyRes = DescribeKey(keyId);
  168. /**
  169. * Parse response and do more further
  170. */
  171. System.out.println("DescribeKey Response: ");
  172. DescribeKeyResponse.KeyMetadata meta = decKeyRes.getKeyMetadata();
  173. System.out.println("KeyId: " + meta.getKeyId());
  174. System.out.println("Description: " + meta.getDescription());
  175. System.out.println("KeyState: " + meta.getKeyState());
  176. System.out.println("KeyUsage: " + meta.getKeyUsage());
  177. System.out.println("===========================================");
  178. System.out.println("Describe the MasterKey success!");
  179. System.out.println("===========================================\n");
  180. } catch (ClientException eResponse) {
  181. System.out.println("Failed.");
  182. System.out.println("Error code: " + eResponse.getErrCode());
  183. System.out.println("Error message: " + eResponse.getErrMsg());
  184. }
  185. /*Generate DataKey*/
  186. /**
  187. * Request and got response
  188. */
  189. try {
  190. final GenerateDataKeyResponse genDKResponse = GenerateDataKey(keyId, "AES_256", 64);
  191. /**
  192. * Parse response and do more further
  193. */
  194. System.out.println("CiphertextBlob: " + genDKResponse.getCiphertextBlob());
  195. System.out.println("KeyId: " + genDKResponse.getKeyId());
  196. System.out.println("Plaintext: " + genDKResponse.getPlaintext());
  197. System.out.println("===========================================");
  198. System.out.println("Generate DataKey success!");
  199. System.out.println("===========================================\n");
  200. } catch (ClientException eResponse) {
  201. System.out.println("Failed.");
  202. System.out.println("Error code: " + eResponse.getErrCode());
  203. System.out.println("Error message: " + eResponse.getErrMsg());
  204. }
  205. /**
  206. * Encrypt the plain text and got a cipher one
  207. */
  208. try {
  209. EncryptResponse encResponse = Encrypt(keyId, plainText);
  210. cipherBlob = encResponse.getCiphertextBlob();
  211. System.out.println("CiphertextBlob: " + cipherBlob);
  212. System.out.println("KeyId: " + encResponse.getKeyId());
  213. System.out.println("===========================================");
  214. System.out.println("Encrypt the plain text success!");
  215. System.out.println("===========================================\n");
  216. } catch (ClientException eResponse) {
  217. System.out.println("Failed.");
  218. System.out.println("Error code: " + eResponse.getErrCode());
  219. System.out.println("Error message: " + eResponse.getErrMsg());
  220. }
  221. /**
  222. * Decrypt the cipher text and verify result with original plain text.
  223. */
  224. try {
  225. DecryptResponse decResponse = Decrypt(cipherBlob);
  226. System.out.println("Plaintext: " + decResponse.getPlaintext());
  227. String verifyPlainText = decResponse.getPlaintext();
  228. int isMatch = verifyPlainText.compareTo(plainText);
  229. System.out.println("KeyId: " + decResponse.getKeyId());
  230. System.out.println("===========================================");
  231. System.out.printf("Decrypt the cipher text success, result " + (isMatch == 0 ? "match" : "mismatch" + "\n"));
  232. System.out.println("===========================================\n");
  233. } catch (ClientException eResponse) {
  234. System.out.println("Failed.");
  235. System.out.println("Error code: " + eResponse.getErrCode());
  236. System.out.println("Error message: " + eResponse.getErrMsg());
  237. }
  238. }
  239. }

在VPC环境中访问KMS服务

需要添加指向vpc内域名的自定义endpoint。并在后续访问KMS过程中,指定使用这个endpoint。

  1. DefaultProfile.addEndpoint("cn-hangzhou-vpc", "cn-hangzhou-vpc", "Kms", "kms-vpc.cn-hangzhou.aliyuncs.com"); //添加自定义endpoint。

KMS endpoint列表详见:KMS部署情况

本文导读目录