Encryption SDKはクライアント側の暗号化ライブラリであり、Key Management Service (KMS) で使用されます。 これにより、データの暗号化、データの復号化、データの署名と署名の検証を行うことができます。 このトピックでは、Encryption SDK for Javaを使用してデータを暗号化および復号化する方法について説明します。
背景情報
サンプルコードの詳細については、alibabacloud-encryption-sdk-javaをご参照ください。
オンプレミスマシンに暗号化SDKをインストールする
Encryption SDKをコンパイルしてインストールします。
git clone https://github.com/aliyun/alibabacloud-encryption-sdk-java.git cd alibabacloud-encryption-sdk-java mvn clean install -DskipTests
プロジェクトに依存関係を追加します。
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>alibabacloud-encryption-sdk-java</artifactId> <version>X.X.X</version> </dependency>
MavenリポジトリからのEncryption SDKのインストール
プロジェクトにalibabacloud-encryption-sdk-javaの依存関係を追加します。 その後、プロジェクトは公開されたEncryption SDKのJavaパッケージをMavenリポジトリから自動的にダウンロードできます。
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>alibabacloud-encryption-sdk-java</artifactId>
<version>X.X.X</version>
</dependency>
Encryption SDKの最新バージョンの詳細については、Alibaba Cloud Encryption SDK For Javaをご参照ください。
データの暗号化と復号化の例
Alibaba CloudアカウントのAccessKeyペアには、すべてのAPI操作に対する権限があります。 AccessKeyペアを使用して操作を実行することは、リスクの高い操作です。 RAMユーザーを使用してAPI操作を呼び出したり、ルーチンのO&Mを実行することを推奨します。プロジェクトコードにAccessKey IDとAccessKey Secretを保存しないことを推奨します。 そうしないと、AccessKeyペアが漏洩し、アカウントに属するすべてのリソースのセキュリティが侵害される可能性があります。
この例では、AccessKeyペアは、ID認証を実装するためにALIBABA_CLOUD_ACCESS_KEY_IDとALIBABA_CLOUD_ACCESS_KEY_SECRET環境変数に保存されます。
認証情報の設定方法の詳細については、「アクセス資格情報の管理」をご参照ください。
環境変数を設定するために使用される方法は、オペレーティングシステムによって異なります。 詳細については、「Linux、macOS、およびWindowsでの環境変数の設定」をご参照ください。
バイト配列型のデータを暗号化および復号化します。
public class BasicEncryptionExample { private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); private static final String CMK_ARN = "acs:kms:RegionId:UserId:key/CmkId"; private static final byte[] PLAIN_TEXT = "Hello World".getBytes(StandardCharsets.UTF_8); public static void main(String[] args) { // 1. Configure parameters to access Alibaba Cloud. AliyunConfig config = new AliyunConfig(); config.withAccessKey(ACCESS_KEY_ID, ACCESS_KEY_SECRET); // 2. Create an SDK object and specify the parameters that are used to access Alibaba Cloud. AliyunCrypto aliyunSDK = new AliyunCrypto(config); // 3. Create a provider that provides a data key or signature. BaseDataKeyProvider provider = new DefaultDataKeyProvider(CMK_ARN); // Configure the algorithm. The default algorithm is AES_GCM_NOPADDING_256. //provider.setAlgorithm(CryptoAlgorithm.SM4_GCM_NOPADDING_128); // 4. Configure the encryption context. Map<String, String> encryptionContext = new HashMap<>(); encryptionContext.put("one", "one"); encryptionContext.put("two", "two"); // 5. Call the Encrypt and Decrypt operations. CryptoResult<byte[]> cipherResult = aliyunSDK.encrypt(provider, PLAIN_TEXT, encryptionContext); CryptoResult<byte[]> plainResult = aliyunSDK.decrypt(provider, cipherResult.getResult()); Assert.assertArrayEquals(PLAIN_TEXT, plainResult.getResult()); } }
説明完全なコードの詳細については、SimpleEncryptAndDecryptSample.javaをご参照ください。
AccessKey IDとAccessKeyシークレットの取得方法については、「AccessKeyペアを作成します。」をご参照ください。
バイトストリーム型のデータを暗号化および復号化します。
public class FileStreamSample { private static final String FILE = "README.md"; // accessKeyId accessKeySecret private static final String ACCESS_KEY_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"); private static final String ACCESS_KEY_SECRET = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"); // The log system. private static final Logger LOGGER = LoggerFactory.getLogger(FileStreamSample.class); // The ID of the customer master key (CMK) in the Alibaba Cloud Resource Name (ARN) format. private static final String CMK_ARN = "acs:kms:RegionId:UserId:key/CmkId"; public static void main(String[] args) throws IOException { AliyunConfig config = new AliyunConfig(); config.withAccessKey(ACCESS_KEY_ID, ACCESS_KEY_SECRET); encryptStream(config); decryptStream(config); Assert.assertEquals(getFileMD5(FILE), getFileMD5(FILE + ".decrypted")); } private static void encryptStream(AliyunConfig config) throws IOException { // 1. Create an SDK object and specify the parameters that are used to access Alibaba Cloud. AliyunCrypto aliyunSDK = new AliyunCrypto(config); // 2. Configure the encryption context. final Map<String, String> encryptionContext = new HashMap<>(); encryptionContext.put("this", "context"); encryptionContext.put("can help you", "to confirm"); encryptionContext.put("this data", "is your original data"); // 3. Create a provider that provides a data key. BaseDataKeyProvider provider = new DefaultDataKeyProvider(CMK_ARN); // 4. Create input and output streams. FileInputStream inputStream = new FileInputStream(FILE); FileOutputStream outputStream = new FileOutputStream(FILE + ".encrypted"); // 5. Call the Encrypt operation. try { aliyunSDK.encrypt(provider, inputStream, outputStream, encryptionContext); } catch (InvalidAlgorithmException e) { System.out.println("Failed."); System.out.println("Error message: " + e.getMessage()); } } private static void decryptStream(AliyunConfig config) throws IOException { // 1. Create an SDK object and specify the parameters that are used to access Alibaba Cloud. AliyunCrypto aliyunSDK = new AliyunCrypto(config); // 2. Create a provider that provides a data key. BaseDataKeyProvider provider = new DefaultDataKeyProvider(CMK_ARN); // 3. Create input and output streams. FileInputStream inputStream = new FileInputStream(FILE + ".encrypted"); FileOutputStream outputStream = new FileOutputStream(FILE + ".decrypted"); // 4. Call the Decrypt operation. try { aliyunSDK.decrypt(provider, inputStream, outputStream); } catch (InvalidAlgorithmException e) { System.out.println("Failed."); System.out.println("Error message: " + e.getMessage()); } } private static String getFileMD5(String fileName) { File file = new File(fileName); if (!file.isFile()) { return null; } MessageDigest digest; byte[] buffer = new byte[4096]; try (FileInputStream in = new FileInputStream(file)){ digest = MessageDigest.getInstance("MD5"); int len; while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0 , len); } return Hex.encodeHexString(digest.digest()); } catch (Exception e) { e.printStackTrace(); } return null; } }