Example usage for org.bouncycastle.crypto.agreement ECDHBasicAgreement ECDHBasicAgreement

List of usage examples for org.bouncycastle.crypto.agreement ECDHBasicAgreement ECDHBasicAgreement

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.agreement ECDHBasicAgreement ECDHBasicAgreement.

Prototype

ECDHBasicAgreement

Source Link

Usage

From source file:ECIESTest.java

public TestResult perform() {
    SecureRandom random = new SecureRandom();
    ECCurve.Fp curve = new ECCurve.Fp(
            new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
            new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
            new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b

    ECDomainParameters params = new ECDomainParameters(curve,
            curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
            new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n

    ECKeyPairGenerator pGen = new ECKeyPairGenerator();
    ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(params, random);

    pGen.init(genParam);//from   ww  w  . ja  v  a2s  . c  om

    AsymmetricCipherKeyPair p1 = pGen.generateKeyPair();
    AsymmetricCipherKeyPair p2 = pGen.generateKeyPair();

    //
    // stream test
    //
    IESEngine i1 = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()),
            new HMac(new SHA1Digest()));
    IESEngine i2 = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()),
            new HMac(new SHA1Digest()));
    byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
    IESParameters p = new IESParameters(d, e, 64);

    i1.init(true, p1.getPrivate(), p2.getPublic(), p);
    i2.init(false, p2.getPrivate(), p1.getPublic(), p);

    byte[] message = Hex.decode("1234567890abcdef");

    try {
        byte[] out1 = i1.processBlock(message, 0, message.length);

        byte[] out2 = i2.processBlock(out1, 0, out1.length);

        if (!sameAs(out2, message)) {
            return new SimpleTestResult(false, this.getName() + ": stream cipher test failed");
        }

    } catch (Exception ex) {
        return new SimpleTestResult(false, this.getName() + ": stream cipher test exception " + ex.toString());
    }

    //
    // twofish with IV0 test
    //
    BufferedBlockCipher c1 = new PaddedBufferedBlockCipher(new CBCBlockCipher(new TwofishEngine()));
    BufferedBlockCipher c2 = new PaddedBufferedBlockCipher(new CBCBlockCipher(new TwofishEngine()));
    i1 = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()),
            new HMac(new SHA1Digest()), c1);
    i2 = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()),
            new HMac(new SHA1Digest()), c2);
    d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };
    p = new IESWithCipherParameters(d, e, 64, 128);

    i1.init(true, p1.getPrivate(), p2.getPublic(), p);
    i2.init(false, p2.getPrivate(), p1.getPublic(), p);

    message = Hex.decode("1234567890abcdef");

    try {
        byte[] out1 = i1.processBlock(message, 0, message.length);

        byte[] out2 = i2.processBlock(out1, 0, out1.length);

        if (!sameAs(out2, message)) {
            return new SimpleTestResult(false, this.getName() + ": twofish cipher test failed");
        }
    } catch (Exception ex) {
        return new SimpleTestResult(false, this.getName() + ": twofish cipher test exception " + ex.toString());
    }

    return new SimpleTestResult(true, this.getName() + ": Okay");
}

From source file:card.CardClient.java

License:Open Source License

/**
 * Get an attribute from the card//from  ww w  .jav  a 2 s.c  o 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.completetrsst.crypto.Crypto.java

License:Apache License

private static byte[] _cryptIES(byte[] input, Key recipient, boolean forEncryption)
        throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    IESCipher cipher = new IESCipher(new IESEngine(new ECDHBasicAgreement(),
            new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA256Digest()),
            new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()))));

    cipher.engineInit(forEncryption ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, recipient, new SecureRandom());
    return cipher.engineDoFinal(input, 0, input.length);
}

From source file:com.licel.jcardsim.crypto.KeyAgreementImpl.java

License:Apache License

public KeyAgreementImpl(byte algorithm) {
    this.algorithm = algorithm;
    switch (algorithm) {
    case ALG_EC_SVDP_DH:
        engine = new ECDHBasicAgreement();
        break;/* w ww . ja  v  a  2 s . co m*/
    case ALG_EC_SVDP_DHC:
        engine = new ECDHCBasicAgreement();
        break;
    default:
        CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM);
        break;
    }
    digestEngine = new SHA1Digest();
}

From source file:COSE.Recipient.java

private byte[] ECDH_GenerateSecret(OneKey key) throws CoseException {
    OneKey epk;//  w  w w. j  av a 2 s. c o  m

    if (senderKey != null) {
        epk = key;
        key = senderKey;
    } else {
        CBORObject cn;
        cn = findAttribute(HeaderKeys.ECDH_SPK);
        if (cn == null) {
            cn = findAttribute(HeaderKeys.ECDH_EPK);
        }
        if (cn == null)
            throw new CoseException("No second party EC key");
        epk = new OneKey(cn);
    }

    if (key.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2)
        throw new CoseException("Not an EC2 Key");
    if (epk.get(KeyKeys.KeyType.AsCBOR()) != KeyKeys.KeyType_EC2)
        throw new CoseException("Not an EC2 Key");
    if (epk.get(KeyKeys.EC2_Curve.AsCBOR()) != key.get(KeyKeys.EC2_Curve.AsCBOR()))
        throw new CoseException("Curves are not the same");

    X9ECParameters p = epk.GetCurve();
    ECDomainParameters parameters = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH());

    ECPoint pubPoint;

    CBORObject y = epk.get(KeyKeys.EC2_Y.AsCBOR());
    byte[] x = epk.get(KeyKeys.EC2_X.AsCBOR()).GetByteString();
    if (y.getType() == CBORType.Boolean) {
        byte[] X = epk.get(KeyKeys.EC2_X.AsCBOR()).GetByteString();
        byte[] rgb = new byte[X.length + 1];
        System.arraycopy(X, 0, rgb, 1, X.length);
        rgb[0] = (byte) (2 + (y.AsBoolean() ? 1 : 0));
        pubPoint = p.getCurve().decodePoint(rgb);
    } else {
        pubPoint = p.getCurve().createPoint(new BigInteger(1, x), new BigInteger(1, y.GetByteString()));
    }

    ECPublicKeyParameters pub = new ECPublicKeyParameters(pubPoint, parameters);
    ECPrivateKeyParameters priv = new ECPrivateKeyParameters(
            new BigInteger(1, key.get(KeyKeys.EC2_D.AsCBOR()).GetByteString()), parameters);
    BasicAgreement e1 = new ECDHBasicAgreement();
    e1.init(priv);

    BigInteger k1 = e1.calculateAgreement(pub);
    return BigIntegers.asUnsignedByteArray((p.getCurve().getFieldSize() + 7) / 8, k1);
}

From source file:me.grapebaba.hyperledger.fabric.Crypto.java

License:Apache License

public ByteString eciesDecrypt(PrivateKey recipientPrivateKey, ByteString cipherText) {
    BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) recipientPrivateKey;
    ECNamedCurveSpec ecNamedCurveSpec = (ECNamedCurveSpec) bcecPrivateKey.getParams();
    int level = SecurityLevel.from(ecNamedCurveSpec.getName()).size();

    //cipherText = ephemeralPubKeyBytes + encryptedTokBytes + macBytes
    //ephemeralPubKeyBytes = first ((384+7)/8)*2 + 1 bytes = first 97 bytes
    //hmac is sha3_384 = 48 bytes or sha3_256 = 32 bytes
    int ephemeralPubKeyLength = ((level + 7) / 8) * 2 + 1;
    int hmacLength = level >> 3;
    int cipherTextLength = cipherText.size();

    if (cipherTextLength <= ephemeralPubKeyLength + hmacLength)
        throw new RuntimeException(String.format("Illegal cipherText length: %d must be > %d", cipherTextLength,
                ephemeralPubKeyLength + hmacLength));

    ByteString ephemeralPubKey = cipherText.substring(0, ephemeralPubKeyLength);
    ByteString encryptedContent = cipherText.substring(ephemeralPubKeyLength, cipherTextLength - hmacLength);
    ByteString hmac = cipherText.substring(cipherTextLength - hmacLength);

    ECPrivateKeyParameters ecdhPrivateKeyParameters;
    try {/*from   www.j av a2s .c om*/
        ecdhPrivateKeyParameters = (ECPrivateKeyParameters) (PrivateKeyFactory
                .createKey(bcecPrivateKey.getEncoded()));
    } catch (IOException e) {
        logger.error("ECIES decrypt load private key exception", e);
        throw new RuntimeException(e);
    }
    ECDomainParameters ecDomainParameters = ecdhPrivateKeyParameters.getParameters();
    ECCurve ecCurve = ecDomainParameters.getCurve();
    ECPublicKeyParameters ecPublicKeyParameters = new ECPublicKeyParameters(
            ecCurve.decodePoint(ephemeralPubKey.toByteArray()), ecDomainParameters);
    BasicAgreement agree = new ECDHBasicAgreement();
    agree.init(ecdhPrivateKeyParameters);
    byte[] keyAgreement = agree.calculateAgreement(ecPublicKeyParameters).toByteArray();

    HKDFParameters hkdfParameters = new HKDFParameters(keyAgreement, null, null);
    HKDFBytesGenerator hkdfBytesGenerator = new HKDFBytesGenerator(digest);
    hkdfBytesGenerator.init(hkdfParameters);
    byte[] hkdfOutputBytes = new byte[AESKEY_LENGTH + HMACKEY_LENGTH];
    hkdfBytesGenerator.generateBytes(hkdfOutputBytes, 0, AESKEY_LENGTH + HMACKEY_LENGTH);
    ByteString hkdfOutput = ByteString.copyFrom(hkdfOutputBytes);
    ByteString aesKey = hkdfOutput.substring(0, AESKEY_LENGTH);
    ByteString hmacKey = hkdfOutput.substring(AESKEY_LENGTH, AESKEY_LENGTH + HMACKEY_LENGTH);
    HMac hMac = new HMac(digest);
    hMac.init(new KeyParameter(hmacKey.toByteArray()));
    hMac.update(encryptedContent.toByteArray(), 0, encryptedContent.size());
    byte[] recoveredHmac = new byte[hMac.getMacSize()];
    hMac.doFinal(recoveredHmac, 0);
    if (!MessageDigest.isEqual(hmac.toByteArray(), recoveredHmac)) {
        throw new RuntimeException("HMAC verify failed");
    }

    CFBBlockCipher aesCipher = new CFBBlockCipher(new AESEngine(), BLOCK_BIT_SIZE);
    ByteString iv = encryptedContent.substring(0, IV_LENGTH);
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(aesKey.toByteArray()), iv.toByteArray());
    aesCipher.init(false, ivAndKey);
    byte[] decryptedBytes = new byte[500];
    aesCipher.decryptBlock(encryptedContent.substring(IV_LENGTH).toByteArray(), 0, decryptedBytes, 0);
    return ByteString.copyFrom(decryptedBytes);
}

From source file:org.ethereum.crypto.CryptoTest.java

License:Open Source License

@Test // ECIES_AES128_SHA256 + No Ephemeral Key + IV(all zeroes)
public void test14() throws Throwable {

    AESEngine aesEngine = new AESEngine();

    IESEngine iesEngine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA256Digest()),
            new HMac(new SHA256Digest()), new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

    IESParameters p = new IESWithCipherParameters(d, e, 64, 128);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[16]);

    ECKeyPairGenerator eGen = new ECKeyPairGenerator();
    KeyGenerationParameters gParam = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());

    eGen.init(gParam);/*from   www.ja va 2 s  .co m*/

    AsymmetricCipherKeyPair p1 = eGen.generateKeyPair();
    AsymmetricCipherKeyPair p2 = eGen.generateKeyPair();

    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keygenParams);

    ECKeyPairGenerator gen = new ECKeyPairGenerator();
    gen.init(new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom()));

    iesEngine.init(true, p1.getPrivate(), p2.getPublic(), parametersWithIV);

    byte[] message = Hex.decode("010101");
    log.info("payload: {}", Hex.toHexString(message));

    byte[] cipher = iesEngine.processBlock(message, 0, message.length);
    log.info("cipher: {}", Hex.toHexString(cipher));

    IESEngine decryptorIES_Engine = new IESEngine(new ECDHBasicAgreement(),
            new KDF2BytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()),
            new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    decryptorIES_Engine.init(false, p2.getPrivate(), p1.getPublic(), parametersWithIV);

    byte[] orig = decryptorIES_Engine.processBlock(cipher, 0, cipher.length);

    log.info("orig: " + Hex.toHexString(orig));
}

From source file:org.ethereum.crypto.CryptoTest.java

License:Open Source License

@Test // ECIES_AES128_SHA256 + Ephemeral Key + IV(all zeroes)
public void test15() throws Throwable {

    byte[] privKey = Hex.decode("a4627abc2a3c25315bff732cb22bc128f203912dd2a840f31e66efb27a47d2b1");

    ECKey ecKey = ECKey.fromPrivate(privKey);

    ECPrivateKeyParameters ecPrivKey = new ECPrivateKeyParameters(ecKey.getPrivKey(), ECKey.CURVE);
    ECPublicKeyParameters ecPubKey = new ECPublicKeyParameters(ecKey.getPubKeyPoint(), ECKey.CURVE);

    AsymmetricCipherKeyPair myKey = new AsymmetricCipherKeyPair(ecPubKey, ecPrivKey);

    AESEngine aesEngine = new AESEngine();

    IESEngine iesEngine = new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA256Digest()),
            new HMac(new SHA256Digest()), new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    byte[] d = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    byte[] e = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 };

    IESParameters p = new IESWithCipherParameters(d, e, 64, 128);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[16]);

    ECKeyPairGenerator eGen = new ECKeyPairGenerator();
    KeyGenerationParameters gParam = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());

    eGen.init(gParam);//from ww w. j a  va 2s  .c o m

    ECKeyGenerationParameters keygenParams = new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom());
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.init(keygenParams);

    EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(generator, new KeyEncoder() {
        public byte[] getEncoded(AsymmetricKeyParameter keyParameter) {
            return ((ECPublicKeyParameters) keyParameter).getQ().getEncoded();
        }
    });

    ECKeyPairGenerator gen = new ECKeyPairGenerator();
    gen.init(new ECKeyGenerationParameters(ECKey.CURVE, new SecureRandom()));

    iesEngine.init(myKey.getPublic(), parametersWithIV, kGen);

    byte[] message = Hex.decode("010101");
    log.info("payload: {}", Hex.toHexString(message));

    byte[] cipher = iesEngine.processBlock(message, 0, message.length);
    log.info("cipher: {}", Hex.toHexString(cipher));

    IESEngine decryptorIES_Engine = new IESEngine(new ECDHBasicAgreement(),
            new KDF2BytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()),
            new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    decryptorIES_Engine.init(myKey.getPrivate(), parametersWithIV, new ECIESPublicKeyParser(ECKey.CURVE));

    byte[] orig = decryptorIES_Engine.processBlock(cipher, 0, cipher.length);

    log.info("orig: " + Hex.toHexString(orig));
}

From source file:org.ethereum.crypto.ECIESCoder.java

License:Open Source License

public static byte[] decrypt(ECPoint ephem, BigInteger prv, byte[] iv, byte[] cipher, byte[] macData)
        throws InvalidCipherTextException {
    AESEngine aesEngine = new AESEngine();

    EthereumIESEngine iesEngine = new EthereumIESEngine(new ECDHBasicAgreement(),
            new ConcatKDFBytesGenerator(new SHA256Digest()), new HMac(new SHA256Digest()), new SHA256Digest(),
            new BufferedBlockCipher(new SICBlockCipher(aesEngine)));

    byte[] d = new byte[] {};
    byte[] e = new byte[] {};

    IESParameters p = new IESWithCipherParameters(d, e, KEY_SIZE, KEY_SIZE);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, iv);

    iesEngine.init(false, new ECPrivateKeyParameters(prv, CURVE), new ECPublicKeyParameters(ephem, CURVE),
            parametersWithIV);//from   www .j  a v  a2 s . c o  m

    return iesEngine.processBlock(cipher, 0, cipher.length, macData);
}

From source file:org.ethereum.crypto.ECIESCoder.java

License:Open Source License

/**
 *  Encryption equivalent to the Crypto++ default ECIES<ECP> settings:
 *
 *  DL_KeyAgreementAlgorithm:        DL_KeyAgreementAlgorithm_DH<struct ECPPoint,struct EnumToType<enum CofactorMultiplicationOption,0> >
 *  DL_KeyDerivationAlgorithm:       DL_KeyDerivationAlgorithm_P1363<struct ECPPoint,0,class P1363_KDF2<class SHA1> >
 *  DL_SymmetricEncryptionAlgorithm: DL_EncryptionAlgorithm_Xor<class HMAC<class SHA1>,0>
 *  DL_PrivateKey:                   DL_Key<ECPPoint>
 *  DL_PrivateKey_EC<class ECP>//w ww.  ja  v  a  2  s .  c  om
 *
 *  Used for Whisper V3
 */
public static byte[] decryptSimple(BigInteger privKey, byte[] cipher)
        throws IOException, InvalidCipherTextException {
    EthereumIESEngine iesEngine = new EthereumIESEngine(new ECDHBasicAgreement(),
            new MGF1BytesGeneratorExt(new SHA1Digest(), 1), new HMac(new SHA1Digest()), new SHA1Digest(), null);

    IESParameters p = new IESParameters(null, null, KEY_SIZE);
    ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[0]);

    iesEngine.setHashMacKey(false);

    iesEngine.init(new ECPrivateKeyParameters(privKey, CURVE), parametersWithIV,
            new ECIESPublicKeyParser(ECKey.CURVE));

    return iesEngine.processBlock(cipher, 0, cipher.length);
}