Search code examples
javaaesjwk

Android SecretKey AES and JWK : How to convert


I have an app what needs to share private AES keys. (they are wrapped). The server will send and receive the keys in JWK format.

For the moment, in android I can generate AES KEY like this :

public SecretKey  generate() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
        KeyGenerator keyGenerator  = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        KeyGenParameterSpec keyGenParameter = new KeyGenParameterSpec.Builder("MyKeyAlias", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
              .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
              .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
              .build();
        keyGenerator.init(keyGenParameter);
        return keyGenerator.generateKey();

    }

Is there an easy way to convert SecretKey to JWK format ? and vice-versa

If not, I saw the getEncoded() method in SecretKey class. How to export symmetric encryption key?

Maybe I need to create my own class to do the conversion

Thanks


Solution

  • I decided to create my own JWK class. And I used GSON library to parse / stringify JSON.

    Another solution :

    @jps proposed to use this library connect2id.com/products/nimbus-jose-jwt/examples/jwk-generation