Search in sources :

Example 16 with ECParameterSpec

use of org.bouncycastle.jce.spec.ECParameterSpec in project openremote by openremote.

the class ProvisioningPublicKeyState method generateSharedECDHSecret.

private void generateSharedECDHSecret(final byte[] provisioneePublicKeyXYPDU) {
    if (provisioneePublicKeyXYPDU.length != 66) {
        throw new IllegalArgumentException("Invalid Provisionee Public Key PDU," + " length of the Provisionee public key must be 66 bytes, but was " + provisioneePublicKeyXYPDU.length);
    }
    final ByteBuffer buffer = ByteBuffer.allocate(provisioneePublicKeyXYPDU.length - 2);
    buffer.put(provisioneePublicKeyXYPDU, 2, buffer.limit());
    final byte[] xy = mTempProvisioneeXY = buffer.array();
    mUnprovisionedMeshNode.setProvisioneePublicKeyXY(xy);
    final byte[] xComponent = new byte[32];
    System.arraycopy(xy, 0, xComponent, 0, xComponent.length);
    final byte[] yComponent = new byte[32];
    System.arraycopy(xy, 32, yComponent, 0, xComponent.length);
    final byte[] provisioneeX = convertToLittleEndian(xComponent, ByteOrder.LITTLE_ENDIAN);
    LOG.info("Provsionee X: " + MeshParserUtils.bytesToHex(provisioneeX, false));
    final byte[] provisioneeY = convertToLittleEndian(yComponent, ByteOrder.LITTLE_ENDIAN);
    LOG.info("Provsionee Y: " + MeshParserUtils.bytesToHex(provisioneeY, false));
    final BigInteger x = BigIntegers.fromUnsignedByteArray(xy, 0, 32);
    final BigInteger y = BigIntegers.fromUnsignedByteArray(xy, 32, 32);
    final ECParameterSpec ecParameters = ECNamedCurveTable.getParameterSpec("secp256r1");
    ECCurve curve = ecParameters.getCurve();
    ECPoint ecPoint = curve.createPoint(x, y);
    ECPublicKeySpec keySpec = new ECPublicKeySpec(ecPoint, ecParameters);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("ECDH", "SC");
        ECPublicKey publicKey = (ECPublicKey) keyFactory.generatePublic(keySpec);
        KeyAgreement a = KeyAgreement.getInstance("ECDH", "SC");
        a.init(mProvisionerPrivaetKey);
        a.doPhase(publicKey, true);
        final byte[] sharedECDHSecret = a.generateSecret();
        mUnprovisionedMeshNode.setSharedECDHSecret(sharedECDHSecret);
        LOG.info("ECDH Secret: " + MeshParserUtils.bytesToHex(sharedECDHSecret, false));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ECPoint(org.bouncycastle.math.ec.ECPoint) InvalidKeyException(java.security.InvalidKeyException) ByteBuffer(java.nio.ByteBuffer) ECPublicKeySpec(org.bouncycastle.jce.spec.ECPublicKeySpec) ECPublicKey(org.bouncycastle.jce.interfaces.ECPublicKey) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) ECCurve(org.bouncycastle.math.ec.ECCurve) BigInteger(java.math.BigInteger) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyAgreement(javax.crypto.KeyAgreement) NoSuchProviderException(java.security.NoSuchProviderException) KeyFactory(java.security.KeyFactory)

Example 17 with ECParameterSpec

use of org.bouncycastle.jce.spec.ECParameterSpec in project athenz by yahoo.

the class Crypto method extractPublicKey.

public static PublicKey extractPublicKey(PrivateKey privateKey) throws CryptoException {
    // we only support RSA and ECDSA private keys
    PublicKey publicKey;
    switch(privateKey.getAlgorithm()) {
        case RSA:
            try {
                KeyFactory kf = KeyFactory.getInstance(getRSAAlgo(), getKeyFactoryProvider());
                RSAPrivateCrtKey rsaCrtKey = (RSAPrivateCrtKey) privateKey;
                RSAPublicKeySpec keySpec = new RSAPublicKeySpec(rsaCrtKey.getModulus(), rsaCrtKey.getPublicExponent());
                publicKey = kf.generatePublic(keySpec);
            } catch (NoSuchProviderException ex) {
                LOG.error("extractPublicKey: RSA - Caught NoSuchProviderException exception: {}", ex.getMessage());
                throw new CryptoException(ex);
            } catch (NoSuchAlgorithmException ex) {
                LOG.error("extractPublicKey: RSA - Caught NoSuchAlgorithmException exception: {}", ex.getMessage());
                throw new CryptoException(ex);
            // /CLOVER:OFF
            } catch (InvalidKeySpecException ex) {
                LOG.error("extractPublicKey: RSA - Caught InvalidKeySpecException exception: {}", ex.getMessage());
                throw new CryptoException(ex);
            }
            // /CLOVER:ON
            break;
        case ECDSA:
            try {
                KeyFactory kf = KeyFactory.getInstance(getECDSAAlgo(), getKeyFactoryProvider());
                BCECPrivateKey ecPrivKey = (BCECPrivateKey) privateKey;
                ECMultiplier ecMultiplier = new FixedPointCombMultiplier();
                ECParameterSpec ecParamSpec = ecPrivKey.getParameters();
                ECPoint ecPointQ = ecMultiplier.multiply(ecParamSpec.getG(), ecPrivKey.getD());
                ECPublicKeySpec keySpec = new ECPublicKeySpec(ecPointQ, ecParamSpec);
                publicKey = kf.generatePublic(keySpec);
            } catch (NoSuchProviderException ex) {
                LOG.error("extractPublicKey: ECDSA - Caught NoSuchProviderException exception: {}", ex.getMessage());
                throw new CryptoException(ex);
            } catch (NoSuchAlgorithmException ex) {
                LOG.error("extractPublicKey: ECDSA - Caught NoSuchAlgorithmException exception: {}", ex.getMessage());
                throw new CryptoException(ex);
            // /CLOVER:OFF
            } catch (InvalidKeySpecException ex) {
                LOG.error("extractPublicKey: ECDSA - Caught InvalidKeySpecException exception: {}", ex.getMessage());
                throw new CryptoException(ex);
            }
            // /CLOVER:ON
            break;
        default:
            String msg = "Unsupported Key Algorithm: " + privateKey.getAlgorithm();
            LOG.error("extractPublicKey: {}", msg);
            throw new CryptoException(msg);
    }
    return publicKey;
}
Also used : RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey) BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) ECMultiplier(org.bouncycastle.math.ec.ECMultiplier) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) ECPoint(org.bouncycastle.math.ec.ECPoint) ECPublicKeySpec(org.bouncycastle.jce.spec.ECPublicKeySpec) BCECPrivateKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey) FixedPointCombMultiplier(org.bouncycastle.math.ec.FixedPointCombMultiplier) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Example 18 with ECParameterSpec

use of org.bouncycastle.jce.spec.ECParameterSpec in project incubator-pulsar by apache.

the class MessageCrypto method loadPublicKey.

private PublicKey loadPublicKey(byte[] keyBytes) throws Exception {
    Reader keyReader = new StringReader(new String(keyBytes));
    PublicKey publicKey = null;
    try (org.bouncycastle.openssl.PEMParser pemReader = new org.bouncycastle.openssl.PEMParser(keyReader)) {
        Object pemObj = pemReader.readObject();
        JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        SubjectPublicKeyInfo keyInfo = null;
        X9ECParameters ecParam = null;
        if (pemObj instanceof ASN1ObjectIdentifier) {
            // make sure this is EC Parameter we're handling. In which case
            // we'll store it and read the next object which should be our
            // EC Public Key
            ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
            ecParam = ECNamedCurveTable.getByOID(ecOID);
            if (ecParam == null) {
                throw new PEMException("Unable to find EC Parameter for the given curve oid: " + ((ASN1ObjectIdentifier) pemObj).getId());
            }
            pemObj = pemReader.readObject();
        } else if (pemObj instanceof X9ECParameters) {
            ecParam = (X9ECParameters) pemObj;
            pemObj = pemReader.readObject();
        }
        if (pemObj instanceof org.bouncycastle.cert.X509CertificateHolder) {
            keyInfo = ((org.bouncycastle.cert.X509CertificateHolder) pemObj).getSubjectPublicKeyInfo();
        } else {
            keyInfo = (SubjectPublicKeyInfo) pemObj;
        }
        publicKey = pemConverter.getPublicKey(keyInfo);
        if (ecParam != null && ECDSA.equals(publicKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(), ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BouncyCastleProvider.PROVIDER_NAME);
            ECPublicKeySpec keySpec = new ECPublicKeySpec(((BCECPublicKey) publicKey).getQ(), ecSpec);
            publicKey = (PublicKey) keyFactory.generatePublic(keySpec);
        }
    } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException e) {
        throw new Exception(e);
    }
    return publicKey;
}
Also used : X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) Reader(java.io.Reader) CryptoKeyReader(org.apache.pulsar.client.api.CryptoKeyReader) StringReader(java.io.StringReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) ByteString(com.google.protobuf.ByteString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) ECPublicKeySpec(org.bouncycastle.jce.spec.ECPublicKeySpec) PEMParser(org.bouncycastle.openssl.PEMParser) StringReader(java.io.StringReader) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory) BCECPublicKey(org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey) PublicKey(java.security.PublicKey) PEMParser(org.bouncycastle.openssl.PEMParser) IOException(java.io.IOException) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) CryptoException(org.apache.pulsar.client.api.PulsarClientException.CryptoException) PEMException(org.bouncycastle.openssl.PEMException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) PEMException(org.bouncycastle.openssl.PEMException) NoSuchProviderException(java.security.NoSuchProviderException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 19 with ECParameterSpec

use of org.bouncycastle.jce.spec.ECParameterSpec in project oxAuth by GluuFederation.

the class ECDSASigner method validateSignature.

@Override
public boolean validateSignature(String signingInput, String signature) throws SignatureException {
    if (getSignatureAlgorithm() == null) {
        throw new SignatureException("The signature algorithm is null");
    }
    if (ecdsaPublicKey == null) {
        throw new SignatureException("The ECDSA public key is null");
    }
    if (signingInput == null) {
        throw new SignatureException("The signing input is null");
    }
    String algorithm;
    String curve;
    switch(getSignatureAlgorithm()) {
        case ES256:
            algorithm = "SHA256WITHECDSA";
            curve = "P-256";
            break;
        case ES384:
            algorithm = "SHA384WITHECDSA";
            curve = "P-384";
            break;
        case ES512:
            algorithm = "SHA512WITHECDSA";
            curve = "P-521";
            break;
        default:
            throw new SignatureException("Unsupported signature algorithm");
    }
    try {
        byte[] sigBytes = Base64Util.base64urldecode(signature);
        if (AlgorithmFamily.EC.equals(getSignatureAlgorithm().getFamily())) {
            sigBytes = ECDSA.transcodeSignatureToDER(sigBytes);
        }
        byte[] sigInBytes = signingInput.getBytes(Util.UTF8_STRING_ENCODING);
        ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(curve);
        ECPoint pointQ = ecSpec.getCurve().createPoint(ecdsaPublicKey.getX(), ecdsaPublicKey.getY());
        ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(pointQ, ecSpec);
        KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        Signature sig = Signature.getInstance(algorithm, "BC");
        sig.initVerify(publicKey);
        sig.update(sigInBytes);
        return sig.verify(sigBytes);
    } catch (InvalidKeySpecException e) {
        throw new SignatureException(e);
    } catch (InvalidKeyException e) {
        throw new SignatureException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException(e);
    } catch (NoSuchProviderException e) {
        throw new SignatureException(e);
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException(e);
    } catch (Exception e) {
        throw new SignatureException(e);
    }
}
Also used : ECDSAPublicKey(org.gluu.oxauth.model.crypto.signature.ECDSAPublicKey) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ECPoint(org.bouncycastle.math.ec.ECPoint) ECPublicKeySpec(org.bouncycastle.jce.spec.ECPublicKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException)

Example 20 with ECParameterSpec

use of org.bouncycastle.jce.spec.ECParameterSpec in project oxAuth by GluuFederation.

the class SHA256withECDSASignatureVerification method decodePublicKey.

@Override
public PublicKey decodePublicKey(byte[] encodedPublicKey) throws SignatureException {
    X9ECParameters curve = SECNamedCurves.getByName("secp256r1");
    ECPoint point = curve.getCurve().decodePoint(encodedPublicKey);
    try {
        return KeyFactory.getInstance("ECDSA").generatePublic(new ECPublicKeySpec(point, new ECParameterSpec(curve.getCurve(), curve.getG(), curve.getN(), curve.getH())));
    } catch (GeneralSecurityException ex) {
        throw new SignatureException(ex);
    }
}
Also used : X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) ECParameterSpec(org.bouncycastle.jce.spec.ECParameterSpec) GeneralSecurityException(java.security.GeneralSecurityException) SignatureException(org.gluu.oxauth.model.exception.SignatureException) ECPoint(org.bouncycastle.math.ec.ECPoint) ECPublicKeySpec(org.bouncycastle.jce.spec.ECPublicKeySpec)

Aggregations

ECParameterSpec (org.bouncycastle.jce.spec.ECParameterSpec)22 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)12 ECPublicKeySpec (org.bouncycastle.jce.spec.ECPublicKeySpec)12 ECPoint (org.bouncycastle.math.ec.ECPoint)10 InvalidKeyException (java.security.InvalidKeyException)7 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 KeyFactory (java.security.KeyFactory)6 X9ECParameters (org.bouncycastle.asn1.x9.X9ECParameters)6 BigInteger (java.math.BigInteger)5 ECDomainParameters (org.bouncycastle.crypto.params.ECDomainParameters)5 ECPrivateKeySpec (org.bouncycastle.jce.spec.ECPrivateKeySpec)5 BCECPublicKey (org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 NoSuchProviderException (java.security.NoSuchProviderException)3 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)3 ECCurve (org.bouncycastle.math.ec.ECCurve)3 PEMException (org.bouncycastle.openssl.PEMException)3 PEMParser (org.bouncycastle.openssl.PEMParser)3 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)3 ByteString (com.google.protobuf.ByteString)2