
driven-adapter.kms.kms-adapter.mustache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of scaffold-clean-architecture Show documentation
Show all versions of scaffold-clean-architecture Show documentation
Gradle plugin to create a clean application in Java that already works, It follows our best practices!
package {{package}}.kms;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.kms.KmsAsyncClient;
import software.amazon.awssdk.services.kms.model.DecryptRequest;
import software.amazon.awssdk.services.kms.model.EncryptRequest;
import software.amazon.awssdk.services.kms.model.EncryptionAlgorithmSpec;
import java.util.Base64;
import java.util.concurrent.ExecutionException;
@Component
public class KmsAdapter // implements ModelRepository from domain
{
private final String keyId;
private final KmsAsyncClient kmsAsyncClient;
public KmsAdapter(@Value("${adapters.aws.kms.keyId}") String keyId, KmsAsyncClient kmsAsyncClient) {
this.keyId = keyId;
this.kmsAsyncClient = kmsAsyncClient;
}
public byte[] decrypt(String secretKey) throws ExecutionException, InterruptedException {
return kmsAsyncClient.decrypt(getDecryptRequest(secretKey, keyId))
.get()
.plaintext()
.asByteArray();
}
public String encrypt(byte[] secretKey) throws ExecutionException, InterruptedException {
return Base64.getEncoder().encodeToString(kmsAsyncClient.encrypt(getEncryptRequest(secretKey, keyId))
.get()
.ciphertextBlob().asByteArray());
}
private DecryptRequest getDecryptRequest(String secretKey, String keyId) {
byte[] decodedSecretKey = Base64.getDecoder().decode(secretKey);
return DecryptRequest.builder()
.ciphertextBlob(SdkBytes.fromByteArray(decodedSecretKey))
.keyId(keyId)
.build();
}
private EncryptRequest getEncryptRequest(byte[] secretKey, String keyId) {
return EncryptRequest.builder()
.plaintext(SdkBytes.fromByteArray(secretKey))
.encryptionAlgorithm(EncryptionAlgorithmSpec.SYMMETRIC_DEFAULT)
.keyId(keyId)
.build();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy