1package org.bouncycastle.jcajce.provider.asymmetric.util; 2 3import java.security.Key; 4import java.security.PrivateKey; 5import java.security.PublicKey; 6import java.security.spec.InvalidKeySpecException; 7import java.security.spec.KeySpec; 8import java.security.spec.PKCS8EncodedKeySpec; 9import java.security.spec.X509EncodedKeySpec; 10 11import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; 12import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; 13import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; 14 15public abstract class BaseKeyFactorySpi 16 extends java.security.KeyFactorySpi 17 implements AsymmetricKeyInfoConverter 18{ 19 protected PrivateKey engineGeneratePrivate( 20 KeySpec keySpec) 21 throws InvalidKeySpecException 22 { 23 if (keySpec instanceof PKCS8EncodedKeySpec) 24 { 25 try 26 { 27 return generatePrivate(PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded())); 28 } 29 catch (Exception e) 30 { 31 throw new InvalidKeySpecException("encoded key spec not recognized: " + e.getMessage()); 32 } 33 } 34 else 35 { 36 throw new InvalidKeySpecException("key spec not recognized"); 37 } 38 } 39 40 protected PublicKey engineGeneratePublic( 41 KeySpec keySpec) 42 throws InvalidKeySpecException 43 { 44 if (keySpec instanceof X509EncodedKeySpec) 45 { 46 try 47 { 48 return generatePublic(SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded())); 49 } 50 catch (Exception e) 51 { 52 throw new InvalidKeySpecException("encoded key spec not recognized: " + e.getMessage()); 53 } 54 } 55 else 56 { 57 throw new InvalidKeySpecException("key spec not recognized"); 58 } 59 } 60 61 protected KeySpec engineGetKeySpec( 62 Key key, 63 Class spec) 64 throws InvalidKeySpecException 65 { 66 if (spec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8")) 67 { 68 return new PKCS8EncodedKeySpec(key.getEncoded()); 69 } 70 else if (spec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509")) 71 { 72 return new X509EncodedKeySpec(key.getEncoded()); 73 } 74 75 throw new InvalidKeySpecException("not implemented yet " + key + " " + spec); 76 } 77} 78