2013-04-11 2 views
1

내가 Stringbyte[]를 인코딩하기 위해 노력하고, 다음 디코딩이 Stringbyte[]에, 내 코드는 다음과 같습니다자바 base64로 인코딩 및 디코딩

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 <<>> ? 

결과는 아닙니다이다 같은 것. 왜 이런 일이 생길까요?

+3

물론 동일하지 않습니다. 바이트를 UTF-8로 해석하는 반면 원하는 것은 바이트 값을 인쇄하는 것입니다. – nhahtdh

+0

nhatdh가 말했듯이, 그냥 할 : System.out.println ("decoder <<>"+ bytes [0]); – ebolyen

+0

나는 시도했고, 바이트의 값을 출력했다. 결과는 -103이고, 코드는 – TonyChou

답변

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

빠른 응답을 보내 주셔서 감사합니다. 인쇄 결과는 다음과 같습니다. 원래 바이트 <<>> [-103] 인코더 <<>> mQ == 디코딩 된 바이트 <<>> [이유는 모르겠습니까?] 이 문제를 해결하려면 어떻게해야합니까? – TonyChou

+0

@ TonyChou - 실제로 맞습니다. Java 바이트는 항상 부호있는 수량입니다. 최대 바이트 값은 +127입니다. 153 바이트를 1 바이트로 변환하면 0x99가됩니다. Java에서 값이 오버플로되면 허용 된 범위 내에서 값이 자동으로 줄 바꿈됩니다. 마지막으로 0x99는 2의 보수로 -103입니다. 양수 값을보고 싶다면'byteValue & 0xff'와 같은 것을 할 필요가 있습니다. 이것은'byteValue'를'int'로 승격시킨 다음 일어난 모든 부호 확장을 마스크합니다. –

+0

대단히 감사합니다! 지금 작동합니다. – TonyChou

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