01: package org.bouncycastle.cms;
02:
03: import java.io.InputStream;
04: import java.security.InvalidKeyException;
05: import java.security.Key;
06: import java.security.NoSuchAlgorithmException;
07: import java.security.NoSuchProviderException;
08:
09: import javax.crypto.Cipher;
10: import javax.crypto.NoSuchPaddingException;
11:
12: import org.bouncycastle.asn1.cms.KEKIdentifier;
13: import org.bouncycastle.asn1.cms.KEKRecipientInfo;
14: import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
15:
16: /**
17: * the RecipientInfo class for a recipient who has been sent a message
18: * encrypted using a secret key known to the other side.
19: */
20: public class KEKRecipientInformation extends RecipientInformation {
21: private KEKRecipientInfo _info;
22: private AlgorithmIdentifier _encAlg;
23:
24: public KEKRecipientInformation(KEKRecipientInfo info,
25: AlgorithmIdentifier encAlg, InputStream data) {
26: super (encAlg, AlgorithmIdentifier.getInstance(info
27: .getKeyEncryptionAlgorithm()), data);
28:
29: this ._info = info;
30: this ._encAlg = encAlg;
31: this ._rid = new RecipientId();
32:
33: KEKIdentifier kekId = info.getKekid();
34:
35: _rid.setKeyIdentifier(kekId.getKeyIdentifier().getOctets());
36: }
37:
38: /**
39: * decrypt the content and return an input stream.
40: */
41: public CMSTypedStream getContentStream(Key key, String prov)
42: throws CMSException, NoSuchProviderException {
43: try {
44: byte[] encryptedKey = _info.getEncryptedKey().getOctets();
45: Cipher keyCipher = Cipher.getInstance(_keyEncAlg
46: .getObjectId().getId(), prov);
47:
48: keyCipher.init(Cipher.UNWRAP_MODE, key);
49:
50: AlgorithmIdentifier aid = _encAlg;
51: String alg = aid.getObjectId().getId();
52: Key sKey = keyCipher.unwrap(encryptedKey, alg,
53: Cipher.SECRET_KEY);
54:
55: return getContentFromSessionKey(sKey, prov);
56: } catch (NoSuchAlgorithmException e) {
57: throw new CMSException("can't find algorithm.", e);
58: } catch (InvalidKeyException e) {
59: throw new CMSException("key invalid in message.", e);
60: } catch (NoSuchPaddingException e) {
61: throw new CMSException("required padding not supported.", e);
62: }
63: }
64: }
|