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:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPrivateKey.java

/**
 *
 *
 * @return/*from w ww.j av  a 2  s.  c o m*/
 */
public SshPublicKey getPublicKey() {
    try {
        DSAPublicKeySpec spec = new DSAPublicKeySpec(getY(), prvkey.getParams().getP(),
                prvkey.getParams().getQ(), prvkey.getParams().getG());

        KeyFactory kf = KeyFactory.getInstance("DSA");

        return new SshDssPublicKey((DSAPublicKey) kf.generatePublic(spec));
    } catch (Exception e) {
        return null;
    }
}

From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKey.java

protected PrivateKey getKey(String alg, byte[] data) throws GeneralSecurityException {
    if (alg.equals("RSA")) {
        try {/*from www . j  a v  a 2  s . c  o m*/
            if (data.length == 0) {
                throw new GeneralSecurityException("Cannot process empty byte stream.");
            }
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            ASN1InputStream derin = new ASN1InputStream(bis);
            ASN1Primitive keyInfo = derin.readObject();

            DERObjectIdentifier rsaOid = PKCSObjectIdentifiers.rsaEncryption;
            AlgorithmIdentifier rsa = new AlgorithmIdentifier(rsaOid);
            PrivateKeyInfo pkeyinfo = new PrivateKeyInfo(rsa, keyInfo);
            ASN1Primitive derkey = pkeyinfo.toASN1Primitive();
            byte[] keyData = BouncyCastleUtil.toByteArray(derkey);
            // The DER object needs to be mangled to
            // create a proper ProvateKeyInfo object
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyData);
            KeyFactory kfac = KeyFactory.getInstance("RSA");

            return kfac.generatePrivate(spec);
        } catch (IOException e) {
            // that should never happen
            return null;
        }

    } else {
        return null;
    }
}

From source file:de.alpharogroup.crypto.key.reader.PublicKeyReader.java

/**
 * Read public key./*ww  w  . j  a va  2  s  .c om*/
 *
 * @param publicKeyBytes
 *            the public key bytes
 * @param provider
 *            the provider
 * @param algorithm
 *            the algorithm for the {@link KeyFactory}
 * @return the public key
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PublicKey readPublicKey(final byte[] publicKeyBytes, final String provider,
        final String algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
    final KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    final PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}

From source file:info.globalbus.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*  w  ww .j  a va  2 s  . com*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

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

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test
            // validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:com.jinhe.tss.framework.license.LicenseManager.java

/**
 * <pre>/*from www .ja  v  a2 s  . c  o m*/
 * ?license??
 * ?Mac??????
 * ???????
 * </pre>
 * @param license
 * @return
 * @throws Exception
 */
boolean validate(License license) throws Exception {
    String macAddress = license.macAddress;
    if (!EasyUtils.isNullOrEmpty(macAddress)) {
        String curMacAddress = MacAddress.getMacAddress();
        if (!macAddress.equals(curMacAddress)) {
            return false;
        }
    }

    File keyFile = new File(LicenseFactory.PUBLIC_KEY_FILE);
    String publicKey = FileHelper.readFile(keyFile).trim();

    X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(EasyUtils.decodeHex(publicKey));
    KeyFactory keyFactory = KeyFactory.getInstance(LicenseFactory.KEY_ALGORITHM);
    java.security.PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

    Signature sig = Signature.getInstance(LicenseFactory.KEY_ALGORITHM);
    sig.initVerify(pubKey);
    sig.update(license.getFingerprint());
    return sig.verify(EasyUtils.decodeHex(license.licenseSignature));
}

From source file:org.javlo.external.agitos.dkim.DKIMUtil.java

public boolean checkDNSForPublickey(String signingDomain, String selector) throws DKIMSignerException {

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    String recordname = selector + "._domainkey." + signingDomain;
    String value = null;/*w w w  .  ja  va 2s  .c o m*/

    try {
        DirContext dnsContext = new InitialDirContext(env);

        javax.naming.directory.Attributes attribs = dnsContext.getAttributes(recordname,
                new String[] { "TXT" });
        javax.naming.directory.Attribute txtrecord = attribs.get("txt");

        if (txtrecord == null) {
            throw new DKIMSignerException("There is no TXT record available for " + recordname);
        }

        // "v=DKIM1; g=*; k=rsa; p=MIGfMA0G ..."
        value = (String) txtrecord.get();

    } catch (NamingException ne) {
        throw new DKIMSignerException("Selector lookup failed", ne);
    }

    if (value == null) {
        throw new DKIMSignerException("Value of RR " + recordname + " couldn't be retrieved");
    }

    // try to read public key from RR
    String[] tags = value.split(";");
    for (String tag : tags) {
        tag = tag.trim();
        if (tag.startsWith("p=")) {

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

                // decode public key, FSTODO: convert to DER format
                PKCS8EncodedKeySpec pubSpec = new PKCS8EncodedKeySpec(tag.substring(2).getBytes());
                RSAPrivateKey pubKey = (RSAPrivateKey) keyFactory.generatePublic(pubSpec);
            } catch (NoSuchAlgorithmException nsae) {
                throw new DKIMSignerException("RSA algorithm not found by JVM");
            } catch (InvalidKeySpecException ikse) {
                throw new DKIMSignerException(
                        "The public key " + tag + " in RR " + recordname + " couldn't be decoded.");
            }

            // FSTODO: create test signature with privKey and test validation with pubKey to check on a valid key pair

            return true;
        }
    }

    throw new DKIMSignerException("No public key available in " + recordname);
}

From source file:com.microsoft.azure.oidc.token.impl.SimpleTokenValidator.java

@Override
public Boolean validateSignature(final Token token) {
    if (token == null) {
        throw new PreconditionException("Required parameter is null");
    }//from  ww  w . j  av a2s . c  o  m
    if (algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName())
            .equals("HMAC")) {
        return Boolean.FALSE;
    }
    final Configuration configuration = configurationCache.load();
    if (configuration == null) {
        throw new GeneralException("Error loading configuration");
    }
    try {
        final TimeStamp now = timeStampFactory.createTimeStamp(System.currentTimeMillis() / 1000);
        if (configuration.getKey(token.getKeyName()).getNotBefore().compareTo(now) > 0) {
            return Boolean.FALSE;
        }
        final Base64 decoder = new Base64();
        final BigInteger exponent = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getExponent().getValue()));
        final BigInteger modulus = new BigInteger(1,
                decoder.decode(configuration.getKey(token.getKeyName()).getSecret().getValue()));
        final RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent);
        final KeyFactory keyFactory = KeyFactory.getInstance(
                algorithmConfigurationService.get().getAlgorithmClassMap().get(token.getAlgorithm().getName()));
        final PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        final Signature sig = Signature.getInstance(
                algorithmConfigurationService.get().getAlgorithmMap().get(token.getAlgorithm().getName()));
        sig.initVerify(pubKey);
        sig.update(token.getPayload().getValue().getBytes());
        return sig.verify(decoder.decode(token.getSignature().getValue()));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | SignatureException | InvalidKeyException e) {
        LOGGER.error(e.getMessage(), e);
        return Boolean.FALSE;
    }
}

From source file:org.javaweb.utils.RSAUtils.java

/**
 * RSA???/*from  w  ww.j  a v  a  2s  .  co  m*/
 *
 * @param data ?
 * @param key  
 * @param sign ??Base64
 * @return
 * @throws Exception
 */
public static boolean verify(byte[] data, Key key, String sign) throws Exception {
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key.getEncoded());
    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);

    return signature.verify(Base64.decodeBase64(sign));
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipClientHandler.java

public void setEncodedServerPublicKey(byte encoded[])
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException {
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(encoded);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    serverPublicKey = kf.generatePublic(x509KeySpec);
}

From source file:com.sammyun.util.RSAUtils.java

/**
 * RSA??//from  ww  w .java2 s.com
 * 
 * @param content ???
 * @return
 */
public static String encryptContent(String content, String ali_public_key) {
    try {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64Util.decode(ali_public_key);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
        signature.initVerify(pubKey);
        signature.update(content.getBytes("utf-8"));
        byte[] signed = signature.sign();
        return Base64Util.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
        return "";
    }
}