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:jef.tools.security.EncrypterUtil.java

/**
 * x509/*from  ww w  . j av a  2s.  c om*/
 * 
 * @param f
 * @param algom
 *            ? getSupportedAlgorithmName (AlgorithmType.KeyFactory)
 * @param isPublic
 *            true?false??
 * @return
 */
public static Key loadX509Key(File f, String algom, boolean isPublic) {
    try {
        byte[] keyData = IOUtils.toByteArray(f);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyData);
        KeyFactory keyFactory = KeyFactory.getInstance(algom);
        Key result = (isPublic) ? keyFactory.generatePublic(keySpec) : keyFactory.generatePrivate(keySpec);
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * PKCS8//from w  w w  .j  a va2  s  .  c o m
 * 
 * @param f
 * @param algom
 *            
 * @param isPublic
 *            true?false??
 * @return
 */
public static Key loadPKCS8Key(File f, String algom, boolean isPublic) {
    try {
        byte[] keyData = IOUtils.toByteArray(f);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyData);
        KeyFactory keyFactory = KeyFactory.getInstance(algom);
        Key result = (isPublic) ? keyFactory.generatePublic(keySpec) : keyFactory.generatePrivate(keySpec);
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.trsst.Common.java

/**
 * Converts a X509-encoded EC key to a PublicKey.
 *///from  w ww  . jav a 2 s  .  c o m
public static PublicKey toPublicKeyFromX509(String stored) throws GeneralSecurityException {
    KeyFactory factory = KeyFactory.getInstance("EC");
    byte[] data = Base64.decodeBase64(stored);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    return factory.generatePublic(spec);

}

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Retrieves a public key stored in a local file
 * <p>/* w ww  .ja  va  2 s.  c o  m*/
 * 
 * @param pubPath path to the public key on the local filesystem
 * @return the key encapsulated in a regular JCE container
 * @throws KeyException the key could not be retrieved or is malformed
 */
public static PublicKey getPublicKey(String pubPath) throws KeyException {
    byte[] bytes;
    File f = new File(pubPath);
    FileInputStream fin;

    String algo = "", tmp = "";

    // recover public key bytes
    try {
        fin = new FileInputStream(f);
        DataInputStream in = new DataInputStream(fin);
        int read, tot = 0;
        while ((read = in.read()) != '\n') {
            algo += (char) read;
            tot++;
        }
        tot++;
        while ((read = in.read()) != '\n') {
            tmp += (char) read;
            tot++;
        }
        tot++;

        bytes = new byte[(int) f.length() - tot];
        in.readFully(bytes);
        in.close();
    } catch (Exception e) {
        throw new KeyException("Could not retrieve public key from " + pubPath, e);
    }

    // reconstruct public key
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytes);
    PublicKey pubKey;
    KeyFactory keyFactory;

    try {
        keyFactory = KeyFactory.getInstance(algo);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyException("Cannot initialize key factory", e);
    }

    try {
        pubKey = keyFactory.generatePublic(pubKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new KeyException("Cannot re-generate public key", e);
    }

    return pubKey;
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static String encrypt(String message, String encodedKey) {
    try {/*from   w w  w  . ja v a2s.co  m*/

        // read private key
        if (StringUtils.isBlank(encodedKey)) {
            throw new SecurityException(
                    "Activation key was not found. Please make sure your instance is correctly configured.");
        }
        byte[] binaryKey = hexToByteArray(encodedKey);

        // create RSA public key cipher
        Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
        try {
            // create private key
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PrivateKey pk = kf.generatePrivate(privateKeySpec);

            pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        } catch (InvalidKeySpecException e) {
            // encrypting with public key?
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PublicKey pk = kf.generatePublic(publicKeySpec);

            pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        }

        // encrypt
        byte[] bytes = message.getBytes("UTF-8");
        // split bit message in chunks
        int start = 0;
        StringBuilder chaos = new StringBuilder();
        while (start < bytes.length) {
            byte[] tmp = new byte[Math.min(bytes.length - start, binaryKey.length / 8)];
            System.arraycopy(bytes, start, tmp, 0, tmp.length);
            start += tmp.length;
            byte[] encrypted = pkCipher.doFinal(tmp);
            chaos.append(byteArrayToHex(encrypted));
            chaos.append(";");
        }
        chaos.setLength(chaos.length() - 1);

        return chaos.toString();

    } catch (IOException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException(
                "Failed to find encryption provider. Please use Java version with cryptography support.", e);
    } catch (IllegalBlockSizeException e) {
        throw new SecurityException(
                "Failed to encrypt string. Please use Java version with cryptography support.", e);
    } catch (BadPaddingException e) {
        throw new SecurityException(
                "Failed to encrypt string. Please use Java version with cryptography support.", e);
    }
}

From source file:org.opendatakit.survey.android.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this row.
 * /*w  w w.  j  a v a2s .  com*/
 * @param appName
 * @param tableId
 * @param xmlBase64RsaPublicKey
 * @param instanceId
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(String appName, String tableId,
        String xmlBase64RsaPublicKey, String instanceId) {

    // fetch the form information
    String base64RsaPublicKey = xmlBase64RsaPublicKey;
    PublicKey pk;
    Base64Wrapper wrapper;

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

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

    int version = android.os.Build.VERSION.SDK_INT;
    if (version < 8) {
        WebLogger.getLogger(appName).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) {
        WebLogger.getLogger(appName).e(t, "Phone does not have Base64 class but API level is " + version);
        WebLogger.getLogger(appName).printStackTrace(e);
        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) {
        WebLogger.getLogger(appName).e(t, "Phone does not support RSA encryption.");
        WebLogger.getLogger(appName).printStackTrace(e);
        return null;
    }
    try {
        pk = kf.generatePublic(publicKeySpec);
    } catch (InvalidKeySpecException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t, "Invalid RSA public key.");
        return null;
    }
    return new EncryptedFormInformation(appName, tableId, xmlBase64RsaPublicKey, instanceId, pk, wrapper);
}

From source file:nl.knmi.adaguc.services.oauth2.OAuth2Handler.java

/**
 * RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S) using SHA-256
 * /*  w ww . jav a2  s . c om*/
 * @param modulus_n
 * @param exponent_e
 * @param signinInput_M
 * @param signature_S
 * @return
 * @throws SignatureException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
static boolean RSASSA_PKCS1_V1_5_VERIFY(String modulus_n, String exponent_e, String signinInput_M,
        String signature_S)
        throws SignatureException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
    Debug.println("Starting verification");
    /* RSA SHA-256 RSASSA-PKCS1-V1_5-VERIFY */
    // Modulus (n from https://www.googleapis.com/oauth2/v2/certs)
    String n = modulus_n;
    // Exponent (e from https://www.googleapis.com/oauth2/v2/certs)
    String e = exponent_e;
    // The JWT Signing Input (JWT Header and JWT Payload concatenated with
    // ".")
    byte[] M = signinInput_M.getBytes();
    // Signature (JWT Crypto)
    byte[] S = Base64.decodeBase64(signature_S);

    byte[] modulusBytes = Base64.decodeBase64(n);
    byte[] exponentBytes = Base64.decodeBase64(e);
    BigInteger modulusInteger = new BigInteger(1, modulusBytes);
    BigInteger exponentInteger = new BigInteger(1, exponentBytes);

    RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulusInteger, exponentInteger);
    KeyFactory fact = KeyFactory.getInstance("RSA");
    PublicKey pubKey = fact.generatePublic(rsaPubKey);
    Signature signature = Signature.getInstance("SHA256withRSA");
    signature.initVerify(pubKey);
    signature.update(M);
    boolean isVerified = signature.verify(S);
    Debug.println("Verify result [" + isVerified + "]");
    return isVerified;
}

From source file:org.opendatakit.services.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this row.
 * //ww  w. j  a  v  a2  s . c  om
 * @param appName
 * @param tableId
 * @param xmlBase64RsaPublicKey
 * @param instanceId
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(String appName, String tableId,
        String xmlBase64RsaPublicKey, String instanceId) {

    // fetch the form information
    String base64RsaPublicKey = xmlBase64RsaPublicKey;
    PublicKey pk;
    Base64Wrapper wrapper;

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

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

    int version = android.os.Build.VERSION.SDK_INT;
    if (version < 8) {
        WebLogger.getLogger(appName).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(appName);
    } catch (ClassNotFoundException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not have Base64 class but API level is " + version);
        WebLogger.getLogger(appName).printStackTrace(e);
        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) {
        WebLogger.getLogger(appName).e(t, "Phone does not support RSA encryption.");
        WebLogger.getLogger(appName).printStackTrace(e);
        return null;
    }
    try {
        pk = kf.generatePublic(publicKeySpec);
    } catch (InvalidKeySpecException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t, "Invalid RSA public key.");
        return null;
    }
    return new EncryptedFormInformation(appName, tableId, xmlBase64RsaPublicKey, instanceId, pk, wrapper);
}

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

public static boolean verifySignatureES256(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-256");
    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("SHA256WITHECDSA", "BC");
    signature.initVerify(publicKey);//w  w  w  . j  a  v a 2 s.  c o  m
    signature.update(signingInput);
    return signature.verify(sigBytes);
}

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

public static boolean verifySignatureES384(byte[] signingInput, byte[] sigBytes, ECDSAPublicKey ecdsaPublicKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        IOException, SignatureException {
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("P-384");
    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("SHA384WITHECDSA", "BC");
    signature.initVerify(publicKey);//from w  w w. j  a  va2 s.  c  o m
    signature.update(signingInput);
    return signature.verify(sigBytes);
}