【问题标题】:How to convert sun.misc.BASE64Encoder to org.apache.commons.codec.binary.Base64如何将 sun.misc.BASE64Encoder 转换为 org.apache.commons.codec.binary.Base64
【发布时间】:2017-03-14 22:19:28
【问题描述】:

我有以下sun.misc.BASE64Encoder 的代码:

BASE64Decoder decoder = new BASE64Decoder();
byte[] saltArray = decoder.decodeBuffer(saltD);
byte[] ciphertextArray = decoder.decodeBuffer(ciphertext);

并希望将其转换为 org.apache.commons.codec.binary.Base64。我浏览了 API、文档等,但找不到似乎匹配并给出相同结果值的东西。

【问题讨论】:

    标签: java base64 apache-commons-codec


    【解决方案1】:

    其实几乎一模一样:

    Base64 decoder = new Base64();
    byte[] saltArray = decoder.decode(saltD);
    byte[] ciphertextArray = decoder.decode(ciphertext);
    

    解码:

    String saltString = encoder.encodeToString(salt);
    String ciphertextString = encoder.encodeToString(ciphertext);
    

    最后一个更难,因为你在最后使用了“toString”。

    【讨论】:

    • 为什么我收到The method encodeToString(byte[]) is undefined for the type Base64
    • 此方法仅从commons-codec-1.4开始可用
    【解决方案2】:

    您可以使用decodeBase64(byte[] base64Data)decodeBase64(String base64String) 方法。例如:

    byte[] result = Base64.decodeBase64(base64);
    

    这是一个简短的例子:

    import java.io.IOException;
    import org.apache.commons.codec.binary.Base64;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    
    public class TestCodec {
    
        public static void main(String[] args) throws IOException {
            String test = "Test BASE64Encoder vs Base64";
    
    //      String encoded = new BASE64Encoder().encode(test.getBytes("UTF-8"));
    //      byte[] result = new BASE64Decoder().decodeBuffer(encoded);
    
            byte[] encoded = Base64.encodeBase64(test.getBytes("UTF-8"));
            byte[] result = Base64.decodeBase64(encoded);
    
            System.out.println(new String(result, "UTF-8"));
        }
    }
    

    【讨论】:

    • 盐呢?这是我似乎无法开始工作的关键部分。
    【解决方案3】:

    除了这两个类(import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder),你可以使用java.util.Base64类。现在改变编码和解码方法如下。 对于编码:

    String ciphertextString =  Base64.getEncoder().encodeToString(ciphertext);
    

    解码:

      final byte[] encryptedByteArray = Base64.getDecoder().decode(ciphertext);
    

    这里的密文是编码方式中的编码密码。

    现在一切都完成了,您可以保存程序并运行。它将运行而不会显示任何错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2010-09-08
      • 2013-09-21
      • 2011-05-14
      相关资源
      最近更新 更多