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:cn.lynx.emi.license.GenerateLicense.java

private static final String encrypt(String key, String data) {
    byte[] corekey = Base64.decodeBase64(key);

    PKCS8EncodedKeySpec pkspec = new PKCS8EncodedKeySpec(corekey);

    try {/*from www .  jav  a2s .  c om*/
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkspec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] encData = cipher.doFinal(data.getBytes("UTF-8"));
        System.out.println("after encrypt, len=" + encData.length);
        return Base64.encodeBase64String(encData);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.hypoport.jwt.common.Toolbox.java

public static ECPublicKey readECDHPublicKey(FileReader keyReader) throws Exception {
    return (ECPublicKey) KeyFactory.getInstance("EC")
            .generatePublic(new X509EncodedKeySpec(readPemFile(keyReader)));
}

From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * ?/*w  w  w .  jav  a 2  s.  c o  m*/
 * 
 * @param data?
 * @param key
 *            
 * @return byte[] ?
 */
public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {

    // ??
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // ??
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}

From source file:facturatron.facturacion.PAC.finkok.ClassicKeyLoader.java

/**
 * @param crtInputStream    Flujo de entrada del certificado del cual se obtiene la llave privada
 * @param passwd            Contrasea con la cual se puede obtener la informacin de la llave
 *                          privada//from  w  ww  .  ja  v a 2  s  .c o  m
 *
 * @return  Llave privada encapsulada en el objeto {@link PrivateKey}
 *
 * @throws KeyException Lanzada si existe un problema con la lectura de la llave privada. La
 *                      excepcin es lanzada si alguno de estos casos se presenta:
 *                      <ul>
 *                          <li>
 *                              Error de lectura del flujo de entrada del documento.
 *                          </li>
 *                          <li>
 *                              Error en la obtencn de la informacin de la llave privada debido
 *                              a que la contrasea no es correcta.
 *                          </li>
 *                          <li>
 *                              Error en la obtencin de la llave privada debido a que el algoritmo
 *                              de cifrado no es el adecuado para el certificado.
 *                          </li>
 *                      </ul>
 */
public static PrivateKey loadPKCS8PrivateKey(InputStream crtInputStream, String passwd) throws KeyException {
    byte[] decrypted = null;
    PrivateKey privateKey = null;

    try {
        decrypted = (passwd != null) ? getCertBytes(crtInputStream, passwd.toCharArray())
                : getBytes(crtInputStream);
    } catch (IOException ioe) {
        throw new KeyException("Error de E/S al leer la informacin del certificado", ioe.getCause());
    }

    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(decrypted);

    try {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        privateKey = kf.generatePrivate(keysp);
    } catch (GeneralSecurityException gse) {
        throw new KeyException("Error al obtener la informacin del certificado debido a su codificacin",
                gse.getCause());
    }

    return privateKey;
}

From source file:br.edu.ufcg.lsd.commune.network.signature.Util.java

public static PrivateKey decodePrivateKey(String privKeyStr) throws InvalidKeySpecException {
    byte[] binaryArray = decodeStringOnBase64(privKeyStr);
    KeyFactory keyFactory;/*from   w ww .  j av a2  s.  c o  m*/
    try {
        keyFactory = KeyFactory.getInstance(SignatureConstants.KEY_GEN_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        //We're assuming that we are always instantiating a valid algorithm
        throw new CommuneRuntimeException(e);
    }
    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(binaryArray);
    return keyFactory.generatePrivate(privateKeySpec);
}

From source file:cl.nic.dte.extension.AutorizacionTypeExtensionHandler.java

@SuppressWarnings("unchecked")
public static PublicKey getPublicKey(AutorizacionType auth)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    List<PEMItem> items = PEMUtil.decode(auth.getRSAPUBK().getBytes());

    for (PEMItem item : items) {
        if ("PUBLIC KEY".equals(item.pemType)) {
            X509EncodedKeySpec enc;
            try {
                enc = new X509EncodedKeySpec(item.getDerBytes());
                KeyFactory rsaKeyFac;
                rsaKeyFac = KeyFactory.getInstance("RSA");
                return (PublicKey) rsaKeyFac.generatePublic((enc));
            } catch (GeneralSecurityException e) {
                throw new InvalidKeySpecException(e);
            }//from w  ww  .  ja v a  2s. c o m
        }
    }
    return null;
}

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

/**
 * RSA??/*from www  .  j av  a  2  s. com*/
 * 
 * @param content
 *            ???
 * @param privateKey
 *            ?
 * @param input_charset
 *            ??
 * @return ??
 */
public static String sign(String content, String privateKey, String algorithm, String input_charset) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
        KeyFactory keyf = KeyFactory.getInstance(CODEC_RSA);
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        Signature signature = Signature.getInstance(algorithm);
        signature.initSign(priKey);
        signature.update(content.getBytes(input_charset));
        byte[] signed = signature.sign();
        return Base64Utils.base64EncodeHex(signed);
    } catch (Exception e) {
        if (LOG.isWarnEnabled())
            LOG.warn("[sign] could not sign with exception", e);
    }

    return null;
}

From source file:architecture.common.license.validator.CheckSignatureValidator.java

public void validate(License license) throws LicenseException {
    try {/*from  ww w  .  ja  va2 s.  c  o m*/
        //   DSA ? .
        String publicKey = "308201b83082012c06072a8648ce3804013082011f02818100fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b76b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c70215009760508f15230bccb292b982a2eb840bf0581cf502818100f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d0782675159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e13c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243bcca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a0381850002818100faf2d25b2866aa68501094d1097bebc95c6bcf1c58766f18b35fbf5e9d761cc5bf913447e374c21d279777859f9f043d1dc0d58b93a2081b56b4f5269a81b076907a3b11b01ec5cfde5dae4dfd7d26346e53e611235e714e69ec1bc141c77a8a28c4c799df570a4c3240e7f2fee19d6ed4caaa1b15b5da4a967ee82e3eb4d4ca";

        byte pub[] = Hex.decodeHex(publicKey.toCharArray());
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pub);

        KeyFactory keyFactory = KeyFactory.getInstance("DSA");
        java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        Signature sig = Signature.getInstance("DSA");

        sig.initVerify(pubKey);
        // license.getSignature().getBytes("UTF-8");
        byte decoded[] = Hex.decodeHex(license.getSignature().toCharArray());

        log.debug("decoded sig: " + Hex.encodeHexString(decoded));

        log.info((new StringBuilder()).append("Validating license. License fingerprint: ")
                .append(license.getSignature()).toString());

        sig.update(license.getFingerprint());

        boolean verified = sig.verify(decoded);

        if (!verified)
            throw new LicenseException("License signature is invalid.");
    } catch (Exception e) {
        log.fatal(e.getMessage(), e);
        throw new LicenseException(e);
    }
}

From source file:hh.learnj.test.license.test.rsa.RSATest.java

/**
 * ?//  w w w .j a  v a2  s.  c  o  m
 * 
 * @return
 * @throws Exception
 */
static PublicKey getPublicKey() throws Exception {
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decodeBase64(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
    return keyFactory.generatePublic(publicKeySpec);
}

From source file:cn.lynx.emi.license.ViewLicense.java

private static final String _decrypt(String data) {
    byte[] corekey = Base64.decodeBase64(LICENSE_CORE_KEY);
    byte[] rawData = Base64.decodeBase64(data);

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(corekey);
    try {//from   w  w w  .jav  a 2s  .  c  o m
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        return new String(cipher.doFinal(rawData), "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}