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:org.jboss.aerogear.cordova.crypto.CryptoPlugin.java

private java.security.KeyPair parseKeyPairFromJson(byte[] encodedPublicKey, byte[] encodedPrivateKey) {
    try {/*from   www  .  j  ava 2s.  c o  m*/
        KeyFactory fact = KeyFactory.getInstance("ECDH", AeroGearCrypto.PROVIDER);
        PublicKey publicKey2 = fact.generatePublic(new X509EncodedKeySpec(encodedPublicKey));
        java.security.PrivateKey privateKey2 = fact.generatePrivate(new PKCS8EncodedKeySpec(encodedPrivateKey));
        return new java.security.KeyPair(publicKey2, privateKey2);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("could not reconstruct key pair from json!", e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("could not reconstruct key pair from json!", e);
    } catch (NoSuchProviderException e) {
        throw new RuntimeException("could not reconstruct key pair from json!", e);
    }
}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Main method to initialise the private key from the database
 * @throws Exception/*from w w w  .  ja  v a2  s.  co  m*/
 */
private void initialisePrivateKey() throws Exception {

    if (encodedPrivateKey == null)
        throw new Exception("An encoded Base64 private key has not been specified.");

    try {
        //Read key files back and decode them from BASE64
        byte[] privateKeyBytes = Base64.decodeBase64(encodedPrivateKey);

        // Convert back to public and private key objects
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        privateKey = keyFactory.generatePrivate(privateKeySpec);

    } catch (InvalidKeySpecException e) {
        throw new Exception("Invalid key specifications. Not a valid key entry." + e.getCause());
    } catch (NoSuchAlgorithmException e) {
        throw new Exception("There is no such algorithm. Please check the JDK ver." + e.getCause());
    }
}

From source file:de.tum.in.tumcampus.services.GcmIntentService.java

/**
 * Loads the private key from preferences
 *
 * @return The private key object// w  w  w  .  j a v  a2s.c o m
 */
private PrivateKey getPrivateKeyFromSharedPrefs() {
    String privateKeyString = Utils.getInternalSettingString(this, Const.PRIVATE_KEY, "");
    byte[] privateKeyBytes = Base64.decode(privateKeyString, Base64.DEFAULT);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        return keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        Utils.log(e);
    }
    return null;
}

From source file:org.springframework.boot.actuate.autoconfigure.cloudfoundry.reactive.ReactiveTokenValidatorTests.java

private PrivateKey getPrivateKey() throws InvalidKeySpecException, NoSuchAlgorithmException {
    String signingKey = "-----BEGIN PRIVATE KEY-----\n"
            + "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDSbn2Xa72IOcxu\n"
            + "tcd+qQ6ufZ1VDe98EmpwO4VQrTd37U9kZtWU0KqeSkgnyzIWmlbyWOdbB4/v4uJa\n"
            + "lGjPQjt9hvd3xOOFXzpj33sWXgMGvGAzopMk64T+7GegOFlDXguA5TZyReM7M51O\n"
            + "ycYwpAEsKXS+lxcG0UsxpJum/WjOLyHsMnJVnoScVBlRYZ2BMyEOuap69/H3lT/X\n"
            + "pzlYEM6SrAifsaWvL2f1K7HKBt/yDkDOlZy6xmAMsghnslNSV0FvypTZrQOXia8t\n"
            + "k6fjA+iN+P0LDZAgKxzn4/B/bV8/6HN/7VZJEdudi/y5qdE7SBnx6QZqCEz/YfqC\n"
            + "olujacgnAgMBAAECggEAc9X2tJ/OWWrXqinOg160gkELloJxTi8lAFsDbAGuAwpT\n"
            + "JcWl1KF5CmGBjsY/8ElNi2J9GJL1HOwcBhikCVNARD1DhF6RkB13mvquWwWtTMvt\n"
            + "eP8JWM19DIc+E+hw2rCuTGngqs7l4vTqpzBTNPtS2eiIJ1IsjsgvSEiAlk/wnW48\n"
            + "11cf6SQMQcT3HNTWrS+yLycEuWKb6Khh8RpD9D+i8w2+IspWz5lTP7BrKCUNsLOx\n"
            + "6+5T52HcaZ9z3wMnDqfqIKWl3h8M+q+HFQ4EN5BPWYV4fF7EOx7+Qf2fKDFPoTjC\n"
            + "VTWzDRNAA1xPqwdF7IdPVOXCdaUJDOhHeXZGaTNSwQKBgQDxb9UiR/Jh1R3muL7I\n"
            + "neIt1gXa0O+SK7NWYl4DkArYo7V81ztxI8r+xKEeu5zRZZkpaJHxOnd3VfADascw\n"
            + "UfALvxGxN2z42lE6zdhrmxZ3ma+akQFsv7NyXcBT00sdW+xmOiCaAj0cgxNOXiV3\n"
            + "sYOwUy3SqUIPO2obpb+KC5ALHwKBgQDfH+NSQ/jn89oVZ3lzUORa+Z+aL1TGsgzs\n"
            + "p7IG0MTEYiR9/AExYUwJab0M4PDXhumeoACMfkCFALNVhpch2nXZv7X5445yRgfD\n"
            + "ONY4WknecuA0rfCLTruNWnQ3RR+BXmd9jD/5igd9hEIawz3V+jCHvAtzI8/CZIBt\n"
            + "AArBs5kp+QKBgQCdxwN1n6baIDemK10iJWtFoPO6h4fH8h8EeMwPb/ZmlLVpnA4Q\n"
            + "Zd+mlkDkoJ5eiRKKaPfWuOqRZeuvj/wTq7g/NOIO+bWQ+rrSvuqLh5IrHpgPXmub\n"
            + "8bsHJhUlspMH4KagN6ROgOAG3fGj6Qp7KdpxRCpR3KJ66czxvGNrhxre6QKBgB+s\n"
            + "MCGiYnfSprd5G8VhyziazKwfYeJerfT+DQhopDXYVKPJnQW8cQW5C8wDNkzx6sHI\n"
            + "pqtK1K/MnKhcVaHJmAcT7qoNQlA4Xqu4qrgPIQNBvU/dDRNJVthG6c5aspEzrG8m\n"
            + "9IHgtRV9K8EOy/1O6YqrB9kNUVWf3JccdWpvqyNJAoGAORzJiQCOk4egbdcozDTo\n"
            + "4Tg4qk/03qpTy5k64DxkX1nJHu8V/hsKwq9Af7Fj/iHy2Av54BLPlBaGPwMi2bzB\n"
            + "gYjmUomvx/fqOTQks9Rc4PIMB43p6Rdj0sh+52SKPDR2eHbwsmpuQUXnAs20BPPI\n"
            + "J/OOn5zOs8yf26os0q3+JUM=\n-----END PRIVATE KEY-----";
    String privateKey = signingKey.replace("-----BEGIN PRIVATE KEY-----\n", "");
    privateKey = privateKey.replace("-----END PRIVATE KEY-----", "");
    byte[] pkcs8EncodedBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}

From source file:org.mitre.jwt.JwtTest.java

/**
 * @throws Exception/*from w  ww .  ja v a  2 s  . c  om*/
 */
@Test
public void testGenerateRsaSignature() throws Exception {

    // Hard code the private/public key so as not to depend on it being in
    // the keystore...

    RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(new BigInteger(
            "AD6E684550542947AD95EF9BACDC0AC2C9168C6EB3212D378C23E5539266111DB2E5B4D42B1E47EB4F7A65DB63D9782C72BC365492FD1E5C7B4CD2174C611668C29013FEDE22619B3F58DA3531BB6C02B3266768B7895CBDAFB3F9AC7A7B2F3DB17EF4DCF03BD2575604BDE0A01BB1FB7B0E733AD63E464DB4D7D89626297A214D7CECCD0C50421A322A01E9DCEA23443F6A9339576B31DFA504A133076394562CB57F3FDEDB26F9A82BED2F6D52D6F6BF8286E2497EF0B5C8456F32B4668F5A9F5FCD3781345DDDB749792C37238A53D18FD976C0C9D1F1E211F1A4A9AAE679C45B92D1741EF0D3C3F373232CE7FB93E9BC461E1C508A20B74E7E3361B3C527",
            16),
            new BigInteger(
                    "627CDD67E75B33EA0990A8F64DEED389942A62EB867C23B274B9F9C440D2078C47089D6D136369D21E5B52B688F8797F3C54D7C1A58B6A8F7851C2C90A4DE42CEFB864328B31191ED19582AD4CA5B38BC0F2E12C9D75BB1DD946AA55A1648D0A4ADEDEED0CDBDBF24EDDF87A345225FBBB0114BCE7E78B831B5CAC197068837AB0B3F07157952A05F67A72B9852972C704B6B32A70C3BB3DEB186936B0F7D6ABE012DEB89BC2DBE1F88AE7A28C06C53D1FB2459E58D8ED266E3BFC28266981D2A5F624D36555DD64F410461ADA5D53F448BA5EEBBD4BCEC3AF53285FB394650D7B3BFB06712E081AAD160EED6E83A3EA2D092712C07A6331209F62D27184BFC9",
                    16));

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

    PrivateKey privateKey = keyFactory.generatePrivate(privateSpec);

    RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(new BigInteger(
            "AD6E684550542947AD95EF9BACDC0AC2C9168C6EB3212D378C23E5539266111DB2E5B4D42B1E47EB4F7A65DB63D9782C72BC365492FD1E5C7B4CD2174C611668C29013FEDE22619B3F58DA3531BB6C02B3266768B7895CBDAFB3F9AC7A7B2F3DB17EF4DCF03BD2575604BDE0A01BB1FB7B0E733AD63E464DB4D7D89626297A214D7CECCD0C50421A322A01E9DCEA23443F6A9339576B31DFA504A133076394562CB57F3FDEDB26F9A82BED2F6D52D6F6BF8286E2497EF0B5C8456F32B4668F5A9F5FCD3781345DDDB749792C37238A53D18FD976C0C9D1F1E211F1A4A9AAE679C45B92D1741EF0D3C3F373232CE7FB93E9BC461E1C508A20B74E7E3361B3C527",
            16), new BigInteger("10001", 16));

    PublicKey publicKey = keyFactory.generatePublic(publicSpec);

    Jwt jwt = new Jwt();
    jwt.getHeader().setType("JWT");
    jwt.getHeader().setAlgorithm("RS256");
    jwt.getClaims().setExpiration(new Date(1300819380L * 1000L));
    jwt.getClaims().setIssuer("joe");
    jwt.getClaims().setClaim("http://example.com/is_root", Boolean.TRUE);

    JwtSigner signer = new RsaSigner(JwsAlgorithm.RS256.getJwaName(), publicKey, privateKey);
    ((RsaSigner) signer).afterPropertiesSet();

    /*
     * Expected string based on the following structures, serialized exactly
     * as follows and base64 encoded:
     * 
     * header: {"typ":"JWT","alg":"HS256"} claims:
     * {"exp":1300819380,"iss":"joe","http://example.com/is_root":true}
     * 
     * Expected signature: dSRvtD-ExzGN-
     * fRXd1wRZOPo1JFPuqgwvaIKp8jgcyMXJegy6IUjssfUfUcICN5yvh0ggOMWMeWkwQ7
     * -PlXMJWymdhXVI3BOpNt7ZOB2vMFYSOOHNBJUunQoe1lmNxuHQdhxqoHahn3u1cLDXz
     * -xx-
     * JELduuMmaDWqnTFPodVPl45WBKHaQhlOiFWj3ZClUV2k5p2yBT8TmxekL8gWwgVbQk5yPnYOs
     * -PcMjzODc9MZX4yI10ZSCSDciwf-
     * rgkQLT7wW4uZCoqTZ7187sCodHd6nw3nghqbtqN05fQ3Yq7ykwaR8pdQBFb2L9l7DhLLuXIREDKIFUHBSUs8OnvXFMg
     */

    String signature = "dSRvtD-ExzGN-fRXd1wRZOPo1JFPuqgwvaIKp8jgcyMXJegy6IUjssfUfUcICN5yvh0ggOMWMeWkwQ7-PlXMJWymdhXVI3BOpNt7ZOB2vMFYSOOHNBJUunQoe1lmNxuHQdhxqoHahn3u1cLDXz-xx-JELduuMmaDWqnTFPodVPl45WBKHaQhlOiFWj3ZClUV2k5p2yBT8TmxekL8gWwgVbQk5yPnYOs-PcMjzODc9MZX4yI10ZSCSDciwf-rgkQLT7wW4uZCoqTZ7187sCodHd6nw3nghqbtqN05fQ3Yq7ykwaR8pdQBFb2L9l7DhLLuXIREDKIFUHBSUs8OnvXFMg";
    String expected = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJleHAiOjEzMDA4MTkzODAsImlzcyI6ImpvZSIsImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ"
            + "." + signature;

    signer.sign(jwt);

    String actual = jwt.toString();

    assertThat(signer.verify(actual), equalTo(true));
    assertThat(actual, equalTo(expected));
    assertThat(jwt.getSignature(), equalTo(signature));
}

From source file:mitm.common.security.crl.GenerateTestCRLs.java

private PrivateKey decodePrivateKey(String encoded) throws Exception {
    byte[] rawKey = Hex.decodeHex(encoded.toCharArray());

    KeySpec keySpec = new PKCS8EncodedKeySpec(rawKey);

    KeyFactory keyFactory = securityFactory.createKeyFactory("RSA");

    return keyFactory.generatePrivate(keySpec);
}

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

/**
 * Encrypts a message./* w w w  . j av  a 2s.co  m*/
 * @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:com.ibm.dbwkl.helper.CryptionModule.java

/**
 * @return PrivateKey Instance//w  ww . j a v a2 s .  co  m
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
private RSAPrivateKey getPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] privateKeyBytes = null;
    RSAPrivateKey privateKey = null;

    privateKeyBytes = getPrivateKeyBytes();
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);

    return privateKey;
}

From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java

/**
 * Try load the keys from disk/*from   w  w w  . j  a v  a2 s.com*/
 */
public void tryLoadKeys() {
    try {
        byte[] publicBytes = Hex
                .decodeHex(new String(FileAccessUtil.readFromDisk(getKeyFilePath(false))).toCharArray());
        byte[] privateBytes = Hex
                .decodeHex(new String(FileAccessUtil.readFromDisk(getKeyFilePath(true))).toCharArray());
        KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC");
        publicKey = fact.generatePublic(new X509EncodedKeySpec(publicBytes));
        privateKey = fact.generatePrivate(new PKCS8EncodedKeySpec(privateBytes));
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException
            | DecoderException ex) {
        Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.SSLUtils.java

public static KeyStore readKeyAndCert(final String pemContent, final String keyPass)
        throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
        InvalidKeySpecException {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);//from  www.j ava  2s .c o  m

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    final List<String> lines = readLines(pemContent);

    String currentHeader = null;
    final StringBuilder current = new StringBuilder();
    final Map<String, String> entries = new LinkedHashMap<String, String>();
    for (final String line : lines) {
        if (line == null) {
            continue;
        }

        if (line.startsWith("-----BEGIN")) {
            currentHeader = line.trim();
            current.setLength(0);
        } else if (line.startsWith("-----END")) {
            entries.put(currentHeader, current.toString());
        } else {
            current.append(line.trim());
        }
    }

    final List<Certificate> certs = new ArrayList<Certificate>();
    for (int pass = 0; pass < 2; pass++) {
        for (final Map.Entry<String, String> entry : entries.entrySet()) {
            final String header = entry.getKey();
            final byte[] data = decodeBase64(entry.getValue());

            if (pass > 0 && header.contains("BEGIN PRIVATE KEY")) {
                final KeySpec spec = new PKCS8EncodedKeySpec(data);
                final PrivateKey key = keyFactory.generatePrivate(spec);
                ks.setKeyEntry("key", key, keyPass.toCharArray(), certs.toArray(new Certificate[] {}));
            } else if (pass < 1 && header.contains("BEGIN CERTIFICATE")) {
                final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data));

                ks.setCertificateEntry("certificate", c);
                certs.add(c);
            }
        }
    }

    return ks;
}