Java无需正向或反向斜线编码和解码字符串

use*_*151 3 java base64 aes

我有编码和解码字符串的代码.

当我输入"9"加密方法返回"9iCOC73F/683bf5WRJDnKQ =="

问题是,当我编码String时,它有时会返回带有(/或\)的编码字符串,我想从String中删除它(/或\).

那么我怎么能用我的加密和解密两种方法来实现.

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptDecryptAESAlgo {
    private static final String ALGO = "AES";
    private static final byte[] keyValue = new byte[] { 'A', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p' };

    public String encrypt(String Data) throws Exception {
        String encryptedValue = "";
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGO);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encVal = c.doFinal(Data.getBytes());
            encryptedValue = new BASE64Encoder().encode(encVal);
            return encryptedValue;
        } catch (Exception e) {
        }
        return encryptedValue;
    }

    public String decrypt(String encryptedData) throws Exception {
        String decryptedValue = "";
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGO);
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
            byte[] decValue = c.doFinal(decordedValue);
            decryptedValue = new String(decValue);
            return decryptedValue;
        } catch (Exception e) {
        }
        return decryptedValue;
    }

    private Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGO);
        return key;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Java.

And*_*ndy 5

使用I64F RFC 4648第5节中描述的Base64"URL安全"编码.这将替换+/用文字-_分别.实例化那些编码器/解码器如下:

java.util.Base64.Encoder encoder = java.util.Base64.getUrlEncoder();
java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();
Run Code Online (Sandbox Code Playgroud)