0

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

2
  • 1
    Do you have imported Base64 class? Commented May 29, 2015 at 5:30
  • Please use getBytes("UTF-8") should this app at some time run on a non-UTF-8 platform, like Windows. Commented May 29, 2015 at 6:01

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.