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:com.teasoft.teavote.util.Signature.java

private PublicKey getPublicKey()
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    Resource resource = res.getResource("classpath:gotaSafui");
    byte[] pubKeyBytes;
    try (InputStream pubKeyInputStream = resource.getInputStream()) {
        pubKeyBytes = IOUtils.toByteArray(pubKeyInputStream);
        pubKeyBytes = Base64.decodeBase64(pubKeyBytes);
    }/*  w  ww  .  j  a v a 2s . c o  m*/
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
    PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
    return pubKey;
}

From source file:com.alliander.osgp.shared.security.CertificateHelper.java

public static PrivateKey createPrivateKeyFromBase64(final String keyBase64, final String keyType,
        final String provider)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, NoSuchProviderException {
    final byte[] key = Base64.decodeBase64(keyBase64);

    final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory privateKeyFactory;
    privateKeyFactory = KeyFactory.getInstance(keyType, provider);
    return privateKeyFactory.generatePrivate(privateKeySpec);
}

From source file:nl.arietimmerman.u2f.server.CryptoHelper.java

/**
 * /*  w  ww.j av a2  s .  c  o  m*/
 * @param encodedPublicKey This is the (uncompressed) x,y-representation of a curve point on the P-256 NIST elliptic curve.
 * @return
 */
public static PublicKey decodePublicKey(byte[] encodedPublicKey) {
    PublicKey result = null;

    try {

        X9ECParameters curve = SECNamedCurves.getByName("secp256r1");
        ECPoint point = curve.getCurve().decodePoint(encodedPublicKey);

        result = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider()).generatePublic(new ECPublicKeySpec(
                point, new ECParameterSpec(curve.getCurve(), curve.getG(), curve.getN(), curve.getH())));

    } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return result;
}

From source file:com.streamsets.lib.security.util.DataSignature.java

public PublicKey decodePublicKey(String encodedPublicKey) throws GeneralSecurityException {
    byte[] bytes = Base64.decodeBase64(encodedPublicKey);
    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(bytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
    return keyFactory.generatePublic(pubKeySpec);
}

From source file:com.alliander.osgp.shared.security.CertificateHelper.java

public static PublicKey createPublicKeyFromBase64(final String keyBase64, final String keyType,
        final String provider)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, NoSuchProviderException {
    final byte[] key = Base64.decodeBase64(keyBase64);

    final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(key);
    final KeyFactory publicKeyFactory = KeyFactory.getInstance(keyType, provider);
    return publicKeyFactory.generatePublic(publicKeySpec);
}

From source file:cn.mrdear.pay.util.RSAUtils.java

/**
 * ?/*www . ja v a2 s.c om*/
 * 
 * @param encodedKey
 *            ?
 * @return 
 */
public static PublicKey generatePublicKey(byte[] encodedKey) {
    Assert.notNull(encodedKey);

    try {
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM, PROVIDER);
        return keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:controlador.ControlEmpleados.java

/**
 * Solicita al server la SecretKey para cifrar/descifrar el resto de la comunicacin. Primero, hace una
 * peticin http de cuya respuesta abre un InputStream y almacena el stream de bytes en un fichero binario.
 * Este fichero es la clave pblica del servidor y se utilizar para descifrar asimtricamente la segunda
 * peticin, la cual contiene un objeto SecretKey que ser el utilizado para cifrar/descifrar de manera simtrica.
 *//*from  w  w w  .  j  a v a  2  s  .  co  m*/
public void solicitarClave() {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpGet = new HttpGet(Configuration.getInstance().getServerUrl() + "/secretKey?opcion=public");
        CloseableHttpResponse response1 = httpclient.execute(httpGet,
                SessionContext.getInstance().getContext());
        try {
            HttpEntity entity1 = response1.getEntity();
            File f = new File("./server1024.publica");
            if (f.exists()) {
                f.delete();
            }
            IOUtils.copy(entity1.getContent(), new FileOutputStream(f));
        } finally {
            response1.close();
        }

        httpGet = new HttpGet(Configuration.getInstance().getServerUrl() + "/secretKey?opcion=secret");
        response1 = httpclient.execute(httpGet, SessionContext.getInstance().getContext());
        try {
            HttpEntity entity1 = response1.getEntity();
            String respuesta = EntityUtils.toString(entity1);
            byte[] clave = Base64.decodeBase64(respuesta);
            //descifro
            byte[] bufferPub = new byte[5000];
            File f = new File("server1024.publica");
            System.out.println(f.getAbsolutePath());
            FileInputStream in = new FileInputStream(f);
            int chars = in.read(bufferPub, 0, 5000);
            in.close();

            byte[] bufferPub2 = new byte[chars];
            System.arraycopy(bufferPub, 0, bufferPub2, 0, chars);

            Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

            KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC
            // 4.2 Recuperar clave publica desde datos codificados en formato X509
            X509EncodedKeySpec clavePublicaSpec = new X509EncodedKeySpec(bufferPub2);
            PublicKey clavePublica2 = keyFactoryRSA.generatePublic(clavePublicaSpec);

            cifrador.init(Cipher.DECRYPT_MODE, clavePublica2); // Descrifra con la clave privada

            byte[] claveAES = cifrador.doFinal(clave);
            SecretKey originalKey = new SecretKeySpec(claveAES, 0, claveAES.length, "AES");
            SessionContext.getInstance().setSecretKey(originalKey);

        } finally {
            response1.close();
        }

    } catch (IOException ex) {
        Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            httpclient.close();
        } catch (IOException ex) {
            Logger.getLogger(ControlEmpleados.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.ejbca.ui.cli.ca.CaImportCVCCACommand.java

public void execute(String[] args) throws ErrorAdminCommandException {
    if (args.length < 4) {
        getLogger().info("Description: " + getDescription());
        getLogger().info(//from  w w  w.j a v  a2s.  c o m
                "Usage 1: " + getCommand() + " <CA name> <pkcs8 RSA private key file> <certificate file>");
        getLogger().info(" Imports a private key and a self signed CVCA certificate and creates a CVCA.");
        getLogger().info("Usage 2: " + getCommand()
                + " <CA name> <pkcs8 private key file> <certificate file> <DN of form C=country,CN=mnemonic,SERIALNUMBER=sequence> <signatureAlgorithm> <validity days>");
        getLogger().info(
                " Imports a private key and generates a new self signed CVCA certificate with the given DN and creates a CVCA.");
        getLogger().info(
                " Signature algorithm can be SHA1WithRSA, SHA256WithRSA, SHA1WithECDSA, SHA224WithECDSA, SHA256WithECDSA, etc.");
        getLogger().info(
                " SERIALNUMBER will not be a part of the CAs DN, it is only used to set a specified sequence (should be of form 00001). Can be left out, and a random sequence is then generated.");
        return;
    }
    try {
        String caName = args[1];
        String pkFile = args[2];
        String certFile = args[3];

        // Import key and certificate
        CryptoProviderTools.installBCProvider();
        byte[] pkbytes = FileTools.readFiletoBuffer(pkFile);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkbytes);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "BC"); // Doesn't matter if we say RSA here, it will fix an EC key as well
        PrivateKey privKey = keyfact.generatePrivate(spec);

        byte[] certbytes = FileTools.readFiletoBuffer(certFile);
        Certificate cert = null;
        try {
            // First check if it was a PEM formatted certificate
            Collection<Certificate> certs = CertTools.getCertsFromPEM(new ByteArrayInputStream(certbytes));
            cert = certs.iterator().next();
        } catch (IOException e) {
            // This was not a PEM certificate, I hope it's binary...
            cert = CertTools.getCertfromByteArray(certbytes);
        }
        PublicKey pubKey = cert.getPublicKey();
        // Verify that the public and private key belongs together
        getLogger().info("Testing keys with algorithm: " + pubKey.getAlgorithm());
        KeyTools.testKey(privKey, pubKey, null);

        Certificate cacert = null;
        if (args.length > 6) {
            // Create a self signed CVCA cert from the DN
            getLogger().info("Generating new self signed certificate.");
            String dn = args[4];
            String sigAlg = args[5];
            Integer valdays = Integer.parseInt(args[6]);

            String country = CertTools.getPartFromDN(dn, "C");
            String mnemonic = CertTools.getPartFromDN(dn, "CN");
            String seq = CertTools.getPartFromDN(dn, "SERIALNUMBER");
            if (StringUtils.isEmpty(seq)) {
                seq = RandomStringUtils.randomNumeric(5);
                getLogger().info("No sequence given, using random 5 number sequence: " + seq);
            }
            HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq);
            CAReferenceField caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(),
                    holderRef.getSequence());
            AuthorizationRoleEnum authRole = AuthorizationRoleEnum.CVCA;
            Date notBefore = new Date();
            Calendar notAfter = Calendar.getInstance();
            notAfter.add(Calendar.DAY_OF_MONTH, valdays);
            CVCertificate cvc = CertificateGenerator.createCertificate(pubKey, privKey, sigAlg, caRef,
                    holderRef, authRole, AccessRightEnum.READ_ACCESS_DG3_AND_DG4, notBefore, notAfter.getTime(),
                    "BC");
            cacert = new CardVerifiableCertificate(cvc);
        } else {
            getLogger().info("Using passed in self signed certificate.");
            cacert = cert;
        }
        try {
            cacert.verify(pubKey);
        } catch (SignatureException e) {
            getLogger().info("Can not verify self signed certificate: " + e.getMessage());
            System.exit(3); // NOPMD
        }

        Certificate[] chain = new Certificate[1];
        chain[0] = cacert;
        ejb.getCAAdminSession().importCAFromKeys(getAdmin(), caName, "foo123", chain, pubKey, privKey, null,
                null);
    } catch (ErrorAdminCommandException e) {
        throw e;
    } catch (Exception e) {
        throw new ErrorAdminCommandException(e);
    }
}

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

/**
 * Encrypts a message.//from   w w  w.  jav  a2  s  . c o  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:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java

@Override
public PrivateKey loadPrivateKey(String privateKeyD) throws U2FException {
    try {//from   w w  w  .j  a  v  a2  s  .  co  m
        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);
    }
}