Example usage for org.bouncycastle.crypto.params ECPublicKeyParameters getParameters

List of usage examples for org.bouncycastle.crypto.params ECPublicKeyParameters getParameters

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.params ECPublicKeyParameters getParameters.

Prototype

public ECDomainParameters getParameters() 

Source Link

Usage

From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.ECDHClientKeyExchangeHandler.java

License:Apache License

@Override
byte[] prepareKeyExchangeMessage() {
    if (tlsContext.getEcContext().getServerPublicKeyParameters() == null) {
        // we are probably handling a simple ECDH ciphersuite, we try to
        // establish server public key parameters from the server
        // certificate message
        Certificate x509Cert = tlsContext.getServerCertificate();

        SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
        ECPublicKeyParameters parameters;
        try {//from   www  . jav  a 2  s . co m
            parameters = (ECPublicKeyParameters) PublicKeyFactory.createKey(keyInfo);
            ECPublicKeyParameters publicKeyParameters = (ECPublicKeyParameters) parameters;
            tlsContext.getEcContext().setServerPublicKeyParameters(parameters);
            LOGGER.debug("Parsed the following EC domain parameters from the certificate: ");
            LOGGER.debug("  Curve order: {}", publicKeyParameters.getParameters().getCurve().getOrder());
            LOGGER.debug("  Parameter A: {}", publicKeyParameters.getParameters().getCurve().getA());
            LOGGER.debug("  Parameter B: {}", publicKeyParameters.getParameters().getCurve().getB());
            LOGGER.debug("  Base point: {} ", publicKeyParameters.getParameters().getG());
            LOGGER.debug("  Public key point Q: {} ", publicKeyParameters.getQ());
        } catch (NoSuchMethodError e) {
            LOGGER.debug("The method was not found. It is possible that it is because an older bouncy castle"
                    + " library was used. We try to proceed the workflow.", e);
        } catch (IOException e) {
            throw new WorkflowExecutionException("Problem in parsing public key parameters from certificate",
                    e);
        }
    }

    AsymmetricCipherKeyPair kp = TlsECCUtils.generateECKeyPair(new SecureRandom(),
            tlsContext.getEcContext().getServerPublicKeyParameters().getParameters());

    ECPublicKeyParameters ecPublicKey = (ECPublicKeyParameters) kp.getPublic();
    ECPrivateKeyParameters ecPrivateKey = (ECPrivateKeyParameters) kp.getPrivate();

    // do some ec point modification
    protocolMessage.setPublicKeyBaseX(ecPublicKey.getQ().getAffineXCoord().toBigInteger());
    protocolMessage.setPublicKeyBaseY(ecPublicKey.getQ().getAffineYCoord().toBigInteger());

    ECCurve curve = ecPublicKey.getParameters().getCurve();
    ECPoint point = curve.createPoint(protocolMessage.getPublicKeyBaseX().getValue(),
            protocolMessage.getPublicKeyBaseY().getValue());

    LOGGER.debug("Using the following point:");
    LOGGER.debug("X: " + protocolMessage.getPublicKeyBaseX().getValue().toString());
    LOGGER.debug("Y: " + protocolMessage.getPublicKeyBaseY().getValue().toString());

    // System.out.println("-----------------\nUsing the following point:");
    // System.out.println("X: " + point.getAffineXCoord());
    // System.out.println("Y: " + point.getAffineYCoord());
    // System.out.println("-----------------\n");
    ECPointFormat[] pointFormats = tlsContext.getEcContext().getServerPointFormats();

    try {
        byte[] serializedPoint = ECCUtilsBCWrapper.serializeECPoint(pointFormats, point);
        protocolMessage.setEcPointFormat(serializedPoint[0]);
        protocolMessage.setEcPointEncoded(Arrays.copyOfRange(serializedPoint, 1, serializedPoint.length));
        protocolMessage.setPublicKeyLength(serializedPoint.length);

        byte[] result = ArrayConverter.concatenate(
                new byte[] { protocolMessage.getPublicKeyLength().getValue().byteValue() },
                new byte[] { protocolMessage.getEcPointFormat().getValue() },
                protocolMessage.getEcPointEncoded().getValue());

        byte[] premasterSecret = TlsECCUtils.calculateECDHBasicAgreement(
                tlsContext.getEcContext().getServerPublicKeyParameters(), ecPrivateKey);
        byte[] random = tlsContext.getClientServerRandom();
        protocolMessage.setPremasterSecret(premasterSecret);
        LOGGER.debug("Computed PreMaster Secret: {}",
                ArrayConverter.bytesToHexString(protocolMessage.getPremasterSecret().getValue()));
        LOGGER.debug("Client Server Random: {}", ArrayConverter.bytesToHexString(random));

        PRFAlgorithm prfAlgorithm = AlgorithmResolver.getPRFAlgorithm(tlsContext.getProtocolVersion(),
                tlsContext.getSelectedCipherSuite());
        byte[] masterSecret = PseudoRandomFunction.compute(prfAlgorithm,
                protocolMessage.getPremasterSecret().getValue(), PseudoRandomFunction.MASTER_SECRET_LABEL,
                random, HandshakeByteLength.MASTER_SECRET);
        LOGGER.debug("Computed Master Secret: {}", ArrayConverter.bytesToHexString(masterSecret));

        protocolMessage.setMasterSecret(masterSecret);
        tlsContext.setMasterSecret(protocolMessage.getMasterSecret().getValue());

        return result;

    } catch (IOException ex) {
        throw new WorkflowExecutionException("EC point serialization failure", ex);
    }
}

From source file:de.rub.nds.tlsattacker.tls.protocol.handshake.ECDHEServerKeyExchangeHandler.java

License:Apache License

/**
 * @param message// w w  w .ja v a2  s  .c o  m
 * @param pointer
 * @return
 */
@Override
public int parseMessageAction(byte[] message, int pointer) {
    if (message[pointer] != HandshakeMessageType.SERVER_KEY_EXCHANGE.getValue()) {
        throw new InvalidMessageTypeException(HandshakeMessageType.SERVER_KEY_EXCHANGE);
    }
    protocolMessage.setType(message[pointer]);

    int currentPointer = pointer + HandshakeByteLength.MESSAGE_TYPE;
    int nextPointer = currentPointer + HandshakeByteLength.MESSAGE_TYPE_LENGTH;
    int length = ArrayConverter.bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer));
    protocolMessage.setLength(length);

    currentPointer = nextPointer;
    nextPointer++;
    EllipticCurveType ct = EllipticCurveType.getCurveType(message[currentPointer]);
    if (ct != EllipticCurveType.NAMED_CURVE) {
        throw new UnsupportedOperationException("Currently only named curves are supported");
    }
    protocolMessage.setCurveType(ct.getValue());

    currentPointer = nextPointer;
    nextPointer = currentPointer + NamedCurve.LENGTH;
    NamedCurve nc = NamedCurve.getNamedCurve(Arrays.copyOfRange(message, currentPointer, nextPointer));
    protocolMessage.setNamedCurve(nc.getValue());

    currentPointer = nextPointer;
    nextPointer++;
    int publicKeyLength = message[currentPointer] & 0xFF;
    protocolMessage.setPublicKeyLength(publicKeyLength);

    currentPointer = nextPointer;
    nextPointer = currentPointer + publicKeyLength;
    protocolMessage.setPublicKey(Arrays.copyOfRange(message, currentPointer, nextPointer));

    byte[] ecParams = ArrayConverter.concatenate(new byte[] { protocolMessage.getCurveType().getValue() },
            protocolMessage.getNamedCurve().getValue(),
            ArrayConverter.intToBytes(protocolMessage.getPublicKeyLength().getValue(), 1),
            protocolMessage.getPublicKey().getValue());
    InputStream is = new ByteArrayInputStream(ecParams);

    try {
        ECPublicKeyParameters publicKeyParameters = ECCUtilsBCWrapper.readECParametersWithPublicKey(is);
        LOGGER.debug("Parsed the following EC domain parameters: ");
        LOGGER.debug("  Curve order: {}", publicKeyParameters.getParameters().getCurve().getOrder());
        LOGGER.debug("  Parameter A: {}", publicKeyParameters.getParameters().getCurve().getA());
        LOGGER.debug("  Parameter B: {}", publicKeyParameters.getParameters().getCurve().getB());
        LOGGER.debug("  Base point: {} ", publicKeyParameters.getParameters().getG());
        LOGGER.debug("  Public key point Q: {} ", publicKeyParameters.getQ());

        tlsContext.getEcContext().setServerPublicKeyParameters(publicKeyParameters);

        currentPointer = nextPointer;
        nextPointer++;
        HashAlgorithm ha = HashAlgorithm.getHashAlgorithm(message[currentPointer]);
        protocolMessage.setHashAlgorithm(ha.getValue());

        currentPointer = nextPointer;
        nextPointer++;
        SignatureAlgorithm sa = SignatureAlgorithm.getSignatureAlgorithm(message[currentPointer]);
        protocolMessage.setSignatureAlgorithm(sa.getValue());

        currentPointer = nextPointer;
        nextPointer = currentPointer + HandshakeByteLength.SIGNATURE_LENGTH;
        int signatureLength = ArrayConverter
                .bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer));
        protocolMessage.setSignatureLength(signatureLength);

        currentPointer = nextPointer;
        nextPointer = currentPointer + signatureLength;
        protocolMessage.setSignature(Arrays.copyOfRange(message, currentPointer, nextPointer));

        protocolMessage.setCompleteResultingMessage(Arrays.copyOfRange(message, pointer, nextPointer));

        return nextPointer;
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new WorkflowExecutionException("EC public key parsing failed", ex);
    }
}

From source file:dorkbox.util.crypto.CryptoECC.java

License:Apache License

/**
 * @return true if publicA and publicB are NOT NULL, and are both equal to eachother
 *///from  w  w w  .  j a  v a2s . com
@SuppressWarnings({ "RedundantIfStatement", "SpellCheckingInspection" })
public static boolean compare(ECPublicKeyParameters publicA, ECPublicKeyParameters publicB) {
    if (publicA == null || publicB == null) {
        return false;
    }

    ECDomainParameters parametersA = publicA.getParameters();
    ECDomainParameters parametersB = publicB.getParameters();

    // is it the same curve?
    boolean equals = parametersA.getCurve().equals(parametersB.getCurve());
    if (!equals) {
        return false;
    }

    equals = parametersA.getG().equals(parametersB.getG());
    if (!equals) {
        return false;
    }

    equals = parametersA.getH().equals(parametersB.getH());
    if (!equals) {
        return false;
    }

    equals = parametersA.getN().equals(parametersB.getN());
    if (!equals) {
        return false;
    }

    ECPoint normalizeA = publicA.getQ().normalize();
    ECPoint normalizeB = publicB.getQ().normalize();

    ECFieldElement xCoordA = normalizeA.getXCoord();
    ECFieldElement xCoordB = normalizeB.getXCoord();

    equals = xCoordA.equals(xCoordB);
    if (!equals) {
        return false;
    }

    ECFieldElement yCoordA = normalizeA.getYCoord();
    ECFieldElement yCoordB = normalizeB.getYCoord();

    equals = yCoordA.equals(yCoordB);
    if (!equals) {
        return false;
    }

    return true;
}

From source file:dorkbox.util.serialization.EccPublicKeySerializer.java

License:Apache License

public static void write(Output output, ECPublicKeyParameters key) throws KryoException {
    byte[] bytes;
    int length;//from  w  w  w  . j  a  v a2s.co m

    ECDomainParameters parameters = key.getParameters();
    ECCurve curve = parameters.getCurve();

    EccPrivateKeySerializer.serializeCurve(output, curve);

    /////////////
    BigInteger n = parameters.getN();
    ECPoint g = parameters.getG();

    /////////////
    bytes = n.toByteArray();
    length = bytes.length;
    output.writeInt(length, true);
    output.writeBytes(bytes, 0, length);

    EccPrivateKeySerializer.serializeECPoint(g, output);
    EccPrivateKeySerializer.serializeECPoint(key.getQ(), output);
}

From source file:eu.betaas.taas.securitymanager.common.mqv.ECMQVUtils.java

License:Apache License

/**
 * A method to perform embedded public key validation (BC style)
 * @param pub: the public key to be validated
 * @return true if valid/*w  w w . j  av a2 s  . c o m*/
 */
public static boolean validateEmbedPubKey(AsymmetricKeyParameter pub) {

    ECPublicKeyParameters ecPub = (ECPublicKeyParameters) pub;
    ECCurve.Fp fpCurve = (Fp) ecPub.getParameters().getCurve();
    BigInteger p = fpCurve.getQ();
    BigInteger xq = ecPub.getQ().normalize().getXCoord().toBigInteger();
    BigInteger yq = ecPub.getQ().normalize().getYCoord().toBigInteger();

    // validate the xq and yq, they must be in the interval [0,q-1]
    if (xq.compareTo(BigInteger.ZERO) == -1 && xq.compareTo(p.subtract(BigInteger.ONE)) == 1
            && yq.compareTo(BigInteger.ZERO) == -1 && yq.compareTo(p.subtract(BigInteger.ONE)) == 1)
        return false;

    BigInteger a = fpCurve.getA().toBigInteger();
    BigInteger b = fpCurve.getB().toBigInteger();

    // test whether Q lies in the curve defined by y^2(mod p)=x^3+ax+b (mod p)
    BigInteger rightEq = xq.pow(3).add(a.multiply(xq)).add(b).mod(p);
    //      System.out.println("x^3+ax+b    = "+rightEq.toString());

    BigInteger y2 = yq.pow(2).mod(p);
    //      System.out.println("y^2       = "+y2.toString());

    if (y2.compareTo(rightEq) != 0)
        return false;

    return true;
}

From source file:eu.betaas.taas.securitymanager.common.mqv.ECMQVUtils.java

License:Apache License

/**
 * A method to compute the implicit signature, s (BC style), defined as: 
 * s = (ephPriv +   ephPub_*statPriv)mod(n)
 * @param ephPub: the ephemeral public key
 * @param ephPriv: the ephemeral private key
 * @param statPriv: the static private key
 * @return implicit signature//w  w  w  . j  av a  2  s  .c  om
 */
public static BigInteger computeImplicitSig(ECPublicKeyParameters ephPub, ECPrivateKeyParameters ephPriv,
        ECPrivateKeyParameters statPriv) {

    BigInteger n = ephPub.getParameters().getN();
    BigInteger r_ = ephPriv.getD();
    BigInteger w_ = statPriv.getD();

    BigInteger Rx = ephPub.getQ().normalize().getXCoord().toBigInteger();

    BigInteger Rx_ = calculateRx_(Rx, n);

    BigInteger implS = r_.add(Rx_.multiply(w_)).mod(n);

    return implS;
}

From source file:eu.betaas.taas.securitymanager.common.mqv.ECMQVUtils.java

License:Apache License

/**
 * A method to calculate the shared key (BC Style), 
 * K = h*implicitSignature(ephPub + Rx_*statPub)
 * @param ephPub: the ephemeral public key 
 * @param statPub: the static/long term public key 
 * @param h: the EC cofactor/*from  w  ww  . java2s  .  c  o  m*/
 * @param implSig: the implicit signature 
 * @return the shared secret key, K
 */
public static org.bouncycastle.math.ec.ECPoint calculateSharedKey(ECPublicKeyParameters ephPub,
        ECPublicKeyParameters statPub, BigInteger h, BigInteger implSig) {

    // ECPoint of the ephemeral public key 
    org.bouncycastle.math.ec.ECPoint wEph = ephPub.getQ();
    // ECPoint of the static public key
    org.bouncycastle.math.ec.ECPoint wStat = statPub.getQ();

    // K = h*implSig*(ephPub +ephPub_*statPub)
    // to do this, we need to calculate scalar multiplication of an ECPoint
    BigInteger n = statPub.getParameters().getN();
    // calculate the Rx_ (ephPub_)
    BigInteger Rx_ = calculateRx_(wEph.normalize().getXCoord().toBigInteger(), n);

    // calculate the ephPub_*statPub
    org.bouncycastle.math.ec.ECPoint R = wStat.multiply(Rx_);
    //calculate the ephPub + ephPub_*statPub (ephPub + R)
    R = R.add(wEph);
    //calculate the h * implicit signature
    BigInteger hImplSig = implSig.multiply(h);
    // finally, calculate the shared key K = h*implSig*(ephPub +ephPub_*statPub)
    org.bouncycastle.math.ec.ECPoint K = R.multiply(hImplSig);

    return K;
}

From source file:org.cryptoworkshop.ximix.client.verify.ECDecryptionChallengeVerifier.java

License:Apache License

/**
 * Verify that the decryption challenge transcript is valid, throwing an exception if an issue is found..
 *
 * @throws TranscriptVerificationException on verification failure.
 *//*from  w  w  w . j a  va  2  s  .c o m*/
public void verify() throws TranscriptVerificationException {
    ASN1InputStream aIn = new ASN1InputStream(logStream);
    ASN1InputStream resultIn = new ASN1InputStream(resultStream);
    ASN1InputStream lastIn = new ASN1InputStream(lastStageStream);

    try {
        int messageIndex = -1;
        ECPair[] encPairs = null;

        ASN1Object obj;
        while ((obj = aIn.readObject()) != null) {
            ChallengeLogMessage logMessage = ChallengeLogMessage.getInstance(obj);

            ECPoint[] sourceMessage = logMessage.getSourceMessage();
            ECDecryptionProof[] proofs = logMessage.getProofs();

            ECPublicKeyParameters currentPubKey = (ECPublicKeyParameters) PublicKeyFactory
                    .createKey(logMessage.getKeyInfo());
            if (!isSameParameters(pubKey.getParameters(), currentPubKey.getParameters())) {
                throw new TranscriptVerificationException(
                        "Log message indicates inconsistent public key parameters.");
            }

            if (messageIndex != logMessage.getIndex()) {
                if (activePeers.length != 0) {
                    LagrangeWeightCalculator weightCalculator = new LagrangeWeightCalculator(maxSequenceNo + 1,
                            pubKey.getParameters().getN());

                    ECPoint accumulatedQ = null;

                    BigInteger[] weights = weightCalculator.computeWeights(activePeers);

                    // verify the partial public keys represent the one we have.
                    for (int i = 0; i != weights.length; i++) {
                        if (weights[i] != null) {
                            if (accumulatedQ == null) {
                                accumulatedQ = activePeers[i].getQ().multiply(weights[i]);
                            } else {
                                accumulatedQ = accumulatedQ.add(activePeers[i].getQ().multiply(weights[i]));
                            }
                        }
                    }

                    if (!pubKey.getQ().equals(accumulatedQ)) {
                        throw new TranscriptVerificationException(
                                "Log message indicates inconsistent public key.");
                    }

                    // verify the partial decrypts result in the final message

                    int len = activeMsgParts[0].length;
                    for (int i = 1; i != activeMsgParts.length; i++) {
                        if (activeMsgParts[i].length != len) {
                            throw new TranscriptVerificationException("Partial decrypt length mismatch");
                        }
                    }

                    int baseIndex = 0;
                    for (int i = 0; i != activeMsgParts.length; i++) {
                        if (activeMsgParts[i] != null) {
                            baseIndex = i;
                            break;
                        }
                    }

                    BigInteger baseWeight = weights[baseIndex];

                    ECPoint[] decryptions = reassemblePoints(activeMsgParts, encPairs, weights, baseIndex,
                            baseWeight);

                    ECPoint[] recordedDecrypts = PointSequence
                            .getInstance(pubKey.getParameters().getCurve(), resultIn.readObject())
                            .getECPoints();

                    if (!Arrays.areEqual(decryptions, recordedDecrypts)) {
                        throw new TranscriptVerificationException(
                                "Recorded decrypts do not match partial ones.");
                    }

                    // reset the peers array.
                    for (int i = 0; i != activePeers.length; i++) {
                        activePeers[i] = null;
                    }
                    for (int i = 0; i != activeMsgParts.length; i++) {
                        activeMsgParts[i] = null;
                    }
                } else if (messageIndex != -1) {
                    throw new TranscriptVerificationException("Nothing to verify!");
                }

                messageIndex = logMessage.getIndex();
                PostedMessage pM = PostedMessage.getInstance(lastIn.readObject());
                encPairs = PairSequence.getInstance(pubKey.getParameters().getCurve(), pM.getMessage())
                        .getECPairs();
            }

            addPeer(logMessage.getSequenceNo(), currentPubKey, sourceMessage);

            if (!logMessage.hasPassed()) {
                throw new TranscriptVerificationException("Log message indicates challenge did not pass.");
            }

            for (int i = 0; i != proofs.length; i++) {
                if (!proofs[i].isVerified(activePeers[logMessage.getSequenceNo()], encPairs[i].getX(),
                        sourceMessage[i])) {
                    throw new TranscriptVerificationException(
                            "Proof results do not match combined source message and cipher text.");
                }
            }
        }
    } catch (TranscriptVerificationException e) {
        throw e;
    } catch (Exception e) {
        throw new TranscriptVerificationException(
                "Exception validating decryption challenge transcript: " + e.getMessage(), e);
    }
}

From source file:org.cryptoworkshop.ximix.client.verify.ECShuffledTranscriptVerifier.java

License:Apache License

/**
 * Base Constructor.//w  w  w .  j a va  2  s. c  om
 *
 * @param pubKey the public key we are verifying against.
 * @param witnessTranscript transcript of witness values.
 * @param initialTranscript transcript of shuffle input.
 * @param finalTranscript transcript of shuffle output.
 * @throws IOException if any of the transcripts cannot be successfully parsed.
 */
public ECShuffledTranscriptVerifier(ECPublicKeyParameters pubKey, InputStream witnessTranscript,
        InputStream initialTranscript, InputStream finalTranscript) throws IOException {
    this.pubKey = pubKey;
    this.ecCurve = pubKey.getParameters().getCurve();

    try {
        //
        // we read the witnesses first as there is no need to load messages from the others if they
        // are not referenced here.
        //
        CMSSignedDataParser cmsParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(),
                witnessTranscript);

        this.witnessTranscript = new ASN1InputStream(cmsParser.getSignedContent().getContentStream());
        this.initialTranscript = initialTranscript;
        this.finalTranscript = finalTranscript;
    } catch (Exception e) {
        throw new IOException("Unable to parse transcripts: " + e.getMessage(), e);
    }
}

From source file:org.cryptoworkshop.ximix.client.verify.ECShuffledTranscriptVerifier.java

License:Apache License

/**
 * File based constructor - this will process the witnessTranscript in batches.
 *
 * @param pubKey the public key we are verifying against.
 * @param witnessTranscriptStream transcript of witness values.
 * @param initialTranscript transcript of shuffle input.
 * @param finalTranscript transcript of shuffle output.
 * @throws IOException if any of the transcripts cannot be successfully parsed.
 *//*from   w w w .j  a  v  a  2 s.c o m*/
public ECShuffledTranscriptVerifier(ECPublicKeyParameters pubKey, InputStream witnessTranscriptStream,
        File initialTranscript, File finalTranscript) throws IOException {
    this.pubKey = pubKey;
    this.ecCurve = pubKey.getParameters().getCurve();

    try {
        //
        // we read the witnesses first as there is no need to load messages from the others if they
        // are not referenced here.
        //
        CMSSignedDataParser cmsParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(),
                witnessTranscriptStream);

        this.witnessTranscript = new ASN1InputStream(cmsParser.getSignedContent().getContentStream());
        this.initialTranscript = initialTranscript;
        this.finalTranscript = finalTranscript;
    } catch (Exception e) {
        throw new IOException("Unable to parse transcripts: " + e.getMessage(), e);
    }
}