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

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

Introduction

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

Prototype

public boolean isValid() 

Source Link

Usage

From source file:com.github.horrorho.inflatabledonkey.crypto.ec.ECCurvePoint.java

License:Open Source License

public static Optional<ECCurvePoint> create(BigInteger x, BigInteger y, String curveName) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    ECPoint Q = x9ECParameters.getCurve().createPoint(x, y);

    if (!Q.isValid()) {
        logger.warn("-- create() - bad Q: {} curve: {}", Q, curveName);
        return Optional.empty();
    }/*  www .j a  va 2s . c o m*/

    ECCurvePoint point = new ECCurvePoint(Q, curveName, x9ECParameters);
    return Optional.of(point);
}

From source file:org.sufficientlysecure.keychain.securitytoken.SCP11bSecureMessaging.java

License:Open Source License

private static ECPublicKey newECDHPublicKey(final ECKeyFormat kf, byte[] data) throws InvalidKeySpecException,
        NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchProviderException {
    if (ecdhFactory == null) {
        ecdhFactory = KeyFactory.getInstance(SCP11B_KEY_AGREEMENT_KEY_TYPE, PROVIDER);
    }//from w  w w. j  ava  2s  .  com

    final X9ECParameters params = NISTNamedCurves.getByOID(kf.getCurveOID());
    if (params == null) {
        throw new InvalidParameterSpecException("unsupported curve");
    }

    final ECCurve curve = params.getCurve();
    final ECPoint p = curve.decodePoint(data);
    if (!p.isValid()) {
        throw new InvalidKeySpecException("invalid EC point");
    }

    final java.security.spec.ECPublicKeySpec pk = new java.security.spec.ECPublicKeySpec(
            new java.security.spec.ECPoint(p.getAffineXCoord().toBigInteger(),
                    p.getAffineYCoord().toBigInteger()),
            getAlgorithmParameterSpec(kf));

    return (ECPublicKey) (ecdhFactory.generatePublic(pk));
}

From source file:org.sufficientlysecure.keychain.securitytoken.SecurityTokenConnection.java

License:Open Source License

/**
 * Call DECIPHER command/*from w ww .ja v a 2  s .  com*/
 *
 * @param encryptedSessionKey the encoded session key
 * @param publicKey
 * @return the decoded session key
 */
public byte[] decryptSessionKey(@NonNull byte[] encryptedSessionKey, CanonicalizedPublicKey publicKey)
        throws IOException {
    final KeyFormat kf = mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT);

    if (!mPw1ValidatedForDecrypt) {
        verifyPinForOther();
    }

    byte[] data;
    byte[] dataLen;
    int pLen = 0;

    X9ECParameters x9Params;

    switch (kf.keyFormatType()) {
    case RSAKeyFormatType:
        data = Arrays.copyOfRange(encryptedSessionKey, 2, encryptedSessionKey.length);
        if (data[0] != 0) {
            data = Arrays.prepend(data, (byte) 0x00);
        }
        break;

    case ECKeyFormatType:
        pLen = ((((encryptedSessionKey[0] & 0xff) << 8) + (encryptedSessionKey[1] & 0xff)) + 7) / 8;
        data = new byte[pLen];

        System.arraycopy(encryptedSessionKey, 2, data, 0, pLen);

        final ECKeyFormat eckf = (ECKeyFormat) kf;
        x9Params = NISTNamedCurves.getByOID(eckf.getCurveOID());

        final ECPoint p = x9Params.getCurve().decodePoint(data);
        if (!p.isValid()) {
            throw new CardException("Invalid EC point!");
        }

        data = p.getEncoded(false);

        if (data.length < 128) {
            dataLen = new byte[] { (byte) data.length };
        } else {
            dataLen = new byte[] { (byte) 0x81, (byte) data.length };
        }
        data = Arrays.concatenate(Hex.decode("86"), dataLen, data);

        if (data.length < 128) {
            dataLen = new byte[] { (byte) data.length };
        } else {
            dataLen = new byte[] { (byte) 0x81, (byte) data.length };
        }
        data = Arrays.concatenate(Hex.decode("7F49"), dataLen, data);

        if (data.length < 128) {
            dataLen = new byte[] { (byte) data.length };
        } else {
            dataLen = new byte[] { (byte) 0x81, (byte) data.length };
        }
        data = Arrays.concatenate(Hex.decode("A6"), dataLen, data);
        break;

    default:
        throw new CardException("Unknown encryption key type!");
    }

    CommandApdu command = commandFactory.createDecipherCommand(data);
    ResponseApdu response = communicate(command);

    if (!response.isSuccess()) {
        throw new CardException("Deciphering with Security token failed on receive", response.getSw());
    }

    switch (mOpenPgpCapabilities.getFormatForKeyType(KeyType.ENCRYPT).keyFormatType()) {
    case RSAKeyFormatType:
        return response.getData();

    /* From 3.x OpenPGP card specification :
       In case of ECDH the card supports a partial decrypt only.
       With its own private key and the given public key the card calculates a shared secret
       in compliance with the Elliptic Curve Key Agreement Scheme from Diffie-Hellman.
       The shared secret is returned in the response, all other calculation for deciphering
       are done outside of the card.
            
       The shared secret obtained is a KEK (Key Encryption Key) that is used to wrap the
       session key.
            
       From rfc6637#section-13 :
       This document explicitly discourages the use of algorithms other than AES as a KEK algorithm.
       */
    case ECKeyFormatType:
        data = response.getData();

        final byte[] keyEnc = new byte[encryptedSessionKey[pLen + 2]];

        System.arraycopy(encryptedSessionKey, 2 + pLen + 1, keyEnc, 0, keyEnc.length);

        try {
            final MessageDigest kdf = MessageDigest
                    .getInstance(MessageDigestUtils.getDigestName(publicKey.getSecurityTokenHashAlgorithm()));

            kdf.update(new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 1 });
            kdf.update(data);
            kdf.update(publicKey.createUserKeyingMaterial(fingerprintCalculator));

            final byte[] kek = kdf.digest();
            final Cipher c = Cipher.getInstance("AESWrap");

            c.init(Cipher.UNWRAP_MODE,
                    new SecretKeySpec(kek, 0, publicKey.getSecurityTokenSymmetricKeySize() / 8, "AES"));

            final Key paddedSessionKey = c.unwrap(keyEnc, "Session", Cipher.SECRET_KEY);

            Arrays.fill(kek, (byte) 0);

            return PGPPad.unpadSessionData(paddedSessionKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {
            throw new CardException("Unknown digest/encryption algorithm!");
        } catch (NoSuchPaddingException e) {
            throw new CardException("Unknown padding algorithm!");
        } catch (PGPException e) {
            throw new CardException(e.getMessage());
        } catch (InvalidKeyException e) {
            throw new CardException("Invalid KEK!");
        }

    default:
        throw new CardException("Unknown encryption key type!");
    }
}