Python과 Java의 상호 운용 가능한 암호화 알고리즘 비교
Gzip 압축
Java Gzip 구현
Java에서는 java.util.zip 패키지의 GZIPOutputStream 및 GZIPInputStream 클래스를 사용하여 Gzip 압축 및 해제를 수행합니다. 다음은 예시 코드입니다.
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.nio.charset.StandardCharsets;
public class GzipJavaExample {
public static void main(String[] args) {
try {
String originalData = "안녕하세요";
// Gzip 압축
ByteArrayOutputStream compressedStream = new ByteArrayOutputStream();
try (GZIPOutputStream gzipWriter = new GZIPOutputStream(compressedStream)) {
gzipWriter.write(originalData.getBytes(StandardCharsets.UTF_8));
}
byte[] compressedBytes = compressedStream.toByteArray();
System.out.println("Compressed (Java): " + java.util.Arrays.toString(compressedBytes));
// Gzip 해제
ByteArrayOutputStream decompressedStream = new ByteArrayOutputStream();
ByteArrayInputStream compressedInput = new ByteArrayInputStream(compressedBytes);
try (GZIPInputStream gzipReader = new GZIPInputStream(compressedInput)) {
byte[] buffer = new byte[256];
int bytesRead;
while ((bytesRead = gzipReader.read(buffer)) != -1) {
decompressedStream.write(buffer, 0, bytesRead);
}
}
byte[] decompressedBytes = decompressedStream.toByteArray();
String decompressedString = new String(decompressedBytes, StandardCharsets.UTF_8);
System.out.println("Decompressed (Java): " + decompressedString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Python Gzip 구현
Python에서는 gzip 모듈을 사용하여 Gzip 압축 및 해제를 처리합니다. 다음은 해당 구현입니다.
import gzip
original_data = "안녕하세요"
# Gzip 압축
compressed_bytes = gzip.compress(original_data.encode('utf-8'))
print(f"Compressed (Python): {compressed_bytes}")
print(f"Compressed (Python, hex): {compressed_bytes.hex()}")
# Gzip 해제
decompressed_bytes = gzip.decompress(compressed_bytes)
decompressed_string = decompressed_bytes.decode('utf-8')
print(f"Decompressed (Python): {decompressed_bytes}")
print(f"Decompressed (Python): {decompressed_string}")
AES 암호화
Java AES 구현 (CBC 모드)
Java에서 AES 암호화는 javax.crypto 패키지를 통해 지원됩니다. 다음은 CBC 모드와 PKCS5 패딩을 사용한 예시입니다. Key는 32바이트(256비트)여야 하며, IV는 16바이트여야 합니다.
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class AesJavaExample {
private static final String SECRET_KEY = "thisisasecretkeyforaes256bit1234567890123456"; // 32 bytes key
private static final String INITIALIZATION_VECTOR = "thisisanivfor16bytes"; // 16 bytes IV
public static void main(String[] args) {
String plainText = "안녕하세요";
try {
// AES 암호화
byte[] keyBytes = SECRET_KEY.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(INITIALIZATION_VECTOR.getBytes(StandardCharsets.UTF_8));
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
System.out.println("Encrypted (Java): " + Arrays.toString(encryptedBytes));
System.out.println("Encrypted (Java, hex): " + bytesToHex(encryptedBytes));
// AES 복호화 (검증용)
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
System.out.println("Decrypted (Java): " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
Python AES 구현 (CBC 모드)
Python에서는 pycryptodome 라이브러리(또는 이전 pycrypto)를 사용하여 AES 암호화를 수행합니다. 설치가 필요합니다: pip install pycryptodome.
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import binascii
SECRET_KEY = "thisisasecretkeyforaes256bit1234567890123456" # 32 bytes key
INITIALIZATION_VECTOR = "thisisanivfor16bytes" # 16 bytes IV
def aes_encrypt_cbc(plaintext, key, iv):
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
padded_data = pad(plaintext.encode('utf-8'), AES.block_size)
encrypted_data = cipher.encrypt(padded_data)
return encrypted_data
def aes_decrypt_cbc(ciphertext, key, iv):
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
decrypted_data = cipher.decrypt(ciphertext)
unpadded_data = unpad(decrypted_data, AES.block_size)
return unpadded_data.decode('utf-8')
plain_text = "안녕하세요"
# AES 암호화
encrypted_bytes = aes_encrypt_cbc(plain_text, SECRET_KEY, INITIALIZATION_VECTOR)
print(f"Encrypted (Python): {encrypted_bytes}")
print(f"Encrypted (Python, hex): {binascii.hexlify(encrypted_bytes).decode('utf-8')}")
# AES 복호화 (검증용)
decrypted_text = aes_decrypt_cbc(encrypted_bytes, SECRET_KEY, INITIALIZATION_VECTOR)
print(f"Decrypted (Python): {decrypted_text}")
SHA-256 해시
Java SHA-256 구현
Java에서는 java.security.MessageDigest 클래스를 사용하여 SHA-256과 같은 해시 알고리즘을 구현합니다. Salt를 적용하는 예시입니다.
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class Sha256JavaExample {
public static void main(String[] args) {
String inputData = "안녕하세요";
String salt = "randomsalt"; // Salt value
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// Salt 적용
digest.update(salt.getBytes(StandardCharsets.UTF_8));
// 데이터 해싱
byte[] hashBytes = digest.digest(inputData.getBytes(StandardCharsets.UTF_8));
System.out.println("SHA-256 Hash (Java, bytes): " + Arrays.toString(hashBytes));
System.out.println("SHA-256 Hash (Java, hex): " + bytesToHex(hashBytes));
} catch (Exception e) {
e.printStackTrace();
}
}
// bytesToHex 함수는 위 AES 예제에서 재사용 가능
public static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
Python SHA-256 구현
Python에서는 hashlib 모듈을 사용하여 SHA-256 해싱을 구현합니다. Salt 적용을 포함합니다.
import hashlib
import binascii
input_data = "안녕하세요"
salt = "randomsalt" # Salt value
# SHA-256 해시 객체 생성
sha256_hash = hashlib.sha256()
# Salt 적용
sha256_hash.update(salt.encode('utf-8'))
# 데이터 해싱
sha256_hash.update(input_data.encode('utf-8'))
hash_bytes = sha256_hash.digest()
print(f"SHA-256 Hash (Python, bytes): {hash_bytes}")
print(f"SHA-256 Hash (Python, hex): {binascii.hexlify(hash_bytes).decode('utf-8')}")
MD5 해시
Python MD5 구현
Python의 hashlib 모듈은 MD5 해싱도 지원합니다. Salt 적용 예시입니다.
import hashlib
import binascii
input_string = "안녕하세요"
salt_value = "randomsalt"
# MD5 객체 생성
md5_hasher = hashlib.md5()
# Salt 적용
md5_hasher.update(salt_value.encode('utf-8'))
# 데이터 해싱
md5_hasher.update(input_string.encode('utf-8'))
# 바이트 형태의 해시 값
hash_result_bytes = md5_hasher.digest()
print(f"MD5 Hash (Python, bytes): {hash_result_bytes}")
# 16진수 문자열 형태의 해시 값
hash_result_hex = md5_hasher.hexdigest()
print(f"MD5 Hash (Python, hex): {hash_result_hex}")
Java MD5 구현
Java에서도 MessageDigest 클래스를 사용하여 MD5 해싱을 구현할 수 있습니다. Salt 적용 예시입니다.
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
public class Md5JavaExample {
public static void main(String[] args) {
String inputString = "안녕하세요";
String saltValue = "randomsalt";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
// Salt 적용
md.update(saltValue.getBytes(StandardCharsets.UTF_8));
// 데이터 해싱
byte[] hashBytes = md.digest(inputString.getBytes(StandardCharsets.UTF_8));
System.out.println("MD5 Hash (Java, bytes): " + Arrays.toString(hashBytes));
System.out.println("MD5 Hash (Java, hex): " + bytesToHex(hashBytes));
} catch (Exception e) {
e.printStackTrace();
}
}
// bytesToHex 함수는 위 AES 예제에서 재사용 가능
public static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
Base64 인코딩
Java Base64 구현
Java 8부터 java.util.Base64 클래스를 통해 Base64 인코딩 및 디코딩을 지원합니다. 간단한 예시입니다.
import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class Base64JavaExample {
public static void main(String[] args) {
String originalText = "안녕하세요";
// Base64 인코딩
Base64.Encoder encoder = Base64.getEncoder();
String encodedString = encoder.encodeToString(originalText.getBytes(StandardCharsets.UTF_8));
System.out.println("Encoded (Java): " + encodedString);
// Base64 디코딩
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(encodedString);
String decodedText = new String(decodedBytes, StandardCharsets.UTF_8);
System.out.println("Decoded (Java): " + decodedText);
}
}
Python Base64 구현
Python에서는 base64 모듈을 사용하여 Base64 인코딩 및 디코딩을 처리합니다.
import base64
original_text = "안녕하세요"
# Base64 인코딩
# 먼저 UTF-8 바이트로 인코딩한 후 Base64로 인코딩
encoded_bytes = base64.b64encode(original_text.encode('utf-8'))
encoded_string = encoded_bytes.decode('utf-8') # 결과는 문자열로 보기 위해 디코딩
print(f"Encoded (Python): {encoded_string}")
# Base64 디코딩
# Base64 문자열을 먼저 바이트로 디코딩한 후 UTF-8로 디코딩
decoded_bytes = base64.b64decode(encoded_string.encode('utf-8'))
decoded_text = decoded_bytes.decode('utf-8')
print(f"Decoded (Python): {decoded_text}")