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, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

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

Usage

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

/**
 * Decrypts a message./* w  ww . 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:org.ejbca.core.protocol.ws.client.CvcRequestCommand.java

/**
 * Runs the command//from  www . j  a v a  2s.co m
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {
        if (args.length < 9 || args.length > 11) {
            getPrintStream().println("Number of arguments: " + args.length);
            usage();
            System.exit(-1); // NOPMD, this is not a JEE app
        }

        String username = args[ARG_USERNAME];
        String userpassword = args[ARG_PASSWORD];
        String dn = args[ARG_SUBJECTDN];
        String sequence = args[ARG_SEQUENCE];
        String signatureAlg = args[ARG_SIGNALG];
        String keySpec = args[ARG_KEYSPEC];
        boolean genrequest = args[ARG_GENREQ].equalsIgnoreCase("true");
        String basefilename = args[ARG_BASEFILENAME];
        String authSignKeyFile = null;
        if (args.length > (ARG_AUTHSIGNKEY)) {
            authSignKeyFile = args[ARG_AUTHSIGNKEY];
        }
        String authSignCertFile = null;
        if (args.length > (ARG_AUTHSIGNCERT)) {
            authSignCertFile = args[ARG_AUTHSIGNCERT];
        }

        getPrintStream().println("Enrolling user:");
        getPrintStream().println("Username: " + username);
        getPrintStream().println("Subject name: " + dn);
        getPrintStream().println("Sequence: " + sequence);
        getPrintStream().println("Signature algorithm: " + signatureAlg);
        getPrintStream().println("Key spec: " + keySpec);

        try {
            CryptoProviderTools.installBCProvider();

            String cvcreq = null;
            if (genrequest) {
                getPrintStream().println("Generating a new request with base filename: " + basefilename);
                // Generate keys for the request
                String keytype = "RSA";
                if (signatureAlg.contains("ECDSA")) {
                    keytype = "ECDSA";
                }
                KeyPair keyPair = KeyTools.genKeys(keySpec, keytype);
                String country = CertTools.getPartFromDN(dn, "C");
                String mnemonic = CertTools.getPartFromDN(dn, "CN");
                if (sequence.equalsIgnoreCase("null")) {
                    sequence = RandomStringUtils.randomNumeric(5);
                    getPrintStream().println("No sequence given, using random 5 number sequence: " + sequence);
                }
                //CAReferenceField caRef = new CAReferenceField(country,mnemonic,sequence);
                CAReferenceField caRef = null; // Don't create a caRef in the self signed request
                // We are making a self signed request, so holder ref is same as ca ref
                HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, sequence);
                CVCertificate request = CertificateGenerator.createRequest(keyPair, signatureAlg, caRef,
                        holderRef);
                byte[] der = request.getDEREncoded();
                if (authSignKeyFile != null) {
                    getPrintStream().println("Reading private key from pkcs8 file " + authSignKeyFile
                            + " to create an authenticated request");
                    byte[] keybytes = FileTools.readFiletoBuffer(authSignKeyFile);
                    KeyFactory keyfact = KeyFactory.getInstance(keytype, "BC");
                    PrivateKey privKey = keyfact.generatePrivate(new PKCS8EncodedKeySpec(keybytes));
                    KeyPair authKeyPair = new KeyPair(null, privKey); // We don't need the public key
                    // Default caRef if we do not pass in a certificate to get caRef from
                    CAReferenceField authCaRef = new CAReferenceField(country, mnemonic, sequence);
                    CVCertificate authCert = null;
                    if (authSignCertFile != null) {
                        getPrintStream().println("Reading cert from cvcert file " + authSignCertFile
                                + " to create an authenticated request");
                        CVCObject parsedObject = CvcPrintCommand.getCVCObject(authSignCertFile);
                        authCert = (CVCertificate) parsedObject;
                        String c = authCert.getCertificateBody().getHolderReference().getCountry();
                        String m = authCert.getCertificateBody().getHolderReference().getMnemonic();
                        String s = authCert.getCertificateBody().getHolderReference().getSequence();
                        authCaRef = new CAReferenceField(c, m, s);
                    }
                    CVCAuthenticatedRequest authRequest = CertificateGenerator
                            .createAuthenticatedRequest(request, authKeyPair, signatureAlg, authCaRef);
                    // Test to verify it yourself first
                    if (authCert != null) {
                        getPrintStream().println("Verifying the request before sending it...");
                        PublicKey pk = KeyTools.getECPublicKeyWithParams(
                                authCert.getCertificateBody().getPublicKey(), keySpec);
                        authRequest.verify(pk);
                    }
                    der = authRequest.getDEREncoded();
                }
                cvcreq = new String(Base64.encode(der));
                // Print the generated request to file
                FileOutputStream fos = new FileOutputStream(basefilename + ".cvreq");
                fos.write(der);
                fos.close();
                getPrintStream().println("Wrote binary request to: " + basefilename + ".cvreq");
                fos = new FileOutputStream(basefilename + ".pkcs8");
                fos.write(keyPair.getPrivate().getEncoded());
                fos.close();
                getPrintStream().println("Wrote private key in " + keyPair.getPrivate().getFormat()
                        + " format to to: " + basefilename + ".pkcs8");
            } else {
                // Read request from file
                getPrintStream().println("Reading request from filename: " + basefilename + ".cvreq");
                byte[] der = FileTools.readFiletoBuffer(basefilename + ".cvreq");
                cvcreq = new String(Base64.encode(der));
            }

            // Edit a user, creating it if it does not exist
            // Actually don't do that, leverage the existing commands and force to use the editUser command instead.
            // This also makes this CLI exactly represent the actual WS-API call 
            // getEjbcaRAWS().editUser(userdata);

            getPrintStream().println("Submitting CVC request for user '" + username + "'.");
            getPrintStream().println();
            // Use the request and request a certificate
            List<Certificate> resp = getEjbcaRAWS().cvcRequest(username, userpassword, cvcreq);

            // Handle the response
            Certificate cert = resp.get(0);
            byte[] b64cert = cert.getCertificateData();
            CVCObject parsedObject = CertificateParser.parseCertificate(Base64.decode(b64cert));
            CVCertificate cvcert = (CVCertificate) parsedObject;
            FileOutputStream fos = new FileOutputStream(basefilename + ".cvcert");
            fos.write(cvcert.getDEREncoded());
            fos.close();
            getPrintStream().println("Wrote binary certificate to: " + basefilename + ".cvcert");
            getPrintStream().println("You can look at the certificate with the command cvcwscli.sh cvcprint "
                    + basefilename + ".cvcert");
        } catch (AuthorizationDeniedException_Exception e) {
            getPrintStream().println("Error : " + e.getMessage());
        } catch (UserDoesntFullfillEndEntityProfile_Exception e) {
            getPrintStream()
                    .println("Error : Given userdata doesn't fullfill end entity profile. : " + e.getMessage());
        }

    } catch (Exception e) {
        if (e instanceof EjbcaException_Exception) {
            EjbcaException_Exception e1 = (EjbcaException_Exception) e;
            getPrintStream()
                    .println("Error code is: " + e1.getFaultInfo().getErrorCode().getInternalErrorCode());
        }
        throw new ErrorAdminCommandException(e);
    }
}

From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java

/**
 * Decode based on d - 32 byte integer/*from   w  ww. j a  va  2s . c o  m*/
 * @param privKey
 * @param curveName - Example secp256r1
 * @return
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static PrivateKey getPrivKeyFromCurve(byte[] privKey, String curveName)
        throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {

    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName);
    KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
    ECNamedCurveSpec params = new ECNamedCurveSpec(curveName, spec.getCurve(), spec.getG(), spec.getN());
    ECPrivateKeySpec priKey = new ECPrivateKeySpec(new BigInteger(privKey), // d
            params);
    return kf.generatePrivate(priKey);
}

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

public KeyPair keyPairFromJson(String keyPairJson) throws U2FException {
    BigInteger x = null;//from www.ja va  2s  . c o  m
    BigInteger y = null;
    BigInteger d = null;

    try {
        JSONObject jsonKeyPair = (JSONObject) new JSONTokener(keyPairJson).nextValue();

        JSONObject jsonPrivateKey = jsonKeyPair.getJSONObject("privateKey");
        d = new BigInteger(Utils.decodeHexString(jsonPrivateKey.getString("d")));

        JSONObject jsonPublicKey = jsonKeyPair.getJSONObject("publicKey");
        x = new BigInteger(Utils.decodeHexString(jsonPublicKey.getString("x")));
        y = new BigInteger(Utils.decodeHexString(jsonPublicKey.getString("y")));
    } catch (JSONException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    } catch (DecoderException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    }

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");

    ECCurve curve = ecSpec.getCurve();
    ECPoint validatePoint = curve.validatePoint(x, y);

    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(validatePoint, ecSpec);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(d, ecSpec);

    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance("ECDSA", BOUNCY_CASTLE_PROVIDER);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        return new KeyPair(publicKey, privateKey);
    } catch (NoSuchAlgorithmException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    } catch (InvalidKeySpecException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    }
}

From source file:info.magnolia.cms.security.SecurityUtil.java

public static String encrypt(String message, String encodedKey) {
    try {//from  ww  w  .j  a v a  2 s.c  o  m

        // read private key
        if (StringUtils.isBlank(encodedKey)) {
            throw new SecurityException(
                    "Activation key was not found. Please make sure your instance is correctly configured.");
        }
        byte[] binaryKey = hexToByteArray(encodedKey);

        // create RSA public key cipher
        Cipher pkCipher = Cipher.getInstance(ALGORITHM, "BC");
        try {
            // create private key
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PrivateKey pk = kf.generatePrivate(privateKeySpec);

            pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        } catch (InvalidKeySpecException e) {
            // encrypting with public key?
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(binaryKey);
            KeyFactory kf = KeyFactory.getInstance(ALGORITHM, "BC");
            PublicKey pk = kf.generatePublic(publicKeySpec);

            pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        }

        // encrypt
        byte[] bytes = message.getBytes("UTF-8");
        // split bit message in chunks
        int start = 0;
        StringBuilder chaos = new StringBuilder();
        while (start < bytes.length) {
            byte[] tmp = new byte[Math.min(bytes.length - start, binaryKey.length / 8)];
            System.arraycopy(bytes, start, tmp, 0, tmp.length);
            start += tmp.length;
            byte[] encrypted = pkCipher.doFinal(tmp);
            chaos.append(byteArrayToHex(encrypted));
            chaos.append(";");
        }
        chaos.setLength(chaos.length() - 1);

        return chaos.toString();

    } catch (IOException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchPaddingException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                "Failed to create authentication string. Please use Java version with cryptography support.",
                e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException(
                "Failed to find encryption provider. Please use Java version with cryptography support.", e);
    } catch (IllegalBlockSizeException e) {
        throw new SecurityException(
                "Failed to encrypt string. Please use Java version with cryptography support.", e);
    } catch (BadPaddingException e) {
        throw new SecurityException(
                "Failed to encrypt string. Please use Java version with cryptography support.", e);
    }
}

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

/**
 * Try load the keys from disk//from w  ww . j av  a2 s  . c  o  m
 */
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:com.thoughtworks.go.server.util.HttpTestUtil.java

private KeyPair generateKeyPair() {
    try {/*from ww  w  .  j  a  v  a2 s.  c o  m*/
        KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
        RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate();
        RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic();
        KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(),
                privateSeed.getPrivateExponent());
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(),
                publicSeed.getPublicExponent());
        return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRequestMessage.java

private PublicKey getPublicKey(final SubjectPublicKeyInfo subjectPKInfo, final String provider)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    try {// w w w  .  j a v  a2 s  .c  om
        final X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes());
        final AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm();
        return KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), provider).generatePublic(xspec);
    } catch (java.security.spec.InvalidKeySpecException e) {
        final InvalidKeyException newe = new InvalidKeyException("Error decoding public key.");
        newe.initCause(e);
        throw newe;
    } catch (IOException e) {
        final InvalidKeyException newe = new InvalidKeyException("Error decoding public key.");
        newe.initCause(e);
        throw newe;
    }
}

From source file:org.apache.cloudstack.utils.auth.SAMLUtils.java

public static KeyFactory getKeyFactory() {
    KeyFactory keyFactory = null;
    try {/*from   ww  w  .  j  a va 2s.  c o m*/
        Security.addProvider(new BouncyCastleProvider());
        keyFactory = KeyFactory.getInstance("RSA", "BC");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        s_logger.error("Unable to create KeyFactory:" + e.getMessage());
    }
    return keyFactory;
}

From source file:org.codice.ddf.security.certificate.generator.PkiTools.java

static KeyFactory getRsaKeyFactory() throws GeneralSecurityException {
    return KeyFactory.getInstance(ALGORITHM, BouncyCastleProvider.PROVIDER_NAME);
}