1 package org.apache.commons.openpgp;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 import org.bouncycastle.openpgp.PGPException;
21 import org.bouncycastle.openpgp.PGPPublicKey;
22 import org.bouncycastle.openpgp.PGPPublicKeyRing;
23 import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
24 import org.bouncycastle.openpgp.PGPSecretKey;
25 import org.bouncycastle.openpgp.PGPSecretKeyRing;
26 import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
27 import org.bouncycastle.openpgp.PGPUtil;
28
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.util.Iterator;
32
33
34
35
36
37
38
39 public class BouncyCastleKeyRing
40 implements KeyRing
41 {
42 private final PGPSecretKeyRingCollection pgpSec;
43
44 private final char[] password;
45
46 private final PGPPublicKeyRingCollection pgpPub;
47
48 private static final long MASK = 0xFFFFFFFFL;
49
50 public BouncyCastleKeyRing( InputStream secretKeyRingStream, InputStream publicKeyRingStream, char[] password )
51 throws IOException, PGPException
52 {
53 pgpSec = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream( secretKeyRingStream ) );
54
55 pgpPub = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream( publicKeyRingStream ) );
56
57 this.password = password;
58 }
59
60 public char[] getPassword()
61 {
62 return password;
63 }
64
65 public PGPSecretKey getSecretKey( String keyId )
66 {
67 Iterator rIt = pgpSec.getKeyRings();
68
69 while ( rIt.hasNext() )
70 {
71 PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next();
72 Iterator kIt = kRing.getSecretKeys();
73
74 while ( kIt.hasNext() )
75 {
76 PGPSecretKey k = (PGPSecretKey) kIt.next();
77
78
79 if ( k.isSigningKey() && Long.toHexString( k.getKeyID() & MASK ).equals( keyId.toLowerCase() ) )
80 {
81 return k;
82 }
83 }
84 }
85
86 return null;
87 }
88
89 public PGPPublicKey getPublicKey( String keyId )
90 {
91 Iterator rIt = pgpPub.getKeyRings();
92
93 while ( rIt.hasNext() )
94 {
95 PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
96 Iterator kIt = kRing.getPublicKeys();
97
98 while ( kIt.hasNext() )
99 {
100 PGPPublicKey k = (PGPPublicKey) kIt.next();
101
102
103 if ( Long.toHexString( k.getKeyID() & MASK ).equals( keyId.toLowerCase() ) )
104 {
105 return k;
106 }
107 }
108 }
109
110 return null;
111 }
112
113 public PGPSecretKey getSecretKey( long keyId )
114 {
115
116 return getSecretKey( Long.toHexString( keyId & MASK ) );
117 }
118
119 public PGPPublicKey getPublicKey( long keyId )
120 {
121
122 return getPublicKey( Long.toHexString( keyId & MASK ) );
123 }
124 }