01: package org.bouncycastle.crypto.agreement.kdf;
02:
03: import org.bouncycastle.asn1.ASN1EncodableVector;
04: import org.bouncycastle.asn1.DERNull;
05: import org.bouncycastle.asn1.DERObjectIdentifier;
06: import org.bouncycastle.asn1.DEROctetString;
07: import org.bouncycastle.asn1.DERSequence;
08: import org.bouncycastle.asn1.DERTaggedObject;
09: import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
10: import org.bouncycastle.crypto.DataLengthException;
11: import org.bouncycastle.crypto.DerivationFunction;
12: import org.bouncycastle.crypto.DerivationParameters;
13: import org.bouncycastle.crypto.Digest;
14: import org.bouncycastle.crypto.generators.KDF2BytesGenerator;
15: import org.bouncycastle.crypto.params.KDFParameters;
16:
17: /**
18: * X9.63 based key derivation function for ECDH CMS.
19: */
20: public class ECDHKEKGenerator implements DerivationFunction {
21: private DerivationFunction kdf;
22:
23: private DERObjectIdentifier algorithm;
24: private int keySize;
25: private byte[] z;
26:
27: public ECDHKEKGenerator(Digest digest) {
28: this .kdf = new KDF2BytesGenerator(digest);
29: }
30:
31: public void init(DerivationParameters param) {
32: DHKDFParameters params = (DHKDFParameters) param;
33:
34: this .algorithm = params.getAlgorithm();
35: this .keySize = params.getKeySize();
36: this .z = params.getZ();
37: }
38:
39: public Digest getDigest() {
40: return kdf.getDigest();
41: }
42:
43: public int generateBytes(byte[] out, int outOff, int len)
44: throws DataLengthException, IllegalArgumentException {
45: // ECC-CMS-SharedInfo
46: ASN1EncodableVector v = new ASN1EncodableVector();
47:
48: v.add(new AlgorithmIdentifier(algorithm, new DERNull()));
49: v.add(new DERTaggedObject(true, 2, new DEROctetString(
50: integerToBytes(keySize))));
51:
52: kdf.init(new KDFParameters(z, new DERSequence(v)
53: .getDEREncoded()));
54:
55: return kdf.generateBytes(out, outOff, len);
56: }
57:
58: private byte[] integerToBytes(int keySize) {
59: byte[] val = new byte[4];
60:
61: val[0] = (byte) (keySize >> 24);
62: val[1] = (byte) (keySize >> 16);
63: val[2] = (byte) (keySize >> 8);
64: val[3] = (byte) keySize;
65:
66: return val;
67: }
68: }
|