Example usage for org.bouncycastle.math.ec ECPoint multiply

List of usage examples for org.bouncycastle.math.ec ECPoint multiply

Introduction

In this page you can find the example usage for org.bouncycastle.math.ec ECPoint multiply.

Prototype

public ECPoint multiply(BigInteger k) 

Source Link

Document

Multiplies this ECPoint by the given number.

Usage

From source file:ca.trustpoint.m2m.ecqv.EcqvProvider.java

License:Apache License

/**
 * Generate reconstruction data for an implicit certificate In the terminology of sec4,
 * ephemeralPublicKey is referenced as Ru
 *
 * @param identifyingInfo the identity portion of the implicit certificate
 * @param ephemeralPublicKey the requesters ephemeral public key
 * @param issuerPrivateKey the issuers private key
 *
 * @return reconstruction data associated with the implicit certificate
 *
 * @throws NoSuchAlgorithmException From Bouncy Castle
 * @throws InvalidAlgorithmParameterException From Bouncy Castle
 * @throws NoSuchProviderException From Bouncy Castle
 * @throws IOException/*from   www.  ja va 2  s  . c o  m*/
 */
public KeyReconstructionData genReconstructionData(byte[] identifyingInfo, PublicKey ephemeralPublicKey,
        PrivateKey issuerPrivateKey) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        NoSuchProviderException, IOException {
    // Reconstruction point, in point and byte format
    ECPoint p;
    byte[] reconstructionPoint;

    // CA's ephemeral key pair (k, kG)
    BCECPublicKey caEphemeralPublicKey;
    BCECPrivateKey caEphemeralPrivateKey;

    BigInteger n = curveParameters.getN(); // get the order of the curve group
    BigInteger r; // private key recovery data and CA ephemeral private key, respectively.
    BigInteger e; // Integer representation of H(Certu)
    BigInteger dCa = ((BCECPrivateKey) issuerPrivateKey).getD(); // Private key (point multiplier)
                                                                 // of the issuer.
    ECPoint infinity = curveParameters.getCurve().getInfinity(); // The identity point.

    do {
        // create ephemeral key pair (k, kG)
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
        keyGen.initialize(curveParameters, random);

        KeyPair caEphemeralKeyPair = keyGen.generateKeyPair();
        caEphemeralPrivateKey = (BCECPrivateKey) caEphemeralKeyPair.getPrivate();
        caEphemeralPublicKey = (BCECPublicKey) caEphemeralKeyPair.getPublic();

        // Compute Pu = Ru + kG
        // this is the reconstruction point
        p = ((BCECPublicKey) ephemeralPublicKey).getQ().add(caEphemeralPublicKey.getQ());

        reconstructionPoint = p.getEncoded(true);

        // Update the digest with the implicit certificate Certu
        for (byte b : identifyingInfo) {
            digest.update(b);
        }

        // Update digest with reconstruction point data.
        for (byte b : reconstructionPoint) {
            digest.update(b);
        }

        // hash the implicit certificate Certu and compute the integer e from H(Certu)
        e = calculateE(n, digest.digest()).mod(n);

        // from sec4 S3.4
    } while (p.multiply(e).add(curveParameters.getG().multiply(dCa)).equals(infinity));

    // compute r = ek + dCA (mod n)
    r = e.multiply(caEphemeralPrivateKey.getD()).add(dCa).mod(n);

    return new KeyReconstructionData(reconstructionPoint, integerToOctetString(r, n));
}

From source file:ca.trustpoint.m2m.ecqv.EcqvProvider.java

License:Apache License

/**
 * Reconstruct the public key from the implicit certificate and the CA's public key
 *
 * @param identifyingInfo the identity portion of the implicit certificate
 * @param reconstructionPoint the reconstruction point for the implicit certificate
 * @param qCa the CA's public key//from ww  w . j a  va 2 s.  c om
 *
 * @return the public key reconstructed from the implicit certificate
 *
 * @throws IOException errors in provided data
 */
public PublicKey reconstructPublicKey(byte[] identifyingInfo, byte[] reconstructionPoint, PublicKey qCa)
        throws IOException {
    // Reconstruct the point Pu from the reconstruction point
    ECPoint rPoint = ((BCECPublicKey) BouncyCastleProvider
            .getPublicKey(new SubjectPublicKeyInfo(algorithmId, reconstructionPoint))).getQ();
    BigInteger n = curveParameters.getN(); // curve point order
    ECPoint caPoint = ((BCECPublicKey) qCa).getQ(); // Massage caPublicKey bytes into ECPoint

    // Calculate H(Certu)
    for (byte b : identifyingInfo) {
        digest.update(b);
    }

    for (byte b : reconstructionPoint) {
        digest.update(b);
    }

    // Hash the implicit certificate Certu and compute the integer e from H(Certu)
    BigInteger e = calculateE(n, digest.digest()).mod(n);

    // compute the point Qu = ePu + Qca
    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(algorithmId,
            rPoint.multiply(e).add(caPoint).getEncoded(false));

    return BouncyCastleProvider.getPublicKey(publicKeyInfo);
}

From source file:card.CardClient.java

License:Open Source License

/**
 * Get an attribute from the card/*from   w  ww .j  a  v  a 2  s  .co m*/
 * 
 * @param i Index of the attribute.
 * @return Blinded public key, blinded attribute signature and the attribute
 */
public BigInteger[] getAttribute(byte id, ECPoint nonce) {
    BigInteger[] result = new BigInteger[3];

    int i = 0;
    while (i < attribute.length && attribute_id[i] != id)
        i++;

    if (i >= attribute.length || attribute_id[i] != id) {
        return null;
    }
    result[ATTRIBUTE] = attribute[i];

    // generate a blinding factor b
    blinder = (ECPrivateKey) keyGen.generateKeyPair().getPrivate();

    // blind public key, attribute signature and signed nonce
    try {
        ECDHBasicAgreement agreement = new ECDHBasicAgreement();
        agreement.init(new ECPrivateKeyParameters(blinder.getD(), ecDom));

        result[BLINDED_KEY] = agreement
                .calculateAgreement(new ECPublicKeyParameters(((ECPublicKey) keys.getPublic()).getQ(), ecDom));
        result[BLINDED_SIGNATURE] = agreement
                .calculateAgreement(new ECPublicKeyParameters(signature[i], ecDom));
        result[SIGNED_NONCE] = agreement.calculateAgreement(
                new ECPublicKeyParameters(nonce.multiply(((ECPrivateKey) keys.getPrivate()).getD()), ecDom));
    } catch (Exception e) {
        e.printStackTrace();
    }

    // return blinded public key, blinded attribute signature, blinded signed nonce, attribute
    return result;
}

From source file:com.example.quangadmin.smsencrypfinal.Khoigiaima.Makhoa.java

/**
 * @return the encryptext/* w  w w  . j a v  a  2  s.c  om*/
 */
public void Makhoa2(byte[] plaintext, ECPoint PublicKEYReceiver, BigInteger PrivateKEYSender) {
    BigInteger m;
    BigInteger r;
    BigInteger v;
    BigInteger nounce;
    ECPoint kG;
    BigInteger kIver;
    length1 = plaintext.length;
    byte[] c = new byte[1 + length1];
    int position = 0;
    c[position] = (byte) length1;
    position += 1;
    System.arraycopy(plaintext, 0, c, position, length1);

    // lay key AES K1 theo hash ban ro~ roi lay K1 ma hoa ban ro tao ra m
    BigInteger K1 = new BigInteger(256, new Random());
    ECPoint Pm = ecc.getG().multiply(K1);
    aes.Encryp(c, new SHA256().SHA256(Pm));
    m = new BigInteger(aes.getEncryptext());

    //Tao chu ky so tren m
    do {
        do {
            nounce = ecc.getNounce();
            kG = ecc.getG().multiply(nounce);
            r = kG.getX().toBigInteger().mod(ecc.getQ());
        } while (r.equals(BigInteger.ZERO));
        kIver = nounce.modInverse(ecc.getQ());
        v = kIver.multiply((m.add(PrivateKEYSender.multiply(r))));
    } while (v.equals(BigInteger.ZERO));

    // Ma hoa key AES K1 theo ECC P-384 xuat vao Pc
    ECPoint kPa = PublicKEYReceiver.multiply(nounce);

    // Chuan bi cho vao goi tao byte
    this.encryptext = aes.getEncryptext();
    this.Pc1 = kG;
    this.Pc2 = Pm.add(kPa);
    this.rr = r;
    this.vv = v;
}

From source file:com.example.quangadmin.smsencrypfinal.Khoigiaima.Makhoa.java

public void Giaima2(BigInteger r, BigInteger v, BigInteger m, ECPoint Pc1, ECPoint Pc2, ECPoint PublicKEYSender,
        BigInteger PrivateKEYReceiver) {
    BigInteger w = v.modInverse(ecc.getQ());
    BigInteger vvv;/*  ww  w  . j a  v a 2 s  .  c  o m*/
    BigInteger u1 = m.multiply(w).mod(ecc.getQ());
    BigInteger u2 = r.multiply(w).mod(ecc.getQ());

    ECPoint X = (ecc.getG().multiply(u1)).add(PublicKEYSender.multiply(u2));
    if (X == null) {
        this.verify = false;
    } else {
        vvv = X.getX().toBigInteger().mod(ecc.getQ());
        if (vvv.equals(r)) {
            this.verify = true;
        }
    }
    ECPoint Pm = Pc2.subtract(Pc1.multiply(PrivateKEYReceiver));
    aes.Decryp(m.toByteArray(), new SHA256().SHA256(Pm));
    this.plaintext = aes.getPlaintext();
}

From source file:com.fruitcat.bitcoin.BIP38.java

License:Apache License

/**
 * Generates a private key from an intermediate passphrase.
 *
 * @param intermediate// ww  w .j a  va 2s  . co m
 * @return
 * @throws GeneralSecurityException
 */
public static GeneratedKey encryptedKeyFromIntermediate(byte[] intermediate) throws GeneralSecurityException {

    byte flagByte = (0x51 == intermediate[7]) ? (byte) 4 : (byte) 0; //uncompressed
    byte[] ownerEntropy = Arrays.copyOfRange(intermediate, 8, 16);
    byte[] passPoint = Arrays.copyOfRange(intermediate, 16, 49);

    byte[] seedB = new byte[24];
    SecureRandom sr = new SecureRandom();
    sr.nextBytes(seedB);
    byte[] factorB = Utils.doubleHash(seedB, 0, 24);
    ECPoint p = CURVE.getCurve().decodePoint(passPoint);
    ECPoint pk = p.multiply(new BigInteger(1, factorB));
    byte[] generatedAddress = Utils.sha256ripe160(pk.getEncoded());
    String addStr = new Address(params, generatedAddress).toString();
    byte[] add = addStr.getBytes();
    byte[] addressHash = Arrays.copyOfRange(Utils.doubleHash(add, 0, add.length), 0, 4);

    byte[] salt = Utils.concat(addressHash, ownerEntropy);
    byte[] secondKey = SCrypt.scrypt(passPoint, salt, 1024, 1, 1, 64);
    byte[] derivedHalf1 = Arrays.copyOfRange(secondKey, 0, 32);
    byte[] derivedHalf2 = Arrays.copyOfRange(secondKey, 32, 64);

    byte[] m1 = new byte[16];
    byte[] m2 = new byte[16];
    for (int i = 0; i < 16; i++) {
        m1[i] = (byte) (seedB[i] ^ derivedHalf1[i]);

    }

    byte[] encryptedPart1 = Utils.AESEncrypt(m1, derivedHalf2);
    System.arraycopy(encryptedPart1, 8, m2, 0, 8);
    System.arraycopy(seedB, 16, m2, 8, 8);
    for (int i = 0; i < 16; i++) {
        m2[i] = (byte) (m2[i] ^ derivedHalf1[16 + i]);
    }

    byte[] encryptedPart2 = Utils.AESEncrypt(m2, derivedHalf2);
    byte[] header = { 0x01, 0x43, flagByte };

    byte[] encryptedPrivateKey = Utils.concat(header, addressHash, ownerEntropy,
            Arrays.copyOfRange(encryptedPart1, 0, 8), encryptedPart2);

    String key = Utils.base58Check(encryptedPrivateKey);
    String confirmationCode = confirm(flagByte, addressHash, ownerEntropy, factorB, derivedHalf1, derivedHalf2);
    return new GeneratedKey(key, addStr, confirmationCode);
}

From source file:com.fruitcat.bitcoin.BIP38.java

License:Apache License

/**
 * Generates the intermediate passphrase string as specified by BIP-0038.
 * If lot is a negative number, lot and sequence are not used.
 * @param passphrase/*  www  .  ja  v  a2s .  co  m*/
 * @param lot
 * @param sequence
 * @return the passphrase
 * @throws java.io.UnsupportedEncodingException
 * @throws java.security.GeneralSecurityException
 */
public static String intermediatePassphrase(String passphrase, int lot, int sequence)
        throws UnsupportedEncodingException, GeneralSecurityException {

    SecureRandom sr = new SecureRandom();
    byte[] ownerEntropy;
    byte[] ownerSalt;
    byte[] passPoint;
    byte[] preFactor;
    byte[] magicBytes = { (byte) 0x2c, (byte) (0xe9), (byte) 0xb3, (byte) 0xe1, (byte) 0xff, (byte) 0x39,
            (byte) 0xe2, (byte) 0x51 };
    byte[] passFactor;

    if (lot >= 0) {
        ownerSalt = new byte[4];
        sr.nextBytes(ownerSalt);
        ByteBuffer b = ByteBuffer.allocate(4);
        b.order(ByteOrder.BIG_ENDIAN); // redundant in Java because it's the default
        b.putInt(4096 * lot + sequence);
        byte[] ls = b.array();
        ownerEntropy = Utils.concat(ownerSalt, ls);
        preFactor = SCrypt.scrypt(passphrase.getBytes("UTF8"), ownerSalt, 16384, 8, 8, 32);
        byte[] tmp = Utils.concat(preFactor, ownerEntropy);
        passFactor = Utils.doubleHash(tmp, 0, 40);

    } else {
        magicBytes[7] = (byte) 0x53;
        ownerSalt = new byte[8];
        sr.nextBytes(ownerSalt);
        ownerEntropy = ownerSalt;
        passFactor = SCrypt.scrypt(passphrase.getBytes("UTF8"), ownerSalt, 16384, 8, 8, 32);
    }

    ECPoint g = CURVE.getG();
    ECPoint p = Utils.compressPoint(g.multiply(new BigInteger(1, passFactor)));
    passPoint = p.getEncoded();
    byte[] result = Utils.concat(magicBytes, ownerEntropy, passPoint);

    return Utils.base58Check(result);
}

From source file:com.fruitcat.bitcoin.BIP38.java

License:Apache License

/**
 * Decrypts a key encrypted with EC multiplication
 * @param passphrase//from  w  w w .  ja  va  2 s  . c om
 * @param encryptedKey
 * @return decrypted key
 * @throws UnsupportedEncodingException
 * @throws GeneralSecurityException
 */
public static String decryptEC(String passphrase, byte[] encryptedKey)
        throws UnsupportedEncodingException, GeneralSecurityException {

    byte flagByte = encryptedKey[2];
    byte[] passFactor;
    boolean hasLot = (flagByte & 4) == 4;
    byte[] ownerSalt = Arrays.copyOfRange(encryptedKey, 7, 15 - (flagByte & 4));
    if (!hasLot) {
        passFactor = SCrypt.scrypt(passphrase.getBytes("UTF8"), ownerSalt, 16384, 8, 8, 32);
    } else {
        byte[] preFactor = SCrypt.scrypt(passphrase.getBytes("UTF8"), ownerSalt, 16384, 8, 8, 32);
        byte[] ownerEntropy = Arrays.copyOfRange(encryptedKey, 7, 15);
        byte[] tmp = Utils.concat(preFactor, ownerEntropy);
        passFactor = Utils.doubleHash(tmp, 0, 40);
    }

    byte[] addressHash = Arrays.copyOfRange(encryptedKey, 3, 7);
    ECPoint g = CURVE.getG();
    ECPoint p = Utils.compressPoint(g.multiply(new BigInteger(1, passFactor)));
    byte[] passPoint = p.getEncoded();
    byte[] salt = new byte[12];
    byte[] encryptedPart2 = Arrays.copyOfRange(encryptedKey, 23, 39);
    System.arraycopy(addressHash, 0, salt, 0, 4);
    System.arraycopy(encryptedKey, 7, salt, 4, 8);

    byte[] secondKey = SCrypt.scrypt(passPoint, salt, 1024, 1, 1, 64);
    byte[] derivedHalf1 = Arrays.copyOfRange(secondKey, 0, 32);
    byte[] derivedHalf2 = Arrays.copyOfRange(secondKey, 32, 64);
    byte[] m2 = Utils.AESDecrypt(encryptedPart2, derivedHalf2);

    byte[] encryptedPart1 = new byte[16];
    System.arraycopy(encryptedKey, 15, encryptedPart1, 0, 8);

    byte[] seedB = new byte[24];

    for (int i = 0; i < 16; i++) {
        m2[i] = (byte) (m2[i] ^ derivedHalf1[16 + i]);
    }
    System.arraycopy(m2, 0, encryptedPart1, 8, 8);

    byte[] m1 = Utils.AESDecrypt(encryptedPart1, derivedHalf2);

    for (int i = 0; i < 16; i++) {
        seedB[i] = (byte) (m1[i] ^ derivedHalf1[i]);
    }

    System.arraycopy(m2, 8, seedB, 16, 8);
    byte[] factorB = Utils.doubleHash(seedB, 0, 24);
    BigInteger n = CURVE.getN();
    BigInteger pk = new BigInteger(1, passFactor).multiply(new BigInteger(1, factorB)).remainder(n);

    // Old way, deprecated
    // ECKey privKey = new ECKey(pk, null);
    ECKey privKey = ECKey.fromPrivate(pk);
    return privKey.getPrivateKeyEncoded(params).toString();
}

From source file:com.github.horrorho.inflatabledonkey.crypto.rfc6637.RFC6637.java

License:Open Source License

public byte[] unwrap(byte[] data, byte[] fingerprint, BigInteger d) {
    try {// ww w .j ava2  s  .  co  m
        logger.trace("-- unwrap() - data: 0x{} fingerprint: 0x{} d: 0x{}", Hex.toHexString(data),
                Hex.toHexString(fingerprint), d.toString(16));
        // TODO write verifcation/ exception handling code.
        ByteBuffer buffer = ByteBuffer.wrap(data);

        int wKeySize = (buffer.getShort() + 7) / 8;
        byte[] wKey = new byte[wKeySize];
        buffer.get(wKey);

        int wrappedSize = Byte.toUnsignedInt(buffer.get());
        byte[] wrapped = new byte[wrappedSize];
        buffer.get(wrapped);

        ECPoint Q = decodePoint(wKey);

        // ECDH assuming curve has a cofactor of 1
        ECPoint S = Q.multiply(d).normalize();

        byte[] hash = kdf.apply(S, fingerprint);

        byte[] derivedKey = Arrays.copyOf(hash, symAlgIDKeyLength);

        Wrapper wrapper = wrapperFactory.get();
        wrapper.init(false, new KeyParameter(derivedKey));
        byte[] unwrap = wrapper.unwrap(wrapped, 0, wrapped.length);

        // TODO sym alg
        byte[] finalize = finalize(unwrap);
        logger.trace("-- unwrap() - unwrapped: 0x{}", Hex.toHexString(finalize));
        return finalize;

    } catch (IOException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:com.google.bitcoin.core.ECKey.java

License:Apache License

/**
 * <p>Given the components of a signature and a selector value, recover and return the public key
 * that generated the signature according to the algorithm in SEC1v2 section 4.1.6.</p>
 *
 * <p>The recId is an index from 0 to 3 which indicates which of the 4 possible keys is the correct one. Because
 * the key recovery operation yields multiple potential keys, the correct key must either be stored alongside the
 * signature, or you must be willing to try each recId in turn until you find one that outputs the key you are
 * expecting.</p>//from w  w w  .ja  va2 s  .  c om
 *
 * <p>If this method returns null it means recovery was not possible and recId should be iterated.</p>
 *
 * <p>Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the
 * output is null OR a key that is not the one you expect, you try again with the next recId.</p>
 *
 * @param recId Which possible key to recover.
 * @param sig the R and S components of the signature, wrapped.
 * @param message Hash of the data that was signed.
 * @param compressed Whether or not the original pubkey was compressed.
 * @return An ECKey containing only the public part, or null if recovery wasn't possible.
 */
@Nullable
public static ECKey recoverFromSignature(int recId, ECDSASignature sig, Sha256Hash message,
        boolean compressed) {
    Preconditions.checkArgument(recId >= 0, "recId must be positive");
    Preconditions.checkArgument(sig.r.compareTo(BigInteger.ZERO) >= 0, "r must be positive");
    Preconditions.checkArgument(sig.s.compareTo(BigInteger.ZERO) >= 0, "s must be positive");
    Preconditions.checkNotNull(message);
    // 1.0 For j from 0 to h   (h == recId here and the loop is outside this function)
    //   1.1 Let x = r + jn
    BigInteger n = CURVE.getN(); // Curve order.
    BigInteger i = BigInteger.valueOf((long) recId / 2);
    BigInteger x = sig.r.add(i.multiply(n));
    //   1.2. Convert the integer x to an octet string X of length mlen using the conversion routine
    //        specified in Section 2.3.7, where mlen = (log2 p)/8 or mlen = m/8.
    //   1.3. Convert the octet string (16 set binary digits)||X to an elliptic curve point R using the
    //        conversion routine specified in Section 2.3.4. If this conversion routine outputs invalid?, then
    //        do another iteration of Step 1.
    //
    // More concisely, what these points mean is to use X as a compressed public key.
    ECCurve.Fp curve = (ECCurve.Fp) CURVE.getCurve();
    BigInteger prime = curve.getQ(); // Bouncy Castle is not consistent about the letter it uses for the prime.
    if (x.compareTo(prime) >= 0) {
        // Cannot have point co-ordinates larger than this as everything takes place modulo Q.
        return null;
    }
    // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities.
    // So it's encoded in the recId.
    ECPoint R = decompressKey(x, (recId & 1) == 1);
    //   1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility).
    if (!R.multiply(n).isInfinity())
        return null;
    //   1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
    BigInteger e = message.toBigInteger();
    //   1.6. For k from 1 to 2 do the following.   (loop is outside this function via iterating recId)
    //   1.6.1. Compute a candidate public key as:
    //               Q = mi(r) * (sR - eG)
    //
    // Where mi(x) is the modular multiplicative inverse. We transform this into the following:
    //               Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
    // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n). In the above equation
    // ** is point multiplication and + is point addition (the EC group operator).
    //
    // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive
    // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
    BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
    BigInteger rInv = sig.r.modInverse(n);
    BigInteger srInv = rInv.multiply(sig.s).mod(n);
    BigInteger eInvrInv = rInv.multiply(eInv).mod(n);
    ECPoint.Fp q = (ECPoint.Fp) ECAlgorithms.sumOfTwoMultiplies(CURVE.getG(), eInvrInv, R, srInv);
    if (compressed) {
        // We have to manually recompress the point as the compressed-ness gets lost when multiply() is used.
        q = new ECPoint.Fp(curve, q.getX(), q.getY(), true);
    }
    return new ECKey((byte[]) null, q.getEncoded());
}