Example usage for java.security KeyFactory generatePublic

List of usage examples for java.security KeyFactory generatePublic

Introduction

In this page you can find the example usage for java.security KeyFactory generatePublic.

Prototype

public final PublicKey generatePublic(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a public key object from the provided key specification (key material).

Usage

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureES512(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-521");
    BigInteger q = ((ECCurve.Fp) ecSpec.getCurve()).getQ();
    ECFieldElement xFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getX());
    ECFieldElement yFieldElement = new ECFieldElement.Fp(q, ecdsaPublicKey.getY());
    ECPoint pointQ = new ECPoint.Fp(ecSpec.getCurve(), xFieldElement, yFieldElement);
    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(pointQ, ecSpec);

    KeyFactory keyFactory = KeyFactory.getInstance("ECDSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Signature signature = Signature.getInstance("SHA512WITHECDSA", "BC");
    signature.initVerify(publicKey);//  w ww  . j a  v  a2 s . c  om
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureRS256(byte[] signingInput, byte[] sigBytes, RSAPublicKey rsaPublicKey)
        throws IllegalBlockSizeException, IOException, InvalidKeyException, NoSuchProviderException,
        InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException {
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
            rsaPublicKey.getPublicExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    byte[] decSig = cipher.doFinal(sigBytes);
    ASN1InputStream aIn = new ASN1InputStream(decSig);
    try {//from w ww . j a  v a 2s . c  o  m
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance("SHA-256", "BC");
        hash.update(signingInput);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureRS384(byte[] signingInput, byte[] sigBytes, RSAPublicKey rsaPublicKey)
        throws IllegalBlockSizeException, IOException, InvalidKeyException, NoSuchProviderException,
        InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException {
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
            rsaPublicKey.getPublicExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    byte[] decSig = cipher.doFinal(sigBytes);
    ASN1InputStream aIn = new ASN1InputStream(decSig);
    try {/*from   ww  w . ja v  a 2s  .c o m*/
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance("SHA-384", "BC");
        hash.update(signingInput);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}

From source file:org.xdi.oxauth.model.util.JwtUtil.java

public static boolean verifySignatureRS512(byte[] signingInput, byte[] sigBytes, RSAPublicKey rsaPublicKey)
        throws IllegalBlockSizeException, IOException, InvalidKeyException, NoSuchProviderException,
        InvalidKeySpecException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException {
    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
            rsaPublicKey.getPublicExponent());

    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

    Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    byte[] decSig = cipher.doFinal(sigBytes);
    ASN1InputStream aIn = new ASN1InputStream(decSig);
    try {/*from  ww w.j a  v a 2 s .  co m*/
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();

        MessageDigest hash = MessageDigest.getInstance("SHA-512", "BC");
        hash.update(signingInput);

        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        return MessageDigest.isEqual(hash.digest(), sigHash.getOctets());
    } finally {
        IOUtils.closeQuietly(aIn);
    }
}

From source file:cn.usually.common.pay.union.sdknew.SecureUtil.java

public static PublicKey getPublicKey(String modulus, String exponent) {
    try {/*from  w w  w.j a  v  a2s .  c  om*/
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
        return keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        throw new RuntimeException("getPublicKey error", e);
    }
}

From source file:acp.sdk.SecureUtil.java

public static PublicKey getPublicKey(String modulus, String exponent) {
    try {/*from w  ww  . j av a2 s.  c  o  m*/
        BigInteger b1 = new BigInteger(modulus);
        BigInteger b2 = new BigInteger(exponent);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
        return keyFactory.generatePublic(keySpec);
    } catch (Exception e) {
        throw new RuntimeException("getPublicKey error", e);
    }
}

From source file:com.amarinfingroup.net.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this uri.
 *
 * @param mUri either an instance URI (if previously saved) or a form URI
 * @param instanceMetadata/*  w w  w . ja  v a2s  . c om*/
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri,
        InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
        if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
            // chain back to the Form record...
            String[] selectionArgs = null;
            String selection = null;
            Cursor instanceCursor = null;
            try {
                instanceCursor = cr.query(mUri, null, null, null, null);
                if (instanceCursor.getCount() != 1) {
                    Log.e(t, "Not exactly one record for this instance!");
                    return null; // save unencrypted.
                }
                instanceCursor.moveToFirst();
                String jrFormId = instanceCursor
                        .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
                if (!instanceCursor.isNull(idxJrVersion)) {
                    selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
                } else {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
                }
            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form matches this jr_form_id");
                return null; // save unencrypted
            }
            formCursor.moveToFirst();
        } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
            formCursor = cr.query(mUri, null, null, null, null);
            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form!");
                return null; // save unencrypted.
            }
            formCursor.moveToFirst();
        }

        formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
        if (formId == null || formId.length() == 0) {
            Log.e(t, "No FormId specified???");
            return null;
        }
        int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
        int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
        formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
        String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null
                : formCursor.getString(idxBase64RsaPublicKey);

        if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
            return null; // this is legitimately not an encrypted form
        }

        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 8) {
            Log.e(t, "Phone does not support encryption.");
            return null; // save unencrypted
        }

        // this constructor will throw an exception if we are not
        // running on version 8 or above (if Base64 is not found).
        try {
            wrapper = new Base64Wrapper();
        } catch (ClassNotFoundException e) {
            Log.e(t, "Phone does not have Base64 class but API level is " + version);
            e.printStackTrace();
            return null; // save unencrypted
        }

        // OK -- Base64 decode (requires API Version 8 or higher)
        byte[] publicKey = wrapper.decode(base64RsaPublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            Log.e(t, "Phone does not support RSA encryption.");
            e.printStackTrace();
            return null;
        }
        try {
            pk = kf.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.e(t, "Invalid RSA public key.");
            return null;
        }
    } finally {
        if (formCursor != null) {
            formCursor.close();
        }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
        Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
        Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
        return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
}

From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this uri.
 *
 * @param mUri either an instance URI (if previously saved) or a form URI
 * @param instanceMetadata/*from w w w  . j a  v a  2s. c o  m*/
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri,
        FormController.InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
        if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
            // chain back to the Form record...
            String[] selectionArgs = null;
            String selection = null;
            Cursor instanceCursor = null;
            try {
                instanceCursor = cr.query(mUri, null, null, null, null);
                if (instanceCursor.getCount() != 1) {
                    Log.e(t, "Not exactly one record for this instance!");
                    return null; // save unencrypted.
                }
                instanceCursor.moveToFirst();
                String jrFormId = instanceCursor
                        .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
                if (!instanceCursor.isNull(idxJrVersion)) {
                    selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
                } else {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
                }
            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form matches this jr_form_id");
                return null; // save unencrypted
            }
            formCursor.moveToFirst();
        } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
            formCursor = cr.query(mUri, null, null, null, null);
            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form!");
                return null; // save unencrypted.
            }
            formCursor.moveToFirst();
        }

        formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
        if (formId == null || formId.length() == 0) {
            Log.e(t, "No FormId specified???");
            return null;
        }
        int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
        int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
        formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
        String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null
                : formCursor.getString(idxBase64RsaPublicKey);

        if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
            return null; // this is legitimately not an encrypted form
        }

        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 8) {
            Log.e(t, "Phone does not support encryption.");
            return null; // save unencrypted
        }

        // this constructor will throw an exception if we are not
        // running on version 8 or above (if Base64 is not found).
        try {
            wrapper = new Base64Wrapper();
        } catch (ClassNotFoundException e) {
            Log.e(t, "Phone does not have Base64 class but API level is " + version);
            e.printStackTrace();
            return null; // save unencrypted
        }

        // OK -- Base64 decode (requires API Version 8 or higher)
        byte[] publicKey = wrapper.decode(base64RsaPublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            Log.e(t, "Phone does not support RSA encryption.");
            e.printStackTrace();
            return null;
        }
        try {
            pk = kf.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.e(t, "Invalid RSA public key.");
            return null;
        }
    } finally {
        if (formCursor != null) {
            formCursor.close();
        }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
        Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
        Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
        return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
}

From source file:com.streamsets.lib.security.util.DataSignature.java

public PublicKey decodePublicKey(String encodedPublicKey) throws GeneralSecurityException {
    byte[] bytes = Base64.decodeBase64(encodedPublicKey);
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
    return keyFactory.generatePublic(pubKeySpec);
}

From source file:architecture.common.license.validator.CheckSignatureValidator.java

public void validate(License license) throws LicenseException {
    try {/*ww w.  j  a v  a 2  s.  c  o  m*/
        //   DSA ? .
        String publicKey = "308201b83082012c06072a8648ce3804013082011f02818100fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c70215009760508f15230bccb292b982a2eb840bf0581cf502818100f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d0782675159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a0381850002818100faf2d25b2866aa68501094d1097bebc95c6bcf1c58766f18b35fbf5e9d761cc5bf913447e374c21d279777859f9f043d1dc0d58b93a2081b56b4f5269a81b076907a3b11b01ec5cfde5dae4dfd7d26346e53e611235e714e69ec1bc141c77a8a28c4c799df570a4c3240e7f2fee19d6ed4caaa1b15b5da4a967ee82e3eb4d4ca";

        byte pub[] = Hex.decodeHex(publicKey.toCharArray());
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pub);

        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        Signature sig = Signature.getInstance("DSA");

        sig.initVerify(pubKey);
        // license.getSignature().getBytes("UTF-8");
        byte decoded[] = Hex.decodeHex(license.getSignature().toCharArray());

        log.debug("decoded sig: " + Hex.encodeHexString(decoded));

        log.info((new StringBuilder()).append("Validating license. License fingerprint: ")
                .append(license.getSignature()).toString());

        sig.update(license.getFingerprint());

        boolean verified = sig.verify(decoded);

        if (!verified)
            throw new LicenseException("License signature is invalid.");
    } catch (Exception e) {
        log.fatal(e.getMessage(), e);
        throw new LicenseException(e);
    }
}