Example usage for java.security KeyFactory getInstance

List of usage examples for java.security KeyFactory getInstance

Introduction

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

Prototype

public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyFactory object that converts public/private keys of the specified algorithm.

Usage

From source file:com.axelor.apps.account.service.payment.PayboxService.java

/** Chargement de la cle AU FORMAT der
  * Utliser la commande suivante pour 'convertir' la cl 'pem' en 'der'
  * openssl rsa -inform PEM -in pubkey.pem -outform DER -pubin -out pubkey.der
  */*from  ww  w.ja  va2  s . co  m*/
  * @param pubKeyFile
  * @return
  * @throws Exception
  */
@Deprecated
private PublicKey getPubKeyDer(String pubKeyPath) throws Exception {

    FileInputStream fis = new FileInputStream(pubKeyPath);
    DataInputStream dis = new DataInputStream(fis);

    byte[] pubKeyBytes = new byte[fis.available()];

    dis.readFully(pubKeyBytes);
    fis.close();
    dis.close();

    KeyFactory keyFactory = KeyFactory.getInstance(this.ENCRYPTION_ALGORITHM);

    // extraction cle
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubKeyBytes);
    return keyFactory.generatePublic(pubSpec);

}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*from   www .  j a v  a  2s.  co  m*/
 */
@Override
public final ByteArray encryptRandomGeneratedKey(ByteArray key, ByteArray data) throws McbpCryptoException {
    ByteArray result;
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");

        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ByteArray.of(key).getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec));

        result = ByteArray.of(cipher.doFinal(data.getBytes()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | InvalidKeyException
            | BadPaddingException | IllegalBlockSizeException e) {
        throw new McbpCryptoException(e.getMessage());
    }
    return result;
}

From source file:biz.bokhorst.xprivacy.Util.java

private static PublicKey getPublicKey(Context context) throws Throwable {
    // Read public key
    String sPublicKey = "";
    InputStreamReader isr = new InputStreamReader(context.getAssets().open("XPrivacy_public_key.txt"), "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    String line = br.readLine();/*from ww w .ja v  a  2s  .c o m*/
    while (line != null) {
        if (!line.startsWith("-----"))
            sPublicKey += line;
        line = br.readLine();
    }
    br.close();
    isr.close();

    // Create public key
    byte[] bPublicKey = Base64.decode(sPublicKey, Base64.NO_WRAP);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec encodedPubKeySpec = new X509EncodedKeySpec(bPublicKey);
    return keyFactory.generatePublic(encodedPubKeySpec);
}

From source file:com.orange.oidc.tim.service.KryptoUtils.java

public static String getJwkPublic(KeyPair kp) {
    try {//from w  w  w.ja  v  a 2s  .  co m
        JSONObject jk = new JSONObject();
        jk.put("kty", "RSA");
        // generate random kid for tim_app_key
        SecureRandom random = new SecureRandom();
        String kid = new BigInteger(130, random).toString(32);
        jk.put("kid", kid);
        jk.put("e", "AQAB");

        KeyFactory kfactory = KeyFactory.getInstance("RSA");

        RSAPublicKeySpec kspec = (RSAPublicKeySpec) kfactory.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);

        jk.put("n", encodeB64(kspec.getModulus().toByteArray()));
        JSONArray ja = new JSONArray();
        ja.put(jk);
        JSONObject jo = new JSONObject();
        jo.put("keys", ja);

        // Log.d("getJwkPublic key: ",pubkey.toString());
        // Log.d("getJwkPublic jwk: ",jo.toString());

        return jo.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.arm.connector.bridge.core.Utils.java

static public PrivateKey createPrivateKeyFromPEM(ErrorLogger logger, String pem, String algorithm) {
    try {/*from  w  w  w  . j  a  v  a2 s  . c  om*/
        String temp = Utils.escapeChars(pem);
        String privKeyPEM = temp.replace("-----BEGIN RSA PRIVATE KEY-----", "");
        privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");

        // DEBUG
        //logger.info("createPrivateKeyFromPEM: " + privKeyPEM);

        Base64 b64 = new Base64();
        byte[] decoded = b64.decode(privKeyPEM);

        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
        KeyFactory kf = KeyFactory.getInstance(algorithm);
        return kf.generatePrivate(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        // exception caught
        logger.warning("createPrivateKeyFromPEM: Exception during private key gen", ex);
    }
    return null;
}

From source file:com.wso2telco.proxy.entity.ServerInitiatedServiceEndpoints.java

private RSAPublicKey loadPublicKey(String publicKeyContent) throws GeneralSecurityException {
    KeyFactory kf = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyContent));
    return (RSAPublicKey) kf.generatePublic(pubSpec);
}

From source file:com.orange.oidc.tim.service.KryptoUtils.java

public static String getJwkPrivate(KeyPair kp) {
    try {/* ww  w.  j a v  a2s  .c om*/
        JSONObject jk = new JSONObject();
        jk.put("kty", "RSA");
        // generate random kid for tim_app_key
        SecureRandom random = new SecureRandom();
        String kid = new BigInteger(130, random).toString(32);
        jk.put("kid", kid);
        jk.put("e", "AQAB");

        KeyFactory kfactory = KeyFactory.getInstance("RSA");

        RSAPrivateKeySpec privkspec = (RSAPrivateKeySpec) kfactory.getKeySpec(kp.getPrivate(),
                RSAPrivateKeySpec.class);
        RSAPublicKeySpec pubkspec = (RSAPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
                RSAPublicKeySpec.class);

        // Log.d("getJwkPrivate n",pubkspec.getPublicExponent().toString());
        // Log.d("getJwkPrivate d",privkspec.getPrivateExponent().toString());

        jk.put("n", encodeB64(pubkspec.getModulus().toByteArray()));
        jk.put("d", encodeB64(privkspec.getPrivateExponent().toByteArray()));
        JSONArray ja = new JSONArray();
        ja.put(jk);
        JSONObject jo = new JSONObject();
        jo.put("keys", ja);

        return jo.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * X509??./*from www. j ava  2s.c  o  m*/
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, CertificateException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}

From source file:com.arm.connector.bridge.core.Utils.java

static public PublicKey createPublicKeyFromPEM(ErrorLogger logger, String pem, String algorithm) {
    try {//from www.  j a  v a2 s  .co  m
        String temp = Utils.escapeChars(pem);
        String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----", "");
        publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");

        // DEBUG
        //logger.info("createPublicKeyFromPEM: " + publicKeyPEM);

        Base64 b64 = new Base64();
        byte[] decoded = b64.decode(publicKeyPEM);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
        KeyFactory kf = KeyFactory.getInstance(algorithm);
        return kf.generatePublic(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        // exception caught
        logger.warning("createPublicKeyFromPEM: Exception during public key gen", ex);
    }
    return null;
}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * X509??.//w ww .j a  v  a2s.  c o  m
 * @param privateKeyFileName ???
 * @param certificateFileName ??
 * @param rootCertificateFileNames ??
 * @throws IOException IOException
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws CertificateException CertificateException
 * @throws InvalidNameException InvalidNameException
 */
public static void configureX509(String privateKeyFileName, String certificateFileName,
        String[] rootCertificateFileNames) throws IOException, NoSuchAlgorithmException,
        InvalidKeySpecException, CertificateException, InvalidNameException {

    xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    // Read RootCA Certificate
    x509RootCertificateFileNames = new ArrayList<String>();
    if (rootCertificateFileNames != null) {
        for (String fileName : rootCertificateFileNames) {
            x509RootCertificateFileNames.add(fileName);
        }
    }

    // Read Private Key
    InputStream is = null;
    if (privateKeyFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_KEY_PATH);
    } else {
        is = new FileInputStream(privateKeyFileName);
    }

    PEMReader privateKeyPemReader = new PEMReader(is);
    byte[] privateKeyDerBytes = privateKeyPemReader.getDerBytes();
    PKCS1EncodedKeySpec keySpecRSAPrivateKey = new PKCS1EncodedKeySpec(privateKeyDerBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    privKey = keyFactory.generatePrivate(keySpecRSAPrivateKey.getKeySpec());

    // Read Certificate
    if (certificateFileName == null) {
        is = TransCellAccessToken.class.getClassLoader()
                .getResourceAsStream(X509KeySelector.DEFAULT_SERVER_CRT_PATH);
    } else {
        is = new FileInputStream(certificateFileName);
    }
    PEMReader serverCertificatePemReader;
    serverCertificatePemReader = new PEMReader(is);
    byte[] serverCertificateBytesCert = serverCertificatePemReader.getDerBytes();
    CertificateFactory cf = CertificateFactory.getInstance(X509KeySelector.X509KEY_TYPE);
    x509Certificate = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(serverCertificateBytesCert));

    // Create the KeyInfo containing the X509Data
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    List x509Content = new ArrayList();
    x509Content.add(x509Certificate.getSubjectX500Principal().getName());
    x509Content.add(x509Certificate);
    X509Data xd = keyInfoFactory.newX509Data(x509Content);
    keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(xd));

    // Get FQDN from Certificate and set FQDN to PersoniumCoreUtils
    String dn = x509Certificate.getSubjectX500Principal().getName();
    LdapName ln = new LdapName(dn);
    for (Rdn rdn : ln.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("CN")) {
            PersoniumCoreUtils.setFQDN(rdn.getValue().toString());
            break;
        }
    }

    // http://java.sun.com/developer/technicalArticles/xml/dig_signature_api/

}