更新时间:2024-06-18 GMT+08:00
如何生成SSE-C方式的加密密钥(Java SDK)
以下代码展示了如何生成SSE-C方式的加密密钥,以及密钥的MD5值如何生成:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class SseCTool { public static void main(String[] args) { // 加密密钥示例:该密钥可根据业务需要自行修改,但长度必须为32个字符,即256 bit的字符串 String keyString = System.getenv("ACCESS_KEY_ID"); // 计算x-obs-server-side-encryption-customer-key头域 String customerKey = toBase64String(keyString.getBytes(Charset.forName("UTF-8"))); System.out.println("customer key is : " + customerKey); // 计算x-obs-server-side-encryption-customer-key-MD5头域 String customerKeyMD5 = computeMD5(fromBase64(customerKey)); System.out.println("md5 for customer key is : " + customerKeyMD5); } // 计算Base64字符串 public static String toBase64String(byte[] data) { java.util.Base64.Encoder encoder = java.util.Base64.getEncoder(); return new String(encoder.encode(data), Charset.forName("UTF-8")); } // 计算MD5字符串 public static String computeMD5(byte[] b64Data) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(b64Data); byte[] byteArray = md5.digest(); return toBase64String(byteArray); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return ""; } } public static byte[] fromBase64(String b64Data) { java.util.Base64.Decoder decoder = java.util.Base64.getDecoder(); return decoder.decode(b64Data.getBytes(Charset.forName("UTF-8"))); } } |
父主题: 常见问题(Java SDK)