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:org.apache.james.jdkim.IscheduleDKIMSigner.java

/**
 * Generate a PrivateKey from a Base64 encoded private key.
 *
 * In order to generate a valid PKCS8 key when you have a PEM key you can do
 * this: <code>/*from w ww .j a  v a  2s .  com*/
 * openssl pkcs8 -topk8 -inform PEM -in rsapriv.pem -outform DER -nocrypt -out rsapriv.der
 * </code> And then base64 encode the content.
 *
 * @param privateKeyPKCS8
 *            a Base64 encoded string of the RSA key in PKCS8 format
 * @return the PrivateKey
 * @throws NoSuchAlgorithmException
 *             if RSA is unknown
 * @throws InvalidKeySpecException
 *             on bad input key
 */
public static PrivateKey getPrivateKey(final String privateKeyPKCS8)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] encKey = Base64.decodeBase64(privateKeyPKCS8.getBytes());
    // byte[] encKey = privateKey.getBytes();
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(encKey);
    KeyFactory keyFactory;
    keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privKey = keyFactory.generatePrivate(privSpec);
    return privKey;
}

From source file:de.alpharogroup.crypto.key.KeyExtensions.java

/**
 * Read public key./*ww  w  . ja v  a  2 s .co  m*/
 *
 * @param publicKeyBytes
 *            the public key bytes
 * @param provider
 *            the provider
 * @return the public key
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PublicKey readPublicKey(final byte[] publicKeyBytes, final String provider)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
    final KeyFactory keyFactory = KeyFactory.getInstance(KeyPairGeneratorAlgorithm.RSA.getAlgorithm());
    final PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}

From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java

public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass,
        byte[] certChain)
        throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
    // load the private key
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
    PrivateKey pk = kf.generatePrivate(keysp);

    // load the cert chain
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certChain);

    Collection<? extends Certificate> certCol = cf.generateCertificates(bais);
    Certificate[] certs = new Certificate[certCol.toArray().length];
    if (certCol.size() == 1) {
        Debug.logInfo("Single certificate; no chain", module);
        bais = new ByteArrayInputStream(certChain);
        Certificate cert = cf.generateCertificate(bais);
        certs[0] = cert;/*from www. ja  va2s .c  om*/
    } else {
        Debug.logInfo("Certificate chain length : " + certCol.size(), module);
        certs = certCol.toArray(new Certificate[certCol.size()]);
    }

    ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
}

From source file:org.apache.james.jdkim.DKIMSigner.java

/**
 * Generate a PrivateKey from a Base64 encoded private key.
 * //from   w  w w  .ja  v  a  2s  . co m
 * In order to generate a valid PKCS8 key when you have a PEM key you can do
 * this: <code>
 * openssl pkcs8 -topk8 -inform PEM -in rsapriv.pem -outform DER -nocrypt -out rsapriv.der
 * </code> And then base64 encode the content.
 * 
 * @param privateKeyPKCS8
 *            a Base64 encoded string of the RSA key in PKCS8 format
 * @return the PrivateKey
 * @throws NoSuchAlgorithmException
 *             if RSA is unknown
 * @throws InvalidKeySpecException
 *             on bad input key
 */
public static PrivateKey getPrivateKey(String privateKeyPKCS8)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] encKey = Base64.decodeBase64(privateKeyPKCS8.getBytes());
    // byte[] encKey = privateKey.getBytes();
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(encKey);
    KeyFactory keyFactory;
    keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privKey = keyFactory.generatePrivate(privSpec);
    return privKey;
}

From source file:hudson.cli.Connection.java

public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException {
    KeyPair keyPair;//from   w  w w .j ava  2  s .  c  o m
    PublicKey otherHalf;

    if (side) {
        AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH");
        paramGen.init(keySize);

        KeyPairGenerator dh = KeyPairGenerator.getInstance("DH");
        dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class));
        keyPair = dh.generateKeyPair();

        // send a half and get a half
        writeKey(keyPair.getPublic());
        otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());
    } else {
        otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey());

        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH");
        keyPairGen.initialize(((DHPublicKey) otherHalf).getParams());
        keyPair = keyPairGen.generateKeyPair();

        // send a half and get a half
        writeKey(keyPair.getPublic());
    }

    KeyAgreement ka = KeyAgreement.getInstance("DH");
    ka.init(keyPair.getPrivate());
    ka.doPhase(otherHalf, true);

    return ka;
}

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

/**
 * <p>//www  . j  av  a  2 s  .  co m
 * 
 * </p>
 * 
 * @param encryptedData ?
 * @param publicKey (BASE64?)
 * @return byte
 * @throws Exception Exception
 */
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(publicKey);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicK = keyFactory.generatePublic(x509KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicK);
    int inputLen = encryptedData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int index = 0;
    // ?
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
            cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        index++;
        offSet = index * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
}

From source file:com.shenit.commons.codec.RsaUtils.java

/**
 * ?//from   w  ww.j  a  v  a 2s  .c om
 * 
 * @param key
 *            ?base64?
 * @throws Exception
 */
public static PrivateKey getPrivateKey(String key) throws Exception {

    byte[] keyBytes;

    keyBytes = Base64.decodeBase64(key);

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

    KeyFactory keyFactory = KeyFactory.getInstance(CODEC_RSA);

    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

    return privateKey;
}

From source file:XmldapCertsAndKeys.java

public static RSAPrivateKey getXmldapPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
    String exponentB64 = "AKh/FZVHiKxcIPA8g2mN8TUdMXuX58I7z4jS+57vYta387MG3DGZtQ/XXfHdPx9WjdoW0KWE2Pl5"
            + "SbOZW7tVcwigF88FrSJ5i6XDwUktmXjFwJM/TvUZlxWAKUdoOX8MC3DrAYZxeT3kC1mzAiBMPdC4"
            + "W4zNe7Zo0YgbsMzQZowVxZTP4GWa/L8o3adXTvdobP1nKW5buPj9vkgaGCTxE0vQzbuiGj1HRJe9"
            + "MRtvcU/I2shiIVE0F35wk8gw0FATtkvMpTpR12YVeo1JGZsHFQoD7gTD/n/NmC9Rjk2baYGj97hV"
            + "9EpDRcPNsMll2pVRy4Z45j2+t/yl8WjaqK5lhkE=";
    String modulusB64 = "ANMnkVA4xfpG0bLos9FOpNBjHAdFahy2cJ7FUwuXd/IShnG+5qF/z1SdPWzRxTtpFFyodtXlBUEI"
            + "biT+IbYPZF1vCcBrcFa8Kz/4rBjrpPZgllgA/WSVKjnJvw8q4/tO6CQZSlRlj/ebNK9VyT1kN+Mr"
            + "KV1SGTqaIJ2l+7Rd05WHscwZMPdVWBbRrg76YTfy6H/NlQIArNLZanPvE0Vd5QfD4ZyG2hTh3y7Z"
            + "lJAUndGJ/kfZw8sKuL9QSrh4eOTc280NQUmPGz6LP5MXNmu0RxEcomod1+ToKll90yEKFAUKuPYF"
            + "gm9J+vYm4tzRequLy/njteRIkcfAdcAtt6PCYjU=";
    byte[] exponentBytes = Base64.decode(exponentB64);
    byte[] modulusBytes = Base64.decode(modulusB64);
    BigInteger exponent = new BigInteger(1, exponentBytes);
    BigInteger modulus = new BigInteger(1, modulusBytes);
    RSAPrivateKeySpec ks = new RSAPrivateKeySpec(modulus, exponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPrivateKey) kf.generatePrivate(ks);
}

From source file:org.kde.kdeconnect.Device.java

Device(Context context, String deviceId) {
    settings = context.getSharedPreferences(deviceId, Context.MODE_PRIVATE);

    //Log.e("Device","Constructor A");

    this.context = context;
    this.deviceId = deviceId;
    this.name = settings.getString("deviceName", context.getString(R.string.unknown_device));
    this.pairStatus = PairStatus.Paired;
    this.protocolVersion = NetworkPackage.ProtocolVersion; //We don't know it yet
    this.deviceType = DeviceType.FromString(settings.getString("deviceType", "desktop"));

    try {/*w  ww .j a va  2 s .  co m*/
        String publicKeyStr = settings.getString("publicKey", null);
        if (publicKeyStr != null) {
            byte[] publicKeyBytes = Base64.decode(publicKeyStr, 0);
            publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("KDE/Device", "Exception deserializing stored public key for device");
    }

    //Assume every plugin is supported until addLink is called and we can get the actual list
    m_supportedPlugins = new Vector<>(PluginFactory.getAvailablePlugins());

    //Do not load plugins yet, the device is not present
    //reloadPluginsFromSettings();
}

From source file:org.apache.xml.security.test.encryption.BaltimoreEncTest.java

/**
 * Method setUp/* ww w.  ja va 2 s.com*/
 */
protected void setUp() throws Exception {
    // Create the comparison strings

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);

    String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml";
    String basedir = System.getProperty("basedir");
    if (basedir != null && !"".equals(basedir)) {
        filename = basedir + "/" + filename;
    }
    File f = new File(filename);

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new java.io.FileInputStream(f));

    cardNumber = retrieveCCNumber(doc);

    // Test decrypt
    testDecryptString = new String("top secret message\n");

    // Count the nodes in the document as a secondary test
    nodeCount = countNodes(doc);

    // Create the keys
    jebBytes = "abcdefghijklmnopqrstuvwx".getBytes("ASCII");
    jobBytes = "abcdefghijklmnop".getBytes("ASCII");
    jedBytes = "abcdefghijklmnopqrstuvwxyz012345".getBytes("ASCII");

    // Certificate information
    rsaCertSerialNumber = new String("1014918766910");

    // rsaKey
    filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/rsa.p8";
    if (basedir != null && !"".equals(basedir)) {
        filename = basedir + "/" + filename;
    }

    byte[] pkcs8Bytes = JavaUtils.getBytesFromFile(filename);

    PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(pkcs8Bytes);

    // Create a key factory 
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    rsaKey = keyFactory.generatePrivate(pkcs8Spec);

    // Initialise the library

    org.apache.xml.security.Init.init();

    // Register our key resolver
    KeyResolver.register("org.apache.xml.security.test.encryption.BobKeyResolver");

    // Check what algorithms are available

    haveISOPadding = false;
    String algorithmId = JCEMapper
            .translateURItoJCEID(org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);

    if (algorithmId != null) {
        try {
            if (Cipher.getInstance(algorithmId) != null)
                haveISOPadding = true;
        } catch (NoSuchAlgorithmException nsae) {
        } catch (NoSuchPaddingException nspe) {
        }
    }

    haveKeyWraps = (JCEMapper.translateURItoJCEID(
            org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_KEYWRAP_AES128) != null);
}