Example usage for org.bouncycastle.asn1.nist NISTNamedCurves getByOID

List of usage examples for org.bouncycastle.asn1.nist NISTNamedCurves getByOID

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.nist NISTNamedCurves getByOID.

Prototype

public static X9ECParameters getByOID(ASN1ObjectIdentifier oid) 

Source Link

Document

return the X9ECParameters object for the named curve represented by the passed in object identifier.

Usage

From source file:net.jradius.client.auth.EAPTLSAuthenticator.java

License:Open Source License

/**
 * Create a private key parameter from the passed in PKCS8 PrivateKeyInfo object.
 * //from www  . ja  v  a 2  s .c  o  m
 * @param keyInfo the PrivateKeyInfo object containing the key material
 * @return a suitable private key parameter
 * @throws IOException on an error decoding the key
 */
public static AsymmetricKeyParameter createKey(PrivateKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithmId();

    if (algId.getObjectId().equals(PKCSObjectIdentifiers.rsaEncryption)) {
        RSAPrivateKeyStructure keyStructure = new RSAPrivateKeyStructure(
                (ASN1Sequence) keyInfo.getPrivateKey());

        return new RSAPrivateCrtKeyParameters(keyStructure.getModulus(), keyStructure.getPublicExponent(),
                keyStructure.getPrivateExponent(), keyStructure.getPrime1(), keyStructure.getPrime2(),
                keyStructure.getExponent1(), keyStructure.getExponent2(), keyStructure.getCoefficient());
    } else if (algId.getObjectId().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = new DHParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();

        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);

        return new DHPrivateKeyParameters(derX.getValue(), dhParams);
    } else if (algId.getObjectId().equals(OIWObjectIdentifiers.elGamalAlgorithm)) {
        ElGamalParameter params = new ElGamalParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();

        return new ElGamalPrivateKeyParameters(derX.getValue(),
                new ElGamalParameters(params.getP(), params.getG()));
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_dsa)) {
        DERInteger derX = (DERInteger) keyInfo.getPrivateKey();
        DEREncodable de = keyInfo.getAlgorithmId().getParameters();

        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.getDERObject());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }

        return new DSAPrivateKeyParameters(derX.getValue(), parameters);
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((DERObject) keyInfo.getAlgorithmId().getParameters());
        ECDomainParameters dParams = null;

        if (params.isNamedCurve()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) params.getParameters();
            X9ECParameters ecP = X962NamedCurves.getByOID(oid);

            if (ecP == null) {
                ecP = SECNamedCurves.getByOID(oid);

                if (ecP == null) {
                    ecP = NISTNamedCurves.getByOID(oid);

                    if (ecP == null) {
                        ecP = TeleTrusTNamedCurves.getByOID(oid);
                    }
                }
            }

            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        } else {
            X9ECParameters ecP = new X9ECParameters((ASN1Sequence) params.getParameters());
            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        }

        ECPrivateKeyStructure ec = new ECPrivateKeyStructure((ASN1Sequence) keyInfo.getPrivateKey());

        return new ECPrivateKeyParameters(ec.getKey(), dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}

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

License:Open Source License

public void addToSaveKeyringParcel(SaveKeyringParcel keyring, int keyFlags) {
    final X9ECParameters params = NISTNamedCurves.getByOID(mECCurveOID);
    final ECCurve curve = params.getCurve();

    SaveKeyringParcel.Algorithm algo = SaveKeyringParcel.Algorithm.ECDSA;
    if (((keyFlags & KeyFlags.ENCRYPT_COMMS) == KeyFlags.ENCRYPT_COMMS)
            || ((keyFlags & KeyFlags.ENCRYPT_STORAGE) == KeyFlags.ENCRYPT_STORAGE)) {
        algo = SaveKeyringParcel.Algorithm.ECDH;
    }/*from  www.j a  v a 2s.c  o m*/

    SaveKeyringParcel.Curve scurve;
    if (mECCurveOID.equals(NISTNamedCurves.getOID("P-256"))) {
        scurve = SaveKeyringParcel.Curve.NIST_P256;
    } else if (mECCurveOID.equals(NISTNamedCurves.getOID("P-384"))) {
        scurve = SaveKeyringParcel.Curve.NIST_P384;
    } else if (mECCurveOID.equals(NISTNamedCurves.getOID("P-521"))) {
        scurve = SaveKeyringParcel.Curve.NIST_P521;
    } else {
        throw new IllegalArgumentException("Unsupported curve " + mECCurveOID);
    }

    keyring.mAddSubKeys.add(new SaveKeyringParcel.SubkeyAdd(algo, curve.getFieldSize(), scurve, keyFlags, 0L));
}

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 www  .j av  a2  s.  c  om

    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  w  w.j av  a 2s .co  m
 *
 * @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!");
    }
}