java. CipherOutputStream, CipherInputStream 을 사용한 암복호화 예제

다음과 같은 방식으로 스트림을 사용해 데이터를 암복호화할 수 있습니다.
예제1번과 예제2번은 이니셜백터를 직접 지정하느냐의 차이만 있습니다.

예제1
String plain = "Hello there. How are you? Have a nice day.";

KeyGenerator kgen = KeyGenerator.getInstance( "AES" );
kgen.init( 256 );
SecretKey aesKey = kgen.generateKey();

Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" );

// Encrypt
cipher.init( Cipher.ENCRYPT_MODE, aesKey );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream( baos, cipher );
cos.write( plain.getBytes() );
cos.flush();
cos.close();
byte[] iv = cipher.getIV();
byte[] enc = baos.toByteArray();

//Decrypt
IvParameterSpec ivParameterSpec = new IvParameterSpec( iv );
cipher.init( Cipher.DECRYPT_MODE, aesKey, ivParameterSpec );
baos = new ByteArrayOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream( enc );
CipherInputStream cis = new CipherInputStream( bais, cipher );
byte[] buffer = new byte[ 1024 ];
int read = -1;
while( ( read = cis.read( buffer ) ) > -1 ){
    baos.write( buffer, 0, read );
}
System.out.println( new String( baos.toByteArray() ) );



예제2
String plain = "Hello there. How are you? Have a nice day.";

SecretKey aesKey = new SecretKeySpec( "00000000000000000000000000000000".getBytes(), "AES" );

//InitialVector를 직접 지정
IvParameterSpec ivParameterSpec = new IvParameterSpec( "0000000000000000".getBytes() );

Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" );

// Encrypt
cipher.init( Cipher.ENCRYPT_MODE, aesKey, ivParameterSpec );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream( baos, cipher );
cos.write( plain.getBytes() );
cos.flush();
cos.close();
byte[] iv = cipher.getIV();
byte[] enc = baos.toByteArray();

//Decrypt
cipher.init( Cipher.DECRYPT_MODE, aesKey, ivParameterSpec );
baos = new ByteArrayOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream( enc );
CipherInputStream cis = new CipherInputStream( bais, cipher );
byte[] buffer = new byte[ 1024 ];
int read = -1;
while( ( read = cis.read( buffer ) ) > -1 ){
    baos.write( buffer, 0, read );
}
System.out.println( new String( baos.toByteArray() ) );

다른글 읽기