1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package io.github.tonywasher.joceanus.gordianknot.impl.bc.keypair;
19
20 import io.github.tonywasher.joceanus.gordianknot.api.base.GordianException;
21 import io.github.tonywasher.joceanus.gordianknot.impl.bc.keypair.BouncyKeyPairGenerator.BouncyKeyFactorySet;
22 import io.github.tonywasher.joceanus.gordianknot.impl.core.exc.GordianCryptoException;
23 import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
24 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
25 import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
26 import org.bouncycastle.crypto.util.PrivateKeyFactory;
27 import org.bouncycastle.crypto.util.PrivateKeyInfoFactory;
28 import org.bouncycastle.crypto.util.PublicKeyFactory;
29 import org.bouncycastle.crypto.util.SubjectPublicKeyInfoFactory;
30
31 import java.io.IOException;
32 import java.security.spec.PKCS8EncodedKeySpec;
33 import java.security.spec.X509EncodedKeySpec;
34
35
36
37
38 public enum BouncyStdKeyFactorySet
39 implements BouncyKeyFactorySet {
40
41
42
43 INSTANCE;
44
45 @Override
46 public AsymmetricKeyParameter parsePKCS8EncodedKeySpec(final PKCS8EncodedKeySpec pEncodedKey) throws GordianException {
47
48 try {
49
50 final PrivateKeyInfo myInfo = PrivateKeyInfo.getInstance(pEncodedKey.getEncoded());
51 return PrivateKeyFactory.createKey(myInfo);
52
53 } catch (IOException e) {
54 throw new GordianCryptoException(BouncyKeyPairGenerator.ERROR_PARSE, e);
55 }
56 }
57
58 @Override
59 public PKCS8EncodedKeySpec createPKCS8EncodedKeySpec(final AsymmetricKeyParameter pParams) throws GordianException {
60
61 try {
62
63 final PrivateKeyInfo myInfo = PrivateKeyInfoFactory.createPrivateKeyInfo(pParams, null);
64 return new PKCS8EncodedKeySpec(myInfo.getEncoded());
65
66 } catch (IOException e) {
67 throw new GordianCryptoException(BouncyKeyPairGenerator.ERROR_PARSE, e);
68 }
69 }
70
71 @Override
72 public AsymmetricKeyParameter parseX509EncodedKeySpec(final X509EncodedKeySpec pEncodedKey) throws GordianException {
73
74 try {
75
76 final SubjectPublicKeyInfo myInfo = SubjectPublicKeyInfo.getInstance(pEncodedKey.getEncoded());
77 return PublicKeyFactory.createKey(myInfo);
78
79 } catch (IOException e) {
80 throw new GordianCryptoException(BouncyKeyPairGenerator.ERROR_PARSE, e);
81 }
82 }
83
84 @Override
85 public X509EncodedKeySpec createX509EncodedKeySpec(final AsymmetricKeyParameter pParams) throws GordianException {
86
87 try {
88
89 final SubjectPublicKeyInfo myInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(pParams);
90 return new X509EncodedKeySpec(myInfo.getEncoded());
91
92 } catch (IOException e) {
93 throw new GordianCryptoException(BouncyKeyPairGenerator.ERROR_PARSE, e);
94 }
95 }
96 }