Raeroxx
Raeroxx

Reputation: 33

what is this return line indicates from java AES encryption method?

This is a block of code from AES encrytion method:

 public  String encrypt(String strToEncrypt) {
        try {
            setKey(myKey);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        } catch (Exception e) {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }

In this code what exactly are we returning to the encrypt method? What does this line here indicate?

Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); 

Upvotes: 1

Views: 70

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308101

First, encryption is almost always a byte[]-to-byte[] thing. So if you want either the input or the output (or both) to be readable String values, then you'll need to do some transformation on the way in and/or on the way out. In this case we do a transformation both ways:

  1. strToEncrypt.getBytes("UTF-8") takes the input String strToEncrypt and converts it into a byte[] using the UTF-8 encoding (a good choice, because it can represent all of Unicode, is universally known/compatible and reasonably compact).
  2. Then cipher.doFinal(...) is the call that executes the actual encryption. Taking the input from #1 and returning a byte[] with the cypher text ("text" is misleading, because that byte[] does not represent readable text, it'll effectively look like binary random noise).
  3. Base64.getEncoder().encodeToString(...) then receives the byte[] returned by doFinal and will encode it using Base64 to get a readable text that represents that binary data.

So in short: encrypts some String and returns the result in a format that could be read by humans, but will almost certainly only be meaningful to a computer.

Upvotes: 1

Related Questions