tim blue
tim blue

Reputation: 138

Encode and Decode String Java

I have this code where I am trying to encode and decode and string in java, but am getting compile errors, here is the code with the errors commented in the code:

public static String encrypt(String plainText, SecretKey secretKey)
        throws Exception {
    byte[] plainTextByte = plainText.getBytes();
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] encryptedByte = cipher.doFinal(plainTextByte);
    Encoder encoder = Base64.getEncoder(); //ERROR "cannot resolve method"
    String encryptedText = encoder.encodeToString(encryptedByte);
    return encryptedText;
}

public static String decrypt(String encryptedText, SecretKey secretKey)
        throws Exception {
    Decoder decoder = Base64.getDecoder(); //ERROR "cannot resolve method"
    byte[] encryptedTextByte = (byte[]) decoder.decode(encryptedText);
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
    String decryptedText = new String(decryptedByte);
    return decryptedText;
}

Thanks for the help in advance

Upvotes: 0

Views: 4903

Answers (2)

Kliment Goranov
Kliment Goranov

Reputation: 11

You can use org.apache.commons.codec.binary.Base64

import org.apache.commons.codec.binary.Base64;
...
byte[] encodedBytes = Base64.encodeBase64(byteToEncode);

and for decode

byte[] bytes = Base64.decodeBase64(base64String);

Upvotes: 1

1337joe
1337joe

Reputation: 2367

Check your imports and make sure you're importing:

import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

My IDE found what looks like a couple dozen classes named Base64, so it's entirely possible you're importing the wrong class even though the name matches.

Also note that the java.util.Base64 class was added in java 1.8, so if you're on an older version it won't be available.

Upvotes: 1

Related Questions