자바에서 공통키를 이용하는 안전한 Cipher 생성방법

import java.security.Key; import java.security.MessageDigest; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.faces.FacesException; import org.apache.commons.codec.binary.Base64; public class Test { private static final int IV_LENGTH = 8; private static final int KEY_LENGTH = 24; private static byte[] convertPasswordToKey(byte[] password) { try { MessageDigest md = MessageDigest.getInstance(“SHA”); byte[] seed = md.digest(password); SecureRandom random = SecureRandom.getInstance(“SHA1PRNG”); random.setSeed(seed); byte[] rawkey = new byte[KEY_LENGTH]; random.nextBytes(rawkey); return rawkey; } catch (Exception e) { throw new FacesException(e); } } private static Cipher getBlockCipherForEncryption(SecretKeyFactory keyGen, SecureRandom random, byte[] rawKey) { try { DESedeKeySpec keyspec = new DESedeKeySpec(rawKey); Key key = keyGen.generateSecret(keyspec); Cipher cipher = Cipher.getInstance(“DESede/CBC/PKCS5Padding”); byte[] iv = new byte[IV_LENGTH]; random.nextBytes(iv); IvParameterSpec ivspec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, key, ivspec, random); return cipher; } catch (Exception e) { throw new FacesException(e); } } private static Cipher getBlockCipherForDecryption(SecretKeyFactory keyGen, SecureRandom random, byte[] rawKey, byte[] iv) { try { DESedeKeySpec keyspec = new DESedeKeySpec(rawKey); Key key = keyGen.generateSecret(keyspec); Cipher cipher = Cipher.getInstance(“DESede/CBC/PKCS5Padding”); IvParameterSpec ivspec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, key, ivspec, random); return cipher; } catch (Exception e) { throw new FacesException(e); } } public static void main(String[] args) throws Exception { String password = “1qaz2wsx”; byte[] passwordKey = convertPasswordToKey(password.getBytes()); SecureRandom prng = SecureRandom.getInstance(“SHA1PRNG”); SecretKeyFactory keygen = SecretKeyFactory.getInstance(“DESede”); Cipher encryptCipher = getBlockCipherForEncryption(keygen, prng, passwordKey); byte[] iVector = encryptCipher.getIV(); Cipher decryptCipher = getBlockCipherForDecryption(keygen, prng, passwordKey, iVector); System.out.println(Base64.encodeBase64String(iVector)); } } ]]>

Related Posts

답글 남기기

이메일 주소를 발행하지 않을 것입니다. 필수 항목은 *(으)로 표시합니다