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:net.jmhertlein.core.crypto.Keys.java

/**
 * Loads the Base64 encoded, X509 formatted RSA public key from the file
 *
 * @param file//from  www .  j av  a 2 s  . co  m
 *
 * @return
 */
public static PublicKey loadPubKey(String file) {
    try {
        X509EncodedKeySpec spec = getX509KeySpec(file);
        if (spec == null)
            return null;
        return KeyFactory.getInstance("RSA").generatePublic(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:com.cloud.utils.security.CertificateHelper.java

public static Key buildPrivateKey(String base64EncodedKeyContent)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(Base64.decodeBase64(base64EncodedKeyContent));
    return kf.generatePrivate(keysp);
}

From source file:com.vmware.identity.rest.idm.data.PrivateKeyDTO.java

private static String encodePrivateKey(PrivateKey key)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    if (key == null) {
        return null;
    }//from www .  ja v a2 s.c  om

    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
    byte[] packed = spec.getEncoded();
    String encodePrivateKey = Base64.encodeBase64String(packed);
    Arrays.fill(packed, (byte) 0);
    return encodePrivateKey;
}

From source file:ch.cyberduck.core.aquaticprime.DictionaryLicense.java

protected void verify(final NSDictionary dictionary, final String publicKey) throws InvalidLicenseException {
    if (null == dictionary) {
        throw new InvalidLicenseException();
    }/* w ww.j a  v a 2 s  .  c  o  m*/
    final NSData signature = (NSData) dictionary.objectForKey("Signature");
    if (null == signature) {
        log.warn(String.format("Missing key 'Signature' in dictionary %s", dictionary));
        throw new InvalidLicenseException();
    }
    // Append all values
    StringBuilder values = new StringBuilder();
    final ArrayList<String> keys = new ArrayList<>(dictionary.keySet());
    // Sort lexicographically by key
    Collections.sort(keys, new NaturalOrderComparator());
    for (String key : keys) {
        if ("Signature".equals(key)) {
            continue;
        }
        values.append(dictionary.objectForKey(key).toString());
    }
    byte[] signaturebytes = signature.bytes();
    byte[] plainbytes = values.toString().getBytes(Charset.forName("UTF-8"));
    try {
        final BigInteger modulus = new BigInteger(StringUtils.removeStart(publicKey, "0x"), 16);
        final BigInteger exponent = new BigInteger(Base64.decodeBase64("Aw=="));
        final KeySpec spec = new RSAPublicKeySpec(modulus, exponent);

        final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec);
        final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(Cipher.DECRYPT_MODE, rsa);
        final MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
        if (!Arrays.equals(rsaCipher.doFinal(signaturebytes), sha1Digest.digest(plainbytes))) {
            throw new InvalidLicenseException();
        }
    } catch (NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException
            | InvalidKeySpecException | NoSuchAlgorithmException e) {
        log.warn(String.format("Signature verification failure for key %s", file));
        throw new InvalidLicenseException();
    }
    if (log.isInfoEnabled()) {
        log.info(String.format("Valid key in %s", file));
    }
}

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

/**
 * read a public key from the given text
 * /*from  w  w  w .j ava  2 s .co  m*/
 * @param keySpec
 *            the key specification.
 * @return the key or null if no key was found
 */
public SshPublicKey readPublicKey(String keySpec) {
    BufferedReader reader = new BufferedReader(new StringReader(keySpec));
    String line;
    SshPublicKey key = null;
    boolean endFound = false;
    boolean dataStarted = false;
    boolean continueHeader = false;
    String base64Data = "";
    try {
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            // skip blank lines. They shouldn't really be in there, but if they are we can ignore them.
            if (line.length() != 0) {
                if (key == null) {
                    if (line.equals(START_MARKER)) {
                        key = new SshPublicKey();
                    }
                } else {
                    if (line.equals(END_MARKER)) {
                        endFound = true;
                        break;
                    } else if (!dataStarted && (continueHeader || HEADER_PATTERN.matcher(line).matches())) {
                        // skip headers
                        continueHeader = line.endsWith("\"");
                    } else {
                        dataStarted = true;

                        base64Data += line;
                    }
                }
            }
        }
        if (!endFound) {
            key = null;
        } else {
            if (base64Data.length() > 0) {
                byte[] keyData = Base64.decodeBase64(StringUtils.getBytesUtf8(base64Data));

                Rfc4253Reader keyReader = new Rfc4253Reader(keyData, 0);
                String algorithm = keyReader.readString();
                if ("ssh-rsa".equals(algorithm)) {
                    key.setAlgorithm("RSA");

                    BigInteger exponent = keyReader.readMpint();
                    BigInteger modulus = keyReader.readMpint();

                    try {
                        KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
                        RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
                        PublicKey publicKey = keyFactory.generatePublic(rsaPublicKeySpec);

                        byte[] encoded = publicKey.getEncoded();

                        key.setKeyData(encoded);

                    } catch (InvalidKeySpecException t) {
                        getLogger().warn("Invalid key spec: " + t.getMessage(), t);
                    } catch (NoSuchAlgorithmException t) {
                        getLogger().warn("Invalid algorithm: " + t.getMessage(), t);
                    }
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    if (key == null || key.getAlgorithm() == null || key.getKeyData() == null) {
        key = null;
    }
    return key;
}

From source file:org.limewire.activation.impl.ActivationCommunicatorImpl.java

private String getEncryptedToken(String licenseId, String randomNumber) throws IOException {
    // get public key from string
    byte[] cipherData;
    byte[] keyBytes = Base64.decodeBase64(activationSettings.getServerKey().getBytes());
    try {/*from   ww  w.j ava 2 s .c  o m*/
        KeyFactory fac = KeyFactory.getInstance(ENCRYPTION_ALGORITHM);
        PublicKey publicKey = fac.generatePublic(new X509EncodedKeySpec(keyBytes));

        byte[] messageToEcrypt = StringUtils.toUTF8Bytes(licenseId + "," + randomNumber);
        cipherData = cipherProvider.encrypt(messageToEcrypt, publicKey, CIPHER_TYPE);
    } catch (GeneralSecurityException e) {
        throw IOUtils.getIOException("Security exception while initializing key", e);
    }
    String noEncoding = new String(Base64.encodeBase64(cipherData));
    return EncodingUtils.encode(noEncoding);
}

From source file:de.alpharogroup.crypto.key.PrivateKeyExtensions.java

/**
 * Generate the corresponding {@link PublicKey} object from the given {@link PrivateKey} object.
 *
 * @param privateKey/*from   www.j a  va 2  s .c  o m*/
 *            the private key
 * @return the corresponding {@link PublicKey} object or null if generation failed.
 * @throws NoSuchAlgorithmException
 *             the no such algorithm exception
 * @throws InvalidKeySpecException
 *             the invalid key spec exception
 */
public static PublicKey generatePublicKey(final PrivateKey privateKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    if (privateKey instanceof RSAPrivateKey) {
        final RSAPrivateCrtKey privk = (RSAPrivateCrtKey) privateKey;
        final RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privk.getModulus(),
                privk.getPublicExponent());

        final KeyFactory keyFactory = KeyFactory.getInstance(KeyPairGeneratorAlgorithm.RSA.getAlgorithm());
        final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
        return publicKey;
    }
    return null;
}

From source file:ch.cyberduck.core.aquaticprime.DonationKey.java

/**
 * @return True if valid license key//from  w ww. j av  a2s  . c  om
 */
@Override
public boolean verify() {
    if (null == dictionary) {
        return false;
    }
    final NSData signature = (NSData) dictionary.objectForKey("Signature");
    if (null == signature) {
        log.warn(String.format("Missing key 'Signature' in dictionary %s", dictionary));
        return false;
    }
    // Append all values
    StringBuilder values = new StringBuilder();
    final ArrayList<String> keys = new ArrayList<>(dictionary.keySet());
    // Sort lexicographically by key
    Collections.sort(keys, new NaturalOrderComparator());
    for (String key : keys) {
        if ("Signature".equals(key)) {
            continue;
        }
        values.append(dictionary.objectForKey(key).toString());
    }
    byte[] signaturebytes = signature.bytes();
    byte[] plainbytes = values.toString().getBytes(Charset.forName("UTF-8"));
    final boolean valid;
    try {
        final BigInteger modulus = new BigInteger(StringUtils.removeStart(this.getPublicKey(), "0x"), 16);
        final BigInteger exponent = new BigInteger(Base64.decodeBase64("Aw=="));
        final KeySpec spec = new RSAPublicKeySpec(modulus, exponent);

        final PublicKey rsa = KeyFactory.getInstance("RSA").generatePublic(spec);
        final Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(Cipher.DECRYPT_MODE, rsa);
        final MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
        valid = Arrays.equals(rsaCipher.doFinal(signaturebytes), sha1Digest.digest(plainbytes));
    } catch (NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidKeyException
            | InvalidKeySpecException | NoSuchAlgorithmException e) {
        log.warn(String.format("Signature verification failure for key %s", file));
        return false;
    }
    if (valid) {
        if (log.isInfoEnabled()) {
            log.info(String.format("Valid key in %s", file));
        }
    } else {
        log.warn(String.format("Not a valid key in %s", file));
    }
    return valid;
}

From source file:com.cliqset.magicsig.MagicKey.java

public PrivateKey getPrivateKey() {
    try {/*from ww  w.  j  a va 2s.  co  m*/
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory
                .generatePrivate(new RSAPrivateKeySpec(new BigInteger(1, getN()), new BigInteger(1, getD())));
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (InvalidKeySpecException ex) {
        return null;
    }
}

From source file:org.apache.kerby.pkix.PkiLoader.java

private PrivateKey doLoadPrivateKey(InputStream inputStream, String password)
        throws GeneralSecurityException, IOException {
    if (password == null) {
        password = "";
    }//from  w  ww.j  a v a2 s  . co  m
    // If the provided InputStream is encrypted, we need a password to decrypt
    // it. If the InputStream is not encrypted, then the password is ignored
    // (can be null).  The InputStream can be DER (raw ASN.1) or PEM (base64).
    PKCS8Key pkcs8 = new PKCS8Key(inputStream, password.toCharArray());

    // If an unencrypted PKCS8 key was provided, then this actually returns
    // exactly what was originally passed inputStream (with no changes).  If an OpenSSL
    // key was provided, it gets reformatted as PKCS #8 first, and so these
    // bytes will still be PKCS #8, not OpenSSL.
    byte[] decrypted = pkcs8.getDecryptedBytes();
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);

    // A Java PrivateKey object is born.
    PrivateKey pk = null;
    if (pkcs8.isDSA()) {
        pk = KeyFactory.getInstance("DSA").generatePrivate(spec);
    } else if (pkcs8.isRSA()) {
        pk = KeyFactory.getInstance("RSA").generatePrivate(spec);
    }

    // For lazier types:
    pk = pkcs8.getPrivateKey();

    return pk;
}