Example usage for java.security KeyFactory generatePrivate

List of usage examples for java.security KeyFactory generatePrivate

Introduction

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

Prototype

public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

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

Usage

From source file:com.wso2telco.gsma.authenticators.GSMAMSISDNAuthenticator.java

/**
 * Read private key from file./*from w w  w .  j  av  a2s.c  om*/
 *
 * @param fileName the file name
 * @return the private key
 * @throws IOException              Signals that an I/O exception has occurred.
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws InvalidKeySpecException  the invalid key spec exception
 */
public PrivateKey readPrivateKeyFromFile(String fileName)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    String publicK = readStringKey(fileName);
    //byte[] keyBytes = new BASE64Decoder().decodeBuffer(publicK);
    byte[] keyBytes = Base64.decodeBase64(publicK.getBytes());
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory fact = KeyFactory.getInstance("RSA");
    return fact.generatePrivate(keySpec);
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is set to 'privateKey' and the private key password is
 * null.//www. jav  a  2s  .co  m
 * 
 * @param alias
 *            the alias used for the key entry
 * @param privKey
 *            RSA private key
 * @param cert
 *            user certificate
 * @param cachain
 *            CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception
 *                if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O");
                    if (cafriendly == null) {
                        cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU");
                        if (cafriendly == null) {
                            cafriendly = "CA_unknown" + i;
                        } else {
                            cafriendly = cafriendly + i;
                        }
                    } else {
                        cafriendly = cafriendly + i;
                    }
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * Read public key from file./*from   www. j a  v a 2 s.  co  m*/
 * @param filePath
 * @return
 * @throws IOException
 */
public PrivateKey readPrivateKeyFromFile(String filePath) throws Exception {
    // Read file to a byte array.
    String privateKeyFileName = filePath;
    Path path = Paths.get(privateKeyFileName);
    byte[] privKeyByteArray = Files.readAllBytes(path);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKeyByteArray);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey myPrivKey = keyFactory.generatePrivate(keySpec);
    return myPrivKey;
}

From source file:com.mhise.util.MHISEUtil.java

public static PrivateKey readKey(Context context) throws Exception {

    String keyFile = "privateKey.key";
    FileInputStream fis = context.openFileInput(keyFile);
    int kl = fis.available();
    byte[] kb = new byte[kl];
    fis.read(kb);/*from  w w w .j  a v  a 2 s .  c  o m*/
    fis.close();
    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(kb);
    PrivateKey pk = kf.generatePrivate(ks);

    return pk;
}

From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java

/**
 * //from w ww  . j  a  v  a 2s  . c  o m
 * 
 * 
 * @param info ?
 * @return ?
 * @throws GeneralSecurityException GeneralSecurityException
 */
public String decode(String info) throws GeneralSecurityException {
    byte[] priKeyText = this.getPriKeyText();
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKeyText));
    KeyFactory keyFactory = null;
    if (provider == null) {
        keyFactory = KeyFactory.getInstance(ALGORITHM);
    } else {
        keyFactory = KeyFactory.getInstance(ALGORITHM, provider);
    }
    // ??
    PrivateKey priKey = keyFactory.generatePrivate(priPKCS8);
    // ?CipherECB?PKCS5Padding
    Cipher cipher = null;
    if (provider == null) {
        cipher = Cipher.getInstance(ALGORITHM);
    } else {
        cipher = Cipher.getInstance(ALGORITHM, provider);
    }
    // ?
    cipher.init(Cipher.DECRYPT_MODE, priKey);
    byte[] newPlainText = cipher.doFinal(Base64.decodeBase64(info.getBytes()));
    return new String(newPlainText);
}

From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java

@Override
public PrivateKey loadPrivateKey(String privateKeyD) throws U2FException {
    try {/*w w  w.j a v  a2  s  . com*/
        KeyFactory fac = KeyFactory.getInstance("ECDSA", BOUNCY_CASTLE_PROVIDER);
        ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");
        ECPrivateKeySpec keySpec = new ECPrivateKeySpec(new BigInteger(privateKeyD, 16), ecSpec);
        return fac.generatePrivate(keySpec);
    } catch (NoSuchAlgorithmException ex) {
        throw new U2FException("Failed to load private key", ex);
    } catch (InvalidKeySpecException ex) {
        throw new U2FException("Failed to load private key", ex);
    }
}

From source file:org.wso2.sample.identity.oauth2.IDTokenDecrypterServlet.java

/**
 * Decrypt the id token using the private key.
 *
 * @param JWE              id token to be decrypted
 * @param privateKeyString client private key as a string
 * @return decrypted id token as an EncryptedJWT object
 * @throws NoSuchAlgorithmException/*from w  w  w . j a v  a  2s .  c  om*/
 * @throws InvalidKeySpecException
 * @throws ParseException
 * @throws JOSEException
 * @throws IllegalArgumentException
 */
private EncryptedJWT decryptJWE(String JWE, String privateKeyString) throws NoSuchAlgorithmException,
        InvalidKeySpecException, ParseException, JOSEException, IllegalArgumentException {

    KeyFactory kf = KeyFactory.getInstance("RSA");
    // Remove EOF characters from key string and generate key object.
    privateKeyString = privateKeyString.replace("\n", "").replace("\r", "");
    PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
    PrivateKey privateKey = kf.generatePrivate(keySpecPKCS8);

    EncryptedJWT jwt = EncryptedJWT.parse(JWE);

    // Create a decrypter with the specified private RSA key.
    RSADecrypter decrypter = new RSADecrypter((RSAPrivateKey) privateKey);

    jwt.decrypt(decrypter);

    return jwt;
}

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

/**
 * Decrypts a message./*from ww  w. ja va 2s . 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);
    }
}