다운로드 : https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
* javascript
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script>
// AES-256-CBC 암호화에 사용할 키와 IV 설정
let key = CryptoJS.enc.Hex.parse("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); // 32바이트 키
let iv = CryptoJS.enc.Hex.parse("abcdef9876543210abcdef9876543210"); // 16바이트 IV
let text = "crypto-js를 활용한 암복호화";
// 암호화
let encrypted = CryptoJS.AES.encrypt(text, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
console.log("Encrypted Text:", encrypted.toString());
// 복호화
let decrypted = CryptoJS.AES.decrypt(encrypted.toString(), key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
console.log("Decrypted Text:", decrypted.toString(CryptoJS.enc.Utf8));
// 결과 : Ojs3Wfzu4YKfGUn5GUY/Ovr5drRZk67N1PVqeo9qDUIEVt+UsNGMGI52CUu7syYe
</script>
* java
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping
@CrossOrigin
public class AesController {
public static void main(String[] args) {
try {
// JavaScript에서 생성된 암호화된 텍스트, 키 및 IV (hex 형식)
String encryptedText = "Ojs3Wfzu4YKfGUn5GUY/Ovr5drRZk67N1PVqeo9qDUIEVt+UsNGMGI52CUu7syYe"; // JavaScript 출력에서 복사
String hexKey = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; // JavaScript 출력에서 복사
String hexIv = "abcdef9876543210abcdef9876543210"; // JavaScript 출력에서 복사
// Hex 문자열을 바이트 배열로 변환
byte[] key = hexStringToByteArray(hexKey);
byte[] iv = hexStringToByteArray(hexIv);
// 복호화 설정
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
// 암호화된 텍스트 복호화
byte[] decodedEncryptedText = Base64.getDecoder().decode(encryptedText);
byte[] decryptedTextBytes = cipher.doFinal(decodedEncryptedText);
String decryptedText = new String(decryptedTextBytes);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
// Hex 문자열을 바이트 배열로 변환하는 유틸리티 메서드
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
}
|