1 16 package org.jmanage.core.crypto; 17 18 import javax.crypto.spec.PBEKeySpec; 19 import javax.crypto.spec.PBEParameterSpec; 20 import javax.crypto.SecretKeyFactory; 21 import javax.crypto.SecretKey; 22 import javax.crypto.Cipher; 23 24 29 public class Test { 30 31 32 private static final String PWD = "test"; 33 34 public static void main(String [] args) 35 throws Exception { 36 37 String plaintext = "this is plaintext"; 38 byte[] cyphertext = getEncrypted(plaintext); 39 System.out.println(cyphertext); 40 String plaintext1 = getDecrypted(cyphertext); 41 System.out.println(plaintext1); 42 } 43 44 private static byte[] getEncrypted(String plaintext) 45 throws Exception { 46 47 PBEKeySpec pbeKeySpec; 48 PBEParameterSpec pbeParamSpec; 49 SecretKeyFactory keyFac; 50 51 byte[] salt = { 53 (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, 54 (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 55 }; 56 57 int count = 20; 59 60 pbeParamSpec = new PBEParameterSpec(salt, count); 62 63 pbeKeySpec = new PBEKeySpec(PWD.toCharArray()); 64 keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 65 SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); 66 67 Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); 69 70 pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); 72 73 byte[] cleartext = plaintext.getBytes(); 75 76 return pbeCipher.doFinal(cleartext); 78 } 79 80 81 private static String getDecrypted(byte[] cyphertext) 82 throws Exception { 83 84 PBEKeySpec pbeKeySpec; 85 PBEParameterSpec pbeParamSpec; 86 SecretKeyFactory keyFac; 87 88 byte[] salt = { 90 (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, 91 (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 92 }; 93 94 int count = 20; 96 97 pbeParamSpec = new PBEParameterSpec(salt, count); 99 100 pbeKeySpec = new PBEKeySpec(PWD.toCharArray()); 101 keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 102 SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); 103 104 Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); 106 107 pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec); 109 110 return new String (pbeCipher.doFinal(cyphertext)); 112 } 113 } 114 | Popular Tags |