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:de.pawlidi.openaletheia.utils.CipherUtils.java

/**
 * /*from   w w w. ja va2s  . c  o m*/
 * @param data
 * @return
 */
public static RSAPublicKey buildPublicKey(final String key) {
    if (StringUtils.isNotEmpty(key)) {
        try {
            byte[] bytes = Converter.toBytes(key);
            KeyFactory keyFactory = KeyFactory.getInstance(CIPHER_ALGORITHM);
            X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes);
            return (RSAPublicKey) keyFactory.generatePublic(pubSpec);
        } catch (Exception e) {
            throw new RuntimeException("Cannot create " + CIPHER_ALGORITHM + " public key from " + key, e);
        }
    }
    return null;
}

From source file:tor.TorCrypto.java

/**
 * Parses a public key encoded as ASN.1//from   w  ww .  j ava 2  s  .c om
 *
 * @param rsapublickey ASN.1 Encoded public key
 * @return PublicKey
 */
public static PublicKey asn1GetPublicKey(byte[] rsapublickey) {
    int blobsize = rsapublickey.length;
    DataInputStream dis = null;
    int jint = 0; // int to represent unsigned byte or unsigned short
    int datacount = 0;

    try {
        // --- Try to read the ANS.1 encoded RSAPublicKey blob -------------
        ByteArrayInputStream bis = new ByteArrayInputStream(rsapublickey);
        dis = new DataInputStream(bis);

        if (dis.readByte() != 0x30) // asn.1 encoded starts with 0x30
            return null;

        jint = dis.readUnsignedByte(); // asn.1 is 0x80 plus number of bytes
        // representing data count
        if (jint == 0x81)
            datacount = dis.readUnsignedByte(); // datalength is specified
        // in next byte.
        else if (jint == 0x82) // bytes count for any supported keysize
            // would be at most 2 bytes
            datacount = dis.readUnsignedShort(); // datalength is specified
        // in next 2 bytes
        else
            return null; // all supported publickey byte-sizes can be
        // specified in at most 2 bytes

        if ((jint - 0x80 + 2 + datacount) != blobsize) // sanity check for
            // correct number of
            // remaining bytes
            return null;

        //      System.out
        //         .println("\nRead outer sequence bytes; validated outer asn.1 consistency ");

        // ------- Next attempt to read Integer sequence for modulus ------
        if (dis.readUnsignedByte() != 0x02) // next byte read must be
            // Integer asn.1 specifier
            return null;
        jint = dis.readUnsignedByte(); // asn.1 is 0x80 plus number of bytes
        // representing data count
        if (jint == 0x81)
            datacount = dis.readUnsignedByte(); // datalength is specified
        // in next byte.
        else if (jint == 0x82) // bytes count for any supported keysize
            // would be at most 2 bytes
            datacount = dis.readUnsignedShort(); // datalength is specified
        // in next 2 bytes
        else
            return null; // all supported publickey modulus byte-sizes can
        // be specified in at most 2 bytes

        // ---- next bytes are big-endian ordered modulus -----
        byte[] modulus = new byte[datacount];
        int modbytes = dis.read(modulus);
        if (modbytes != datacount) // if we can read enought modulus bytes
            // ...
            return null;

        //System.out.println("Read modulus");

        // ------- Next attempt to read Integer sequence for public exponent
        // ------
        if (dis.readUnsignedByte() != 0x02) // next byte read must be
            // Integer asn.1 specifier
            return null;
        datacount = dis.readUnsignedByte(); // size of modulus is specified
        // in one byte
        byte[] exponent = new byte[datacount];
        int expbytes = dis.read(exponent);
        if (expbytes != datacount)
            return null;
        //System.out.println("Read exponent");

        // ----- Finally, create the PublicKey object from modulus and
        // public exponent --------
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(1, modulus),
                new BigInteger(1, exponent));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        return pubKey;
    } catch (Exception exc) {
        return null;
    } finally {
        try {
            dis.close();
        } catch (Exception exc) {
            /* ignore */
            ;
        }
    }
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Decrypts a message.//from   w  w  w  .  j  av a  2 s .  c o m
 * @param args Arguments: enc, privateKey, sig, publicKey
 * @param callback Callback
 */
public static void decrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        // Get the arguments
        String enc = args.getString(0);
        String key = args.getString(1);
        String sig = null;
        String pub = null;
        if (args.length() == 4) {
            sig = args.getString(2);
            pub = args.getString(3);
        }
        Boolean ver = null;

        // Convert everything into byte arrays
        byte[] encRaw = Base64.decode(enc, Base64.DEFAULT);
        byte[] keyRaw = Base64.decode(stripKey(key), Base64.DEFAULT);

        // Verify signature
        if (sig != null && pub != null) {
            try {
                byte[] sigRaw = Base64.decode(sig, Base64.DEFAULT);
                byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);
                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
                KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
                Signature s = Signature.getInstance("SHA1withRSA", "BC");
                s.initVerify(kf.generatePublic(publicKeySpec));
                s.update(encRaw);
                ver = s.verify(sigRaw);
            } catch (Exception ex) {
                Log.i("whistle", "Verification failed: " + ex.getMessage());
                ver = false;
            }
        }

        // Split enc into encrypted aes data and remaining enc
        byte[] encSplit = encRaw;
        byte[] aesRaw = new byte[RSA_BYTES];
        System.arraycopy(encSplit, 0, aesRaw, 0, aesRaw.length);
        encRaw = new byte[encSplit.length - RSA_BYTES];
        System.arraycopy(encSplit, RSA_BYTES, encRaw, 0, encRaw.length);

        // Decrypt encrypted aes data using RSAES-OAEP
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        Cipher c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding");
        c.init(Cipher.DECRYPT_MODE, kf.generatePrivate(privateKeySpec));
        aesRaw = c.doFinal(aesRaw);

        // Decrypted enc using AES-CBC
        byte[] aesKey = new byte[AES_BYTES];
        byte[] aesIv = new byte[aesRaw.length - aesKey.length];
        System.arraycopy(aesRaw, 0, aesKey, 0, aesKey.length);
        System.arraycopy(aesRaw, aesKey.length, aesIv, 0, aesIv.length);
        c = Cipher.getInstance("AES/CBC/PKCS7Padding");
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));
        byte[] dec = c.doFinal(encRaw);

        JSONArray res = new JSONArray();
        res.put(new String(dec, "utf-8"));
        res.put(ver);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Decrypt error:" + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:im.whistle.crypt.Crypt.java

/**
 * Encrypts a message.//from w ww .ja  va 2  s .  c om
 * @param args Arguments: data, publicKey[, privateKey]
 * @param callback Callback
 */
public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        PRNGProvider.init(); // Ensure OpenSSL fix

        // Get the arguments
        String data = args.getString(0);
        String pub = args.getString(1);
        String priv = null;
        if (args.length() == 3) {
            priv = args.getString(2);
        }
        String sig = null;

        // Convert everything into byte arrays
        byte[] dataRaw = data.getBytes("utf-8");
        byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);

        // Generate random AES key and IV
        byte[] aesKey = new byte[AES_BYTES];
        new SecureRandom().nextBytes(aesKey);
        byte[] aesIv = new byte[16]; // Block size
        new SecureRandom().nextBytes(aesIv);
        Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));

        // Encrypt data with AES
        byte[] encData = c.doFinal(dataRaw);

        // Encrypt aes data with RSA
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC");
        c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec));
        c.update(aesKey);
        c.update(aesIv);
        byte[] encKey = c.doFinal();

        // Concatenate and transform
        byte[] encRaw = new byte[encKey.length + encData.length];
        System.arraycopy(encKey, 0, encRaw, 0, encKey.length);
        System.arraycopy(encData, 0, encRaw, encKey.length, encData.length);
        encKey = null;
        encData = null;
        String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8");

        // Sign
        if (priv != null) {
            // Fail on error (no try-catch)
            byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT);
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw);
            Signature s = Signature.getInstance("SHA1withRSA", "BC");
            s.initSign(kf.generatePrivate(privateKeySpec));
            s.update(encRaw);
            sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8");
        }

        JSONArray res = new JSONArray();
        res.put(enc);
        res.put(sig);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

public static PublicKey generatePublicKey(BigInteger modulus, BigInteger exponential)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPublicKeySpec rsaKeySpec = new RSAPublicKeySpec(modulus, exponential);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePublic(rsaKeySpec);
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

/**
* Converts a {@link String} to {@link PublicKey}.
*    /*from   w  w  w .j a v  a2  s  .co  m*/
                             
@param  publicKeyString  An object of the type {@link String}
*                                  
        
@return  {@link PublicKey}
* 
        
@see         X509EncodedKeySpec
*
        
@see         KeyFactory
*/
public static PublicKey stringToPublicKey(String publicKeyString)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyString.getBytes()));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePublic(spec);
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Creates a public key from a byte[]/*  w  w w  .  j av  a 2s .  co m*/
 * 
 * @param keyType
 *            type for example "RSA"
 * @param keyBytes
 *            the byte[] with the key
 * @return the public key or null on error
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 */
public static PublicKey createPublicKeyFromBytes(byte[] keyBytes) {
    PublicKey pk = null;
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.KEY_FACTORY, new BouncyCastleProvider());
        pk = keyFactory.generatePublic(new X509EncodedKeySpec(keyBytes));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        logger.warn("Exception caught in CryptCore." + "createPublicKeyFromBytes, returning null", e);
    }
    return pk;
}

From source file:com.adeptj.modules.security.jwt.internal.JwtKeys.java

static PublicKey createVerificationKey(SignatureAlgorithm signatureAlgo, String publicKey) {
    LOGGER.info("Creating RSA verification key!!");
    Assert.isTrue(StringUtils.startsWith(publicKey, PUB_KEY_HEADER), INVALID_PUBLIC_KEY_MSG);
    try {/*from ww  w .  j a v  a2s.  c o m*/
        KeyFactory keyFactory = KeyFactory.getInstance(signatureAlgo.getFamilyName());
        byte[] publicKeyData = Base64.getDecoder().decode(publicKey.replace(PUB_KEY_HEADER, EMPTY)
                .replace(PUB_KEY_FOOTER, EMPTY).replaceAll(REGEX_SPACE, EMPTY).trim().getBytes(UTF_8));
        LOGGER.info("Creating X509EncodedKeySpec from public key !!");
        return keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyData));
    } catch (GeneralSecurityException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new KeyInitializationException(ex.getMessage(), ex);
    }
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

/**
 * Reads an RSA {@link PublicKey} from disk.
 *    /*from w  w  w  . j  a  va2  s  . co m*/
                             
@param  fileName  An object of the type {@link String}
 *                                  
        
@return  {@link PublicKey}
 * 
        
@see         SDCardReadWrite
 */
public static PublicKey readPublicKey(String fileName) throws IOException {

    File sdCard = Environment.getExternalStorageDirectory();
    File keyDir = new File(sdCard.getAbsolutePath() + Constants.KEYS_DIR);
    File file = new File(keyDir, fileName);
    InputStream inputStream = new FileInputStream(file.toString());
    ObjectInputStream objInputStream = new ObjectInputStream(new BufferedInputStream(inputStream));
    try {
        BigInteger modulus = (BigInteger) objInputStream.readObject();
        BigInteger exponential = (BigInteger) objInputStream.readObject();
        RSAPublicKeySpec rsaKeySpec = new RSAPublicKeySpec(modulus, exponential);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(rsaKeySpec);
    } catch (Exception e) {
        throw new RuntimeException("readPublicKey exception", e);
    } finally {
        objInputStream.close();
    }

}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void verify(String cert64, String public64) throws CertificateException, NoSuchAlgorithmException,
        InvalidKeySpecException, SignatureException, NoSuchProviderException, InvalidKeyException {
    if (StringUtils.isBlank(cert64)) {
        throw new CertificateException("Certificate is empty");
    } else if (StringUtils.isBlank(public64)) {
        throw new InvalidKeyException("Public key is empty");
    }//from  ww w  . j  a  v a2  s. c o m
    byte[] cert = Base64.decode(cert64);
    byte[] key = Base64.decode(public64);
    X509CertImpl x509 = new X509CertImpl(cert);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(key);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    x509.verify(publicKey);
    x509.checkValidity(utc.getTime());
}