summaryrefslogtreecommitdiffstats
path: root/bcprov/src/main/java/org/bouncycastle/crypto/parsers/ECIESPublicKeyParser.java
blob: 1880a5060fdc1cce39f1fa687d960b5e7fdf6960 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package org.bouncycastle.crypto.parsers;

import java.io.IOException;
import java.io.InputStream;

import org.bouncycastle.crypto.KeyParser;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;

public class ECIESPublicKeyParser
    implements KeyParser
{
    private ECDomainParameters ecParams;

    public ECIESPublicKeyParser(ECDomainParameters ecParams)
    {
        this.ecParams = ecParams;
    }

    public AsymmetricKeyParameter readKey(InputStream stream)
        throws IOException
    {
        byte[] V;
        int    first = stream.read();

        // Decode the public ephemeral key
        switch (first)
        {
        case 0x00: // infinity
            throw new IOException("Sender's public key invalid.");

        case 0x02: // compressed
        case 0x03: // Byte length calculated as in ECPoint.getEncoded();
            V = new byte[1 + (ecParams.getCurve().getFieldSize()+7)/8];
            break;

        case 0x04: // uncompressed or
        case 0x06: // hybrid
        case 0x07: // Byte length calculated as in ECPoint.getEncoded();
            V = new byte[1 + 2*((ecParams.getCurve().getFieldSize()+7)/8)];
            break;

        default:
            throw new IOException("Sender's public key has invalid point encoding 0x" + Integer.toString(first, 16));
        }

        V[0] = (byte)first;
        stream.read(V, 1, V.length - 1);

        return new ECPublicKeyParameters(ecParams.getCurve().decodePoint(V), ecParams);
    }
}