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.orbeon.oxf.processor.SignatureVerifierProcessor.java

public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(SignatureVerifierProcessor.this, name) {
        public void readImpl(PipelineContext context, final XMLReceiver xmlReceiver) {
            try {
                final Document pubDoc = readCacheInputAsDOM4J(context, INPUT_PUBLIC_KEY);
                final String pubString = XPathUtils.selectStringValueNormalize(pubDoc, "/public-key");
                final byte[] pubBytes = Base64.decode(pubString);
                final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("DSA");
                final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

                final Signature dsa = Signature.getInstance("SHA1withDSA");
                dsa.initVerify(pubKey);/*from  w  ww . j a  v a 2  s . co m*/

                final Document data = readInputAsDOM4J(context, INPUT_DATA);
                final Node sigDataNode = data.selectSingleNode("/signed-data/data/*");
                final String sig = StringUtils
                        .trimToEmpty(XPathUtils.selectStringValue(data, "/signed-data/signature"));

                sigDataNode.detach();
                final Document sigData = new NonLazyUserDataDocument();
                sigData.add(sigDataNode);

                dsa.update(Dom4jUtils.domToString(sigData).getBytes("utf-8"));

                // Verify signature and throw in case of failure
                try {
                    if (!dsa.verify(Base64.decode(sig)))
                        throw new OXFException("Signature verification failed");
                } catch (SignatureException e) {
                    throw e;
                } catch (Exception e) {
                    // A number of things can fail above, including Base64 decoding
                    // NOTE: We don't pas the cause so that we can match on SignatureException as root Exception
                    throw new SignatureException("Signature verification failed");
                }

                // Signature verification passed
                final LocationSAXWriter saw = new LocationSAXWriter();
                saw.setContentHandler(xmlReceiver);
                saw.write(sigData);
            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:cn.util.RSAUtils.java

/**
 * ?RSA?/* w w w.j  a v a2  s .  c o m*/
 * ?????RSA/None/PKCS1Padding??JDK?????AndroidRSA
 * /None/NoPadding
 * 
 * @param modulus
 *            
 * @param exponent
 *            
 * @return
 */
public static RSAPrivateKey getPrivateKey() {

    try {
        return (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(privateKeyData));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.apache.cordova.crypt.Crypt.java

public String encrypt(String data, String publickey) throws Exception {
    publickey = publickey.replaceAll("(-+BEGIN PUBLIC KEY-+\\r?\\n|-+END PUBLIC KEY-+\\r?\\n?)", "");

    try {//from  w ww. ja va2s.  co  m
        byte[] publickeyRaw = Base64.decode(publickey, Base64.DEFAULT);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publickeyRaw);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pub = fact.generatePublic(keySpec);

        byte[] text = data.getBytes(Charset.forName("UTF-8"));

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pub);
        byte[] cipherString = cipher.doFinal(text);

        return new String(Base64.encode(cipherString, Base64.DEFAULT));

    } catch (Exception e) {
        Log.w("Crypt", e);
        return null;
    }
}

From source file:license.TestWakeLicense.java

/**
 * ?//from  www  .  j ava2 s .  co  m
 * @return
 * @throws Exception
 */
static PublicKey readPublicKeyFromFile() throws Exception {
    ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(KeyData.publicKey));
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        return fact.generatePublic(keySpec);
    } finally {
        oin.close();
    }
}

From source file:com.tasktop.c2c.server.internal.profile.crypto.OpenSSHPublicKeyReader.java

public SshPublicKey readPublicKey(String keySpec) {
    keySpec = keySpec.trim();/*from  w w w .j  a  v  a 2s .com*/
    String[] parts = keySpec.split(" ");
    if (parts.length >= 2) {
        String algorithm = parts[0];
        String base64Data = parts[1];
        if (algorithm.equals("ssh-rsa")) {
            SshPublicKey sshPublicKey = new SshPublicKey();
            sshPublicKey.setAlgorithm("RSA");
            byte[] decodedData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data));

            Rfc4253Reader reader = new Rfc4253Reader(decodedData, 0);

            try {
                byte[] format = reader.readBytes();
                byte[] exponent = reader.readBytes();
                byte[] modulus = reader.readBytes();

                if (Arrays.equals(FORMAT, format)) {
                    BigInteger exp = new BigInteger(exponent);
                    BigInteger mod = new BigInteger(modulus);
                    RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(mod, exp);
                    try {
                        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(rsaPublicKeySpec);
                        sshPublicKey.setKeyData(publicKey.getEncoded());
                        return sshPublicKey;
                    } catch (InvalidKeySpecException t) {
                        getLogger().warn("Invalid key spec: " + t.getMessage(), t);
                    } catch (NoSuchAlgorithmException t) {
                        getLogger().warn("Invalid algorithm: " + t.getMessage(), t);
                    }
                }

            } catch (IOException e) {
                // ignore
            }
        }
    }
    return null;
}

From source file:com.teasoft.teavote.util.Signature.java

private PrivateKey getPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Resource resource = res.getResource("classpath:xormeSafui");
    byte[] privKeyBytes;
    try (InputStream privKeyInputStream = resource.getInputStream()) {
        privKeyBytes = IOUtils.toByteArray(privKeyInputStream);
        privKeyBytes = Base64.decodeBase64(privKeyBytes);
    }//from  w  w  w .  j  a  v a 2 s  .  co m
    PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
    return privKey;
}

From source file:com.jaspersoft.jasperserver.jaxrs.client.core.EncryptionUtils.java

private static PublicKey getPublicKey(String n, String e) throws Exception {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    int radix = 16;
    BigInteger modulus = new BigInteger(n, radix);
    BigInteger publicExponent = new BigInteger(e, radix);
    RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(modulus, publicExponent);
    return keyFactory.generatePublic(publicKeySpec);
}

From source file:fr.mby.saml2.sp.impl.helper.SecurityHelper.java

/**
 * Build a private Key from DER resource.
 * //from   ww  w  . j a  v a 2 s .  c  om
 * @param certificate
 *            the DER resource
 * @param pkSpecClass
 *            the java key specification class
 * @param type
 *            the certificate type
 * @return the java.security.cert.Certificate
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws IllegalArgumentException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws IOException
 */
public static PrivateKey buildPrivateKey(final Resource privateKey, final Class<EncodedKeySpec> pkSpecClass,
        final String type) throws SecurityException, NoSuchMethodException, IllegalArgumentException,
        InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchAlgorithmException,
        InvalidKeySpecException, IOException {
    PrivateKey result = null;

    final Constructor<EncodedKeySpec> keySpecConstructor = pkSpecClass.getConstructor(byte[].class);
    final byte[] keyBytes = SecurityHelper.readBytesFromFilePath(privateKey);
    if (keyBytes != null) {
        final EncodedKeySpec keySpec = keySpecConstructor.newInstance(keyBytes);
        final KeyFactory pkFactory = KeyFactory.getInstance(type);
        result = pkFactory.generatePrivate(keySpec);
    }

    return result;
}

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

/**
 * Creates a new private and public key and at the same time encodes the public key as XML to be used by the .NET client
 * @param size/*www.  j av a2  s.  co m*/
 * @param productId
 *
 */
private void firstTimeInitialisation(int size) {
    try {

        // Get Key Pair Generator for RSA.
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(size);

        KeyPair keypair = keyGen.genKeyPair();
        privateKey = keypair.getPrivate();
        publicKey = keypair.getPublic();

        // Get the bytes of the public and private keys
        byte[] privateKeyBytes = privateKey.getEncoded();
        byte[] publicKeyBytes = publicKey.getEncoded();

        // store temporarily witht he public key for the lifetime of this class.
        encodedPrivateKey = new Base64().encode(privateKeyBytes);

        // Generate the Private Key, Public Key and Public Key in XML format.
        KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(publicKeyBytes));

        // Store the public key in XML string to make compatible .Net public key file
        encodedToXMLPublicKey = getRSAPublicKeyAsXMLString(rsaPublicKey);

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:nl.surfnet.spring.security.opensaml.util.KeyStoreUtil.java

/**
 * Append a certificate and private key to a keystore.
 *
 * @param keyStore        where to append the certificate and private key to
 * @param keyAlias        the alias of the key
 * @param certificateInputStream the inputStream containing the certificate in the PEM format
 * @param privatekeyInputStream  the input stream containing the private key in the DER format
 * @param password        the password on the key
 *                        <p/>//from   w  ww . j a va2 s . com
 *                        Generate your private key: openssl genrsa -out something.key 1024
 *                        <p/>
 *                        Show the PEM private key: openssl asn1parse -inform pem -dump -i
 *                        -in something.key
 *                        <p/>
 *                        Translate the key to pkcs8 DER format: openssl pkcs8 -topk8
 *                        -inform PEM -outform DER -in something.key -nocrypt >
 *                        something.pkcs8.der
 *                        <p/>
 *                        Show the DER private key: openssl asn1parse -inform der -dump -i
 *                        -in something.pkcs8.der
 *                        <p/>
 *                        Generate a certificate request: openssl req -new -key
 *                        something.key -out something.csr
 *                        <p/>
 *                        Generate a certificate: openssl x509 -req -days 365 -in
 *                        something.csr -signkey something.key -out something.crt
 */

public static void appendKeyToKeyStore(KeyStore keyStore, String keyAlias, InputStream certificateInputStream,
        InputStream privatekeyInputStream, char[] password) throws IOException {

    CertificateFactory certFact;
    Certificate cert;
    try {
        certFact = CertificateFactory.getInstance("X.509");
        cert = certFact.generateCertificate(certificateInputStream);
    } catch (CertificateException e) {
        throw new RuntimeException("Could not instantiate cert", e);
    }
    ArrayList<Certificate> certs = new ArrayList<Certificate>();
    certs.add(cert);

    byte[] privKeyBytes = IOUtils.toByteArray(privatekeyInputStream);

    try {
        KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
        RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(ks);
        keyStore.setKeyEntry(keyAlias, privKey, password, certs.toArray(new Certificate[certs.size()]));
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}