简体   繁体   English

编码和解码字符串Java

[英]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: 我在尝试在Java中编码和解码以及字符串的地方有此代码,但是却遇到编译错误,这是代码中注释了错误的代码:

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 我在这里先向您的帮助表示感谢

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. 我的IDE发现了几十个名为Base64类,因此即使名称匹配,也很可能导入了错误的类。

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. 还要注意, java.util.Base64类是在Java 1.8中添加的,因此,如果您使用的是旧版本,则它将不可用。

You can use org.apache.commons.codec.binary.Base64 您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM