Search code examples
javaamazon-web-servicescryptographypublic-key-encryptionamazon-kms

Encrypt with a AWS KMS Public Key without using an AWS SDK or CLI tool


I have generated a Public-Private pair through the KMS CMK SDK and I retrieved the public key. I am looking for a way to encrypt data with this public key without using the KMS SDK or anything related to amazon. Then I would proceed with decryption by using the KMS API again.

The problem is that the client does not wish to integrate with any AWS related software.

Another important point is that I do want to store my private keys locally nor access them at all. I am using the aws CMK keyId in order to perform encryptions and decryptions.

The algorithm used to generate the pair is: RSAES_OAEP_SHA_256 The key specification is: RSA_4096

I am working with Java and I am looking for a solution with the java security packages.

Any help would be much appreciated, I will amend my question in case more details are needed.


Solution

  • I managed to encrypt using the RSAES_OAEP_SHA_256 algorithm in plain Java and decrypt using the KMS SDK. My solution below:

    public static byte[] encrypt(String plainText, String publicKey) throws GeneralSecurityException {
    
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("OAEP", new BouncyCastleProvider());
        AlgorithmParameterSpec specification = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
        parameters.init(specification);
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding", new BouncyCastleProvider());
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey), parameters);
        return cipher.doFinal(plainText.getBytes());
    }