Java编码和解码字符串,不使用正斜杠或反斜杠

7

我有一段编码和解码字符串的代码。

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

问题在于,当我对字符串进行编码时,有时会返回带有(/ 或 \)的编码字符串,我想从字符串中删除(/ 或 \)

那么我该如何在我的加密和解密两个方法中实现这一点呢?

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

我正在使用Java。


1
请在您的期望中添加输入和输出。 - Sanjeev
@Sanjeev 当我输入“9”时,加密方法返回“9iCOC73F/683bf5WRJDnKQ==”。 - user3441151
1
为什么会成为问题呢?“/”是Base64字符集的一部分。你无法避免字符串包含该字符。你可以替换它,但那样会带来其他问题... - Fildor
1
使用Base58、Base36、Base32、Base16、Base10、Base2、Base1?或者您可以用更合适的字符替换有问题的字符。 - Artjom B.
1个回答

15

按照IETF RFC 4648第5节中所述,使用Base64“URL-safe”编码。这将分别用-_字符替换+/字符。根据以下方式实例化这些编码器/解码器:

java.util.Base64.Encoder encoder = java.util.Base64.getUrlEncoder();
java.util.Base64.Decoder decoder = java.util.Base64.getUrlDecoder();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接