Example usage for org.bouncycastle.crypto.agreement ECDHCBasicAgreement calculateAgreement

List of usage examples for org.bouncycastle.crypto.agreement ECDHCBasicAgreement calculateAgreement

Introduction

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

Prototype

public BigInteger calculateAgreement(CipherParameters pubKey) 

Source Link

Usage

From source file:com.cryptolib.CryptoObject.java

License:Open Source License

/**
* Performs ECDH//w ww. j  a  va2s.  c om
*/
public void createSharedEncKey(ECPublicKey key) throws CryptoSocketException {
    try {
        X9ECParameters ecP = CustomNamedCurves.getByName(curve);
        ECDomainParameters ecdp = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH());
        ECPublicKeyParameters ecpkp = new ECPublicKeyParameters(key.getQ(), ecdp);
        BCECPrivateKey sk = (BCECPrivateKey) this.encKeypair.getPrivate();
        ECPrivateKeyParameters ecskp = new ECPrivateKeyParameters(sk.getD(), ecdp);
        ECDHCBasicAgreement ba = new ECDHCBasicAgreement();
        ba.init(ecskp);
        byte[] byteSharedSecret = ba.calculateAgreement(ecpkp).toByteArray();
        byte[] byteSharedSecretSecond = new byte[byteSharedSecret.length / 2];
        byte[] byteSharedSecretFirst = new byte[byteSharedSecret.length / 2];
        System.arraycopy(byteSharedSecret, 0, byteSharedSecretSecond, 0, byteSharedSecretSecond.length);
        System.arraycopy(byteSharedSecret, byteSharedSecretSecond.length, byteSharedSecretFirst, 0,
                byteSharedSecretFirst.length);
        this.sharedSecretFirst = new SecretKeySpec(byteSharedSecretFirst, "AES");
        this.sharedSecretSecond = new SecretKeySpec(byteSharedSecretSecond, "AES");
        this.has_symmetric_key = true;
        this.enc = Cipher.getInstance("AES/GCM/NoPadding");
        this.dec = Cipher.getInstance("AES/GCM/NoPadding");
    } catch (IllegalStateException is) {
        throw new CryptoSocketException("unable to create shared encryption key, wrong state!");
    } catch (NoSuchAlgorithmException nsa) {
        throw new CryptoSocketException("Encryption algorithm not found!");
    } catch (NoSuchPaddingException nsp) {
        throw new CryptoSocketException("Invalid padding algorithm!");
    }
}