1 package org.bouncycastle.jcajce.provider.asymmetric.x509; 2 3 import java.security.InvalidKeyException; 4 import java.security.Key; 5 import java.security.KeyFactorySpi; 6 import java.security.PrivateKey; 7 import java.security.PublicKey; 8 import java.security.spec.InvalidKeySpecException; 9 import java.security.spec.KeySpec; 10 import java.security.spec.PKCS8EncodedKeySpec; 11 import java.security.spec.X509EncodedKeySpec; 12 13 import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; 14 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; 15 import org.bouncycastle.jce.provider.BouncyCastleProvider; 16 17 public class KeyFactory 18 extends KeyFactorySpi 19 { 20 engineGeneratePrivate( KeySpec keySpec)21 protected PrivateKey engineGeneratePrivate( 22 KeySpec keySpec) 23 throws InvalidKeySpecException 24 { 25 if (keySpec instanceof PKCS8EncodedKeySpec) 26 { 27 try 28 { 29 PrivateKeyInfo info = PrivateKeyInfo.getInstance(((PKCS8EncodedKeySpec)keySpec).getEncoded()); 30 PrivateKey key = BouncyCastleProvider.getPrivateKey(info); 31 32 if (key != null) 33 { 34 return key; 35 } 36 37 throw new InvalidKeySpecException("no factory found for OID: " + info.getPrivateKeyAlgorithm().getAlgorithm()); 38 } 39 catch (Exception e) 40 { 41 throw new InvalidKeySpecException(e.toString()); 42 } 43 } 44 45 throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName()); 46 } 47 engineGeneratePublic( KeySpec keySpec)48 protected PublicKey engineGeneratePublic( 49 KeySpec keySpec) 50 throws InvalidKeySpecException 51 { 52 if (keySpec instanceof X509EncodedKeySpec) 53 { 54 try 55 { 56 SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(((X509EncodedKeySpec)keySpec).getEncoded()); 57 PublicKey key = BouncyCastleProvider.getPublicKey(info); 58 59 if (key != null) 60 { 61 return key; 62 } 63 64 throw new InvalidKeySpecException("no factory found for OID: " + info.getAlgorithm().getAlgorithm()); 65 } 66 catch (Exception e) 67 { 68 throw new InvalidKeySpecException(e.toString()); 69 } 70 } 71 72 throw new InvalidKeySpecException("Unknown KeySpec type: " + keySpec.getClass().getName()); 73 } 74 engineGetKeySpec(Key key, Class keySpec)75 protected KeySpec engineGetKeySpec(Key key, Class keySpec) 76 throws InvalidKeySpecException 77 { 78 if (keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8")) 79 { 80 return new PKCS8EncodedKeySpec(key.getEncoded()); 81 } 82 else if (keySpec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509")) 83 { 84 return new X509EncodedKeySpec(key.getEncoded()); 85 } 86 87 throw new InvalidKeySpecException("not implemented yet " + key + " " + keySpec); 88 } 89 engineTranslateKey(Key key)90 protected Key engineTranslateKey(Key key) 91 throws InvalidKeyException 92 { 93 throw new InvalidKeyException("not implemented yet " + key); 94 } 95 }