Java base64 编码和解码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15940763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:21:06  来源:igfitidea点击:

Java base64 encode and decode

javabase64

提问by TonyChou

I am trying to encode byte[]to String, then decode this Stringto byte[], my code is:

我正在尝试编码byte[]String,然后将其解码Stringbyte[],我的代码是:

byte[] aaa = new byte[1];
aaa[0] = (byte) 153;

String encoder = Base64.encodeBase64String(aaa);
System.out.println("encoder <<>> " + encoder);

// Decode the Base64 String.        
byte[] bytes = Base64.decodeBase64(encoder);
String decoder = new String(bytes, "UTF08");
System.out.println("decoder <<>> " + decoder );

Result is:

结果是:

encoder <<>> mQ==
decoder <<>> ?

The result are not the same one. Why does this happen?

结果是不一样的。为什么会发生这种情况?

采纳答案by Ted Hopp

Try this:

试试这个:

byte[] aaa = new byte[1];
aaa[0] = (byte) 153;
System.out.println("original bytes <<>> " + Arrays.toString(aaa));

// Encode the bytes to Base64
String encoder = Base64.encodeBase64String(aaa);
System.out.println("encoder <<>> " + encoder);

// Decode the Base64 String to bytes
byte[] bytes = Base64.decodeBase64(encoder);
System.out.println("decoded bytes <<>> " + Arrays.toString(bytes));

回答by maris

simple static utility methods to encode and decode the given string.

简单的静态实用方法来编码和解码给定的字符串。

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
...

private static byte[] key = {
        0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x41, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x4b, 0x65, 0x79
    };  // "ThisIsASecretKey";

    public static String encrypt(String stringToEncrypt) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        final String encryptedString = Base64.encodeBase64String(cipher.doFinal(stringToEncrypt.getBytes()));
        return encryptedString;
    }

    public static String decrypt(String stringToDecrypt) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        final SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(stringToDecrypt)));
        return decryptedString;
    }