Java base64编码和解码

时间:2013-04-11 04:25:38

标签: java base64

我正在尝试将byte[]编码为String,然后将此String解码为byte[],我的代码为:

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

结果是:

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

结果不一样。为什么会这样?

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:0)

用于对给定字符串进行编码和解码的简单静态实用程序方法。

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