1 19 20 21 package org.openharmonise.him.authentication; 22 import java.util.Random ; 23 24 import javax.crypto.Cipher; 25 import javax.crypto.SecretKey; 26 import javax.crypto.SecretKeyFactory; 27 import javax.crypto.spec.PBEKeySpec; 28 import javax.crypto.spec.PBEParameterSpec; 29 30 import sun.misc.BASE64Decoder; 31 import sun.misc.BASE64Encoder; 32 33 40 41 public class PBE { 42 private static int ITERATIONS = 1000; 43 44 53 public static String encrypt(char[] password, String plaintext) 54 throws Exception { 55 byte[] salt = new byte[8]; 57 Random random = new Random (); 58 random.nextBytes(salt); 59 PBEKeySpec keySpec = new PBEKeySpec(password); 61 SecretKeyFactory keyFactory = 63 SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 64 SecretKey key = keyFactory.generateSecret(keySpec); 66 PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATIONS); 68 Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); 70 cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); 71 byte[] ciphertext = cipher.doFinal(plaintext.getBytes()); 72 BASE64Encoder encoder = new BASE64Encoder(); 73 String saltString = encoder.encode(salt); 74 String ciphertextString = encoder.encode(ciphertext); 75 return saltString + ciphertextString; 76 } 77 78 87 public static String decrypt(char[] password, String text) 88 throws Exception { 89 String salt = text.substring(0, 12); 92 String ciphertext = text.substring(12, text.length()); 93 BASE64Decoder decoder = new BASE64Decoder(); 95 byte[] saltArray = decoder.decodeBuffer(salt); 96 byte[] ciphertextArray = decoder.decodeBuffer(ciphertext); 97 PBEKeySpec keySpec = new PBEKeySpec(password); 99 SecretKeyFactory keyFactory = 101 SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 102 SecretKey key = keyFactory.generateSecret(keySpec); 104 PBEParameterSpec paramSpec = 106 new PBEParameterSpec(saltArray, ITERATIONS); 107 Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); 109 cipher.init(Cipher.DECRYPT_MODE, key, paramSpec); 110 byte[] plaintextArray = cipher.doFinal(ciphertextArray); 112 return new String (plaintextArray); 113 } 114 } 115 | Popular Tags |