001package org.apache.commons.ssl.org.bouncycastle.asn1.x9;
002
003import java.math.BigInteger;
004
005import org.apache.commons.ssl.org.bouncycastle.asn1.ASN1Object;
006import org.apache.commons.ssl.org.bouncycastle.asn1.ASN1OctetString;
007import org.apache.commons.ssl.org.bouncycastle.asn1.ASN1Primitive;
008import org.apache.commons.ssl.org.bouncycastle.asn1.DEROctetString;
009import org.bouncycastle.math.ec.ECFieldElement;
010
011/**
012 * class for processing an FieldElement as a DER object.
013 */
014public class X9FieldElement
015    extends ASN1Object
016{
017    protected ECFieldElement  f;
018    
019    private static X9IntegerConverter converter = new X9IntegerConverter();
020
021    public X9FieldElement(ECFieldElement f)
022    {
023        this.f = f;
024    }
025    
026    public X9FieldElement(BigInteger p, ASN1OctetString s)
027    {
028        this(new ECFieldElement.Fp(p, new BigInteger(1, s.getOctets())));
029    }
030    
031    public X9FieldElement(int m, int k1, int k2, int k3, ASN1OctetString s)
032    {
033        this(new ECFieldElement.F2m(m, k1, k2, k3, new BigInteger(1, s.getOctets())));
034    }
035    
036    public ECFieldElement getValue()
037    {
038        return f;
039    }
040    
041    /**
042     * Produce an object suitable for an ASN1OutputStream.
043     * <pre>
044     *  FieldElement ::= OCTET STRING
045     * </pre>
046     * <p>
047     * <ol>
048     * <li> if <i>q</i> is an odd prime then the field element is
049     * processed as an Integer and converted to an octet string
050     * according to x 9.62 4.3.1.</li>
051     * <li> if <i>q</i> is 2<sup>m</sup> then the bit string
052     * contained in the field element is converted into an octet
053     * string with the same ordering padded at the front if necessary.
054     * </li>
055     * </ol>
056     */
057    public ASN1Primitive toASN1Primitive()
058    {
059        int byteCount = converter.getByteLength(f);
060        byte[] paddedBigInteger = converter.integerToBytes(f.toBigInteger(), byteCount);
061
062        return new DEROctetString(paddedBigInteger);
063    }
064}