1package org.bouncycastle.jcajce.provider.symmetric.util; 2 3import java.lang.reflect.Constructor; 4import java.security.InvalidKeyException; 5import java.security.spec.InvalidKeySpecException; 6import java.security.spec.KeySpec; 7 8import javax.crypto.SecretKey; 9import javax.crypto.SecretKeyFactorySpi; 10import javax.crypto.spec.SecretKeySpec; 11 12import org.bouncycastle.asn1.ASN1ObjectIdentifier; 13 14public class BaseSecretKeyFactory 15 extends SecretKeyFactorySpi 16 implements PBE 17{ 18 protected String algName; 19 protected ASN1ObjectIdentifier algOid; 20 21 protected BaseSecretKeyFactory( 22 String algName, 23 ASN1ObjectIdentifier algOid) 24 { 25 this.algName = algName; 26 this.algOid = algOid; 27 } 28 29 protected SecretKey engineGenerateSecret( 30 KeySpec keySpec) 31 throws InvalidKeySpecException 32 { 33 if (keySpec instanceof SecretKeySpec) 34 { 35 return new SecretKeySpec(((SecretKeySpec)keySpec).getEncoded(), algName); 36 } 37 38 throw new InvalidKeySpecException("Invalid KeySpec"); 39 } 40 41 protected KeySpec engineGetKeySpec( 42 SecretKey key, 43 Class keySpec) 44 throws InvalidKeySpecException 45 { 46 if (keySpec == null) 47 { 48 throw new InvalidKeySpecException("keySpec parameter is null"); 49 } 50 if (key == null) 51 { 52 throw new InvalidKeySpecException("key parameter is null"); 53 } 54 55 if (SecretKeySpec.class.isAssignableFrom(keySpec)) 56 { 57 return new SecretKeySpec(key.getEncoded(), algName); 58 } 59 60 try 61 { 62 Class[] parameters = { byte[].class }; 63 64 Constructor c = keySpec.getConstructor(parameters); 65 Object[] p = new Object[1]; 66 67 p[0] = key.getEncoded(); 68 69 return (KeySpec)c.newInstance(p); 70 } 71 catch (Exception e) 72 { 73 throw new InvalidKeySpecException(e.toString()); 74 } 75 } 76 77 protected SecretKey engineTranslateKey( 78 SecretKey key) 79 throws InvalidKeyException 80 { 81 if (key == null) 82 { 83 throw new InvalidKeyException("key parameter is null"); 84 } 85 86 if (!key.getAlgorithm().equalsIgnoreCase(algName)) 87 { 88 throw new InvalidKeyException("Key not of type " + algName + "."); 89 } 90 91 return new SecretKeySpec(key.getEncoded(), algName); 92 } 93} 94