Java

AES encrypt decrypt 암호화 복호화

루에 2015. 9. 4. 11:15
반응형

AES방식을 사용한 String 암,복호화다.


복호화한 후에는 new String(Byte)로 return했는데, 이게 서버로 가서 문제를 일으키는지는 확인하지 못했다. 문제 생기면 저것말고 다른 방식으로 byte->String 변환을 해야한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class AESencryp {
    private static final String TAG = AESencryp.class.getSimpleName();
    
    private static final String ALGO = "AES";
    private static final Key KEY;
//    private static final byte[] keyValue = new byte[]{'T','h','e','B','E','S','T','S','e','c',
'e','t','K','e','y'};
//    private static final String plainText = "AES plain text";
    
    static
    {
        KeyGenerator generator = null;
        try {
            generator = KeyGenerator.getInstance(ALGO);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        generator.init(128);
        KEY = generator.generateKey();
    }
 
    public static String encrypt(String plainText){
        try {
            Cipher c = Cipher.getInstance(ALGO);
            c.init(Cipher.ENCRYPT_MODE, KEY);
            byte[] encrypted = c.doFinal(plainText.getBytes());
            Log.d(TAG, "encrypted plain text : " + encrypted);
            return new String(encrypted);
//            return Base64.encodeToString(encrypted, Base64.DEFAULT);
        } catch (NoSuchAlgorithmException e) {
            Log.d(TAG, "NoSuchAlgorithmException");
        } catch (NoSuchPaddingException e) {
            Log.d(TAG, "NoSuchPaddingException");
        } catch (InvalidKeyException e) {
            Log.d(TAG, "InvalidKeyException");
        } catch (BadPaddingException e) {
            Log.d(TAG, "BadPaddingException");
        } catch (IllegalBlockSizeException e) {
            Log.d(TAG, "IllegalBlockSizeException");
        }
        return null;
    }
    
    public static String decrypt(String encryptedText){
        try {
            Cipher c = Cipher.getInstance(ALGO);
            c.init(Cipher.DECRYPT_MODE, KEY);
            byte[] decrypted2 = Base64.decode(encryptedText.getBytes(), Base64.DEFAULT);
            byte[] decrypted = c.doFinal(decrypted2);
            Log.d(TAG, "decrypt : " + decrypted.toString());
            return new String(decrypted);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        }
        return null;
    }
}
 
 cs

반응형