0

I am not familiar AES-256 encryption/decryption. I read some tutorial which generate a AES-256 key with following code:

public static SecretKey getAESKey() throws NoSuchAlgorithmException {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256, SecureRandom.getInstanceStrong());

    return keyGen.generateKey();
} 

I want to share that key with client, but when I convert this key into string:

String secretKeyString = Base64.getEncoder().encodeToString(secretKey.getEncoded());
System.out.println("generated key = "+secretKeyString)

it will generate output: KDAgcwjZ2OWwBLgvZtbYwIJ1F8LqABuCPclJhiYfIwA=

This is not a valid 256 bits key. When I try to decrypt the encrypted text using an online tool with that key, it gives an error that key size is not 256 bits. How can I get the key from SecretKey?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    That very much depends on the tool you are using. You see, that string you got, yeah, that is how Base64 encoded binary data looks like. But tools IMPORTING keys rely on the format that a tool like ssh-keygen would generate, for example something like `ssh-rsa A...UwVyG81c= user@whatever.host` In other words: depending on the online tool you are using, you might have to ensure that the string you generate contains those other pieces. – GhostCat Apr 08 '22 at 08:43
  • 3
    And out of curiosity: why do you want to generate keys using java? There are many tools that do that for you, and that nicely create private and public key file for sharing? Finally: security requires **knowledge**. You absolutely shouldn't build your skills on security "by stackoverflow". So: not only read a tutorial here or there, research this topic for real. – GhostCat Apr 08 '22 at 08:46
  • Basically what @GhostCat said. According to https://stackoverflow.com/q/5355466/1651107 you are converting key to base64 correctly. Probably tool you are using does not use the base64 string as key – Piro Apr 08 '22 at 08:48
  • @Piro should i share similar string key with client ? – Abid Akhund Apr 08 '22 at 09:06
  • You simply need to encode the key in a format the online tool expects. Therefore read the documentation of the online encryption tool what it expects/supports, because the generated key of your code and the example key are valid AES256 bit keys in base64 encoding. – Robert Apr 08 '22 at 16:42

0 Answers0