ㅇ. 소스코드
public class CipherTest {
public static void encrypt(String filePath)
throws Exception {
int availableBytes = -1;
byte[] plainTextBytes = null;
byte[] cipherTextBytes = null;
byte[] keyBytes = null;
byte[] keyAndCipherTextBytes = null;
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
inputStream = new FileInputStream(filePath);
// 파일에 내용이 있는지 확인
availableBytes = inputStream.available();
if (availableBytes <= 0) {
System.out.println("해당파일에 처리할 내용이 없습니다.");
return ;
}
// plainText를 byte[]로 읽음
plainTextBytes = new byte[availableBytes];
inputStream.read(plainTextBytes);
inputStream.close();
// key값 구함
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
keygenerator.init(new SecureRandom());
SecretKey key = keygenerator.generateKey();
// key값으로 암호화함
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
// 'key값 + 암호화한값'을 파일에 저장
cipherTextBytes = cipher.doFinal(plainTextBytes);
keyBytes = key.getEncoded();
keyAndCipherTextBytes = new byte[keyBytes.length + cipherTextBytes.length];
System.arraycopy(keyBytes, 0,
keyAndCipherTextBytes, 0, keyBytes.length);
System.arraycopy(cipherTextBytes, 0,
keyAndCipherTextBytes, keyBytes.length, cipherTextBytes.length);
outputStream = new FileOutputStream(filePath);
outputStream.write(keyAndCipherTextBytes);
outputStream.close();
}
public static void decrypt(String filePath)
throws Exception {
int availableBytes = -1;
SecretKey key = null;
byte[] plainTextBytes = null;
byte[] keyBytes = new byte[8];
byte[] cipherTextBytes = null;
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
inputStream = new FileInputStream(filePath);
// 파일에 내용이 있는지 확인
availableBytes = inputStream.available();
if (availableBytes <= 0) {
System.out.println("해당파일에 처리할 내용이 없습니다.");
return ;
}
// key값과 암호화값의 byte[]를 구함
cipherTextBytes = new byte[availableBytes - keyBytes.length];
inputStream.read(keyBytes);
inputStream.read(cipherTextBytes);
inputStream.close();
// key값 구함
key = new SecretKeySpec(keyBytes, "DES");
// key값으로 복호화함
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
plainTextBytes = cipher.doFinal(cipherTextBytes);
// 복호화한 값 파일에 저장
outputStream = new FileOutputStream(filePath);
outputStream.write(plainTextBytes);
outputStream.close();
}
public static void main(String[] args)
throws UnsupportedEncodingException {
// 파라미터 확인
if (args.length != 2
|| (!args[1].equals("-e") && !args[1].equals("-d")) ) {
System.out.print("파일명과 암호화(-e)와 복호화(-d) 여부를 입력해 주세요. ");
System.out.println("ex)c:\\temp\\a.txt -e");
return;
}
// 파일이 있는지 확인
String filePath = args[0];
String executeOption= args[1];
if (executeOption.equals("-e")) {
try {
CipherTest.encrypt(filePath);
} catch (Exception exception) {
exception.printStackTrace();
}
}else if(executeOption.equals("-d")) {
try {
CipherTest.decrypt(filePath);
} catch (Exception exception) {
exception.printStackTrace();
}
}
}