진이의 Developer Story
CryptorJS in Java Example 본문
package com.exam.project.util;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AesCipher {
private static final String algorithm = "AES/CBC/NoPadding";
private static final byte[] keyValue = new byte[] { 0x0E, 0x0E, 0x02, 0x01, 0x04, 0x05, 0x0D, 0x07, 0x07, 0x09,
0x0B, 0x0B, 0x0C, 0x0D, 0x0E, 0x0A };
private static final byte[] ivValue = new byte[] { 0x0A, 0x0E, 0x0D, 0x07, 0x0B, 0x0A, 0x09, 0x0A, 0x07, 0x06, 0x03,
0x04, 0x03, 0x0D, 0x01, 0x0B };
private static final IvParameterSpec ivspec = new IvParameterSpec(ivValue);
private static final SecretKeySpec keyspec = new SecretKeySpec(keyValue, "AES");
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String encrypt(String Data) throws Exception {
Data = padString(Data);
Cipher c = Cipher.getInstance(algorithm);
c.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = new BASE64Encoder().encode(encVal);
return encryptedValue;
}
public static String decrypt(String encryptedData) throws Exception {
Cipher c = Cipher.getInstance(algorithm);
c.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String padString(String source) {
char paddingChar = ' ';
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++) {
source += paddingChar;
}
return source;
}
}
알고리즘방식 : AES/CBC/NoPadding (algorithm 상수)
kv, iv : 바이트 형식
'Java' 카테고리의 다른 글
자바 인코딩 확인하기 (0) | 2017.01.03 |
---|---|
String -> JSON 변환 (0) | 2016.02.12 |
양력의 기원 및 양음력 변환방법 (1) (0) | 2016.01.29 |
URL을 사용한 POST 전송 후 결과값 읽어와서 반환하기 (0) | 2016.01.28 |
Eclipse Javadoc (1) | 2016.01.13 |
Comments