Example usage for org.bouncycastle.asn1.sec ECPrivateKey getParameters

List of usage examples for org.bouncycastle.asn1.sec ECPrivateKey getParameters

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.sec ECPrivateKey getParameters.

Prototype

public ASN1Primitive getParameters() 

Source Link

Usage

From source file:edu.tamu.tcat.crypto.bouncycastle.ASN1SeqKeyImpl.java

License:Apache License

private static PrivateKey decodeECKey(byte[] encodedKey) throws EncodingException {
    try {/*from   ww w.  jav  a2 s  . com*/
        ECPrivateKey priv = ECPrivateKey.getInstance(encodedKey);
        ASN1Sequence parameters = (ASN1Sequence) priv.getParameters();

        ASN1Integer version = (ASN1Integer) parameters.getObjectAt(0);
        if (version.getPositiveValue().intValue() != 1)
            throw new EncodingException("Only know how to decode version 1");
        ASN1Sequence fieldId = (ASN1Sequence) parameters.getObjectAt(1);
        ASN1Encodable fieldType = fieldId.getObjectAt(0);
        ECField field;
        if (fieldType.toString().equals("1.2.840.10045.1.1")) {
            ASN1Integer primeObject = (ASN1Integer) fieldId.getObjectAt(1);
            field = new ECFieldFp(primeObject.getPositiveValue());
        } else
            throw new EncodingException("Only know how to decode prime fields");
        ASN1Sequence curveSeq = (ASN1Sequence) parameters.getObjectAt(2);

        ASN1OctetString a = (ASN1OctetString) curveSeq.getObjectAt(0);
        ASN1OctetString b = (ASN1OctetString) curveSeq.getObjectAt(1);
        EllipticCurve curve;
        if (curveSeq.size() > 2) {
            DERBitString seed = (DERBitString) curveSeq.getObjectAt(2);
            curve = new EllipticCurve(field, getInteger(a.getOctets()), getInteger(b.getOctets()),
                    seed.getBytes());
        } else
            curve = new EllipticCurve(field, getInteger(a.getOctets()), getInteger(b.getOctets()));

        ASN1OctetString gEncoded = (ASN1OctetString) parameters.getObjectAt(3);
        ECPoint g = ECPointUtil.decodePoint(curve, gEncoded.getOctets());
        ASN1Integer n = (ASN1Integer) parameters.getObjectAt(4);
        ASN1Integer h = (ASN1Integer) parameters.getObjectAt(5);
        ECParameterSpec paramSpec = new ECParameterSpec(curve, g, n.getPositiveValue(),
                h.getPositiveValue().intValue());

        ECPrivateKeySpec spec = new ECPrivateKeySpec(priv.getKey(), paramSpec);
        KeyFactory factory = KeyFactory.getInstance("EC", Activator.getDefault().getBouncyCastleProvider());
        PrivateKey key = factory.generatePrivate(spec);
        return key;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new EncodingException("Failed decoding type [EC]", e);
    }
}