编码字符串是否有最大base64大小?

时间:2019-03-13 09:44:43

标签: java string base64 decode encode

在将我存储在磁盘上之后,我正在使用Base64对具有数千个数据的巨大json字符串进行编码。稍后,我再次从磁盘检索并将其再次解码为可读的普通字符串json。

public static String encryptString(String string) {     
    byte[] bytesEncoded = Base64.getMimeEncoder().encode(string.getBytes());
    return (new String(bytesEncoded));
}

public static String decryptString(String string) {
    byte[] bytesDecoded = Base64.getMimeDecoder().decode(string);
    return (new String(bytesDecoded));
}

Base64编码和解码函数的大小是否存在限制?还是我可以编码和解码超大字符串?

谢谢。

1 个答案:

答案 0 :(得分:1)

没有最大大小,但我还想提出另一种方法 encrypt decrypt

加密

public static String encrypt(String strClearText,String strKey) throws Exception{
    String strData="";

    try {
        SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
        Cipher cipher=Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, skeyspec);
        String isoText = new String(strClearText.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); // there are shorthand ways of doing this, but this is for your explaination
        byte[] encrypted=cipher.doFinal(isoText.getBytes(StandardCharsets.ISO_8859_1));
        strData=Base64.getEncoder().encodeToString(encrypted);

    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception(e);
    }
    return strData;
}

解密

public static String decrypt(String strEncrypted,String strKey) throws Exception{
    String strData="";

    try {
        SecretKeySpec skeyspec=new SecretKeySpec(strKey.getBytes(),"Blowfish");
        Cipher cipher=Cipher.getInstance("Blowfish");
        cipher.init(Cipher.DECRYPT_MODE, skeyspec);
        byte[] decrypted=cipher.doFinal(Base64.getDecoder().decode(strEncrypted));
        isoStrData=new String(decrypted, StandardCharsets.ISO_8859_1);
        strData=new String(isoStrData.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception(e);
    }
    return strData;
}

键在您的程序中始终可以是常量,但不建议这样做。