1 7 package org.jboss.security.plugins; 8 9 import javax.crypto.Cipher; 10 import javax.crypto.SecretKey; 11 import javax.crypto.SecretKeyFactory; 12 import javax.crypto.spec.PBEKeySpec; 13 import javax.crypto.spec.PBEParameterSpec; 14 15 import org.jboss.security.Base64Utils; 16 17 29 public class PBEUtils 30 { 31 public static byte[] encode(byte[] secret, String cipherAlgorithm, 32 SecretKey cipherKey, PBEParameterSpec cipherSpec) 33 throws Exception 34 { 35 Cipher cipher = Cipher.getInstance(cipherAlgorithm); 36 cipher.init(Cipher.ENCRYPT_MODE, cipherKey, cipherSpec); 37 byte[] encoding = cipher.doFinal(secret); 38 return encoding; 39 } 40 41 public static String encode64(byte[] secret, String cipherAlgorithm, 42 SecretKey cipherKey, PBEParameterSpec cipherSpec) 43 throws Exception 44 { 45 byte[] encoding = encode(secret, cipherAlgorithm, cipherKey, cipherSpec); 46 String b64 = Base64Utils.tob64(encoding); 47 return b64; 48 } 49 50 public static byte[] decode(byte[] secret, String cipherAlgorithm, 51 SecretKey cipherKey, PBEParameterSpec cipherSpec) 52 throws Exception 53 { 54 Cipher cipher = Cipher.getInstance(cipherAlgorithm); 55 cipher.init(Cipher.DECRYPT_MODE, cipherKey, cipherSpec); 56 byte[] decode = cipher.doFinal(secret); 57 return decode; 58 } 59 60 public static String decode64(String secret, String cipherAlgorithm, 61 SecretKey cipherKey, PBEParameterSpec cipherSpec) 62 throws Exception 63 { 64 byte[] encoding = Base64Utils.fromb64(secret); 65 byte[] decode = decode(encoding, cipherAlgorithm, cipherKey, cipherSpec); 66 return new String (decode, "UTF-8"); 67 } 68 69 public static void main(String [] args) throws Exception 70 { 71 if( args.length != 4 ) 72 { 73 System.err.println( 74 "Ecrypt a password using the JaasSecurityDomain password" 75 +"Usage: PBEUtils salt count domain-password password" 76 +"salt : the Salt attribute from the JaasSecurityDomain" 77 +"count : the IterationCount attribute from the JaasSecurityDomain" 78 +"domain-password : the plaintext password that maps to the KeyStorePass" 79 +" attribute from the JaasSecurityDomain" 80 +"password : the plaintext password that should be encrypted with the" 81 +" JaasSecurityDomain password" 82 ); 83 } 84 85 byte[] salt = args[0].substring(0, 8).getBytes(); 86 int count = Integer.parseInt(args[1]); 87 char[] password = args[2].toCharArray(); 88 byte[] passwordToEncode = args[3].getBytes("UTF-8"); 89 PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, count); 90 PBEKeySpec keySpec = new PBEKeySpec(password); 91 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEwithMD5andDES"); 92 SecretKey cipherKey = factory.generateSecret(keySpec); 93 String encodedPassword = encode64(passwordToEncode, "PBEwithMD5andDES", 94 cipherKey, cipherSpec); 95 System.err.println("Encoded password: "+encodedPassword); 96 } 97 } 98 | Popular Tags |