1 16 package org.jmanage.core.crypto; 17 18 import javax.crypto.SecretKey; 19 import javax.crypto.SecretKeyFactory; 20 import javax.crypto.Cipher; 21 import javax.crypto.KeyGenerator; 22 import javax.crypto.spec.PBEKeySpec; 23 import javax.crypto.spec.PBEParameterSpec; 24 import javax.crypto.spec.DESedeKeySpec; 25 26 31 public class EncryptedKey { 32 33 34 public static final String CRYPTO_ALGORITHM = "DESede"; 35 36 private static final String PBE_ALGORITHM = "PBEWithMD5AndDES"; 37 38 39 private static final int KEY_SIZE = 112; 40 41 42 43 44 private static final byte[] salt = { 45 (byte) 0xd7, (byte) 0x73, (byte) 0x31, (byte) 0x8c, 46 (byte) 0x8e, (byte) 0xb7, (byte) 0xee, (byte) 0x91 47 }; 48 49 50 private static final int iteration_count = 1000; 51 52 private SecretKey secretKey; 53 private byte[] encryptedKey; 54 55 public EncryptedKey(char[] password) 56 throws Exception { 57 58 KeyGenerator keyGen = KeyGenerator.getInstance(CRYPTO_ALGORITHM); 59 keyGen.init(KEY_SIZE); 60 SecretKey key = keyGen.generateKey(); 61 this.secretKey = key; 62 this.encryptedKey = getEncrypted(secretKey.getEncoded(), password); 63 } 64 65 public EncryptedKey(byte[] encryptedKey, char[] password) { 66 67 this.encryptedKey = encryptedKey; 68 69 byte[] key = getDecrypted(encryptedKey, password); 70 try { 71 SecretKeyFactory keyFac = SecretKeyFactory.getInstance(CRYPTO_ALGORITHM); 72 this.secretKey = keyFac.generateSecret(new DESedeKeySpec(key));; 73 } catch (Exception e) { 74 throw new RuntimeException (e); 75 } 76 } 77 78 83 public void setPassword(char[] password){ 84 assert password != null; 85 this.encryptedKey = getEncrypted(secretKey.getEncoded(), password); 86 } 87 88 public SecretKey getSecretKey() { 89 return secretKey; 90 } 91 92 public byte[] get() { 93 return encryptedKey; 94 } 95 96 private static byte[] getEncrypted(byte[] plaintext, char[] password) { 97 98 try { 99 100 Cipher pbeCipher = getCipher(Cipher.ENCRYPT_MODE, password); 101 102 return pbeCipher.doFinal(plaintext); 103 } catch (Exception e) { 104 throw new RuntimeException (e); 105 } 106 } 107 108 private static byte[] getDecrypted(byte[] cyphertext, char[] password){ 109 110 try { 111 112 Cipher cipher = getCipher(Cipher.DECRYPT_MODE, password); 113 114 return cipher.doFinal(cyphertext); 115 } catch (Exception e) { 116 throw new RuntimeException (e); 117 } 118 } 119 120 private static Cipher getCipher(int mode, char[] password) 121 throws Exception { 122 123 PBEKeySpec pbeKeySpec; 124 PBEParameterSpec pbeParamSpec; 125 SecretKeyFactory keyFac; 126 127 128 pbeParamSpec = new PBEParameterSpec(salt, iteration_count); 129 130 pbeKeySpec = new PBEKeySpec(password); 131 keyFac = SecretKeyFactory.getInstance(PBE_ALGORITHM); 132 SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); 133 134 135 Cipher pbeCipher = Cipher.getInstance(PBE_ALGORITHM); 136 137 138 pbeCipher.init(mode, pbeKey, pbeParamSpec); 139 return pbeCipher; 140 } 141 } 142 | Popular Tags |