Example usage for java.security.interfaces RSAPrivateCrtKey getPublicExponent

List of usage examples for java.security.interfaces RSAPrivateCrtKey getPublicExponent

Introduction

In this page you can find the example usage for java.security.interfaces RSAPrivateCrtKey getPublicExponent.

Prototype

public BigInteger getPublicExponent();

Source Link

Document

Returns the public exponent.

Usage

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

/**
 * Generate the corresponding {@link PublicKey} object from the given {@link PrivateKey} object.
 *
 * @param privateKey//from  w  w w . j  a  va 2  s .  co 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:com.vmware.o11n.plugin.crypto.model.CryptoUtil.java

/**
 * Compute the RSA Public Key from an RSA Private Key
 *
 * @param privateKey RSA Private Key/*from www .j  av  a 2s  .c o m*/
 * @return RSA Public Key
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static RSAPublicKey getPublicFromPrivate(RSAPrivateCrtKey privateKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPublicKeySpec spec = new RSAPublicKeySpec(privateKey.getModulus(), privateKey.getPublicExponent());
    return (RSAPublicKey) getPublicKey(spec);
}

From source file:jenkins.bouncycastle.api.PEMEncodable.java

/**
 * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String}
 * //from   www .j  a  v  a  2s  .  c  o  m
 * @param pem {@link String} with the PEM data
 * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller
 * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with
 * <code>Arrays.fill(passphrase, (char)0)</code>
 * @return {@link PEMEncodable} object
 * @throws IOException launched if a problem exists reading the PEM information
 * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided
 */
@Nonnull
public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase)
        throws IOException, UnrecoverableKeyException {

    try (PEMParser parser = new PEMParser(new StringReader(pem));) {

        Object object = parser.readObject();

        JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC");

        // handle supported PEM formats.
        if (object instanceof PEMEncryptedKeyPair) {
            if (passphrase != null) {
                PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase);
                PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object;
                return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (passphrase != null) {
                InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase);
                PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object;
                return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PEMKeyPair) {
            return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object));
        } else if (object instanceof PrivateKeyInfo) {
            PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object);

            // JENKINS-35661 in this case we know how to get the public key too
            if (pk instanceof RSAPrivateCrtKey) {
                // obtain public key spec from the private key
                RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk;
                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(),
                        rsaPK.getPublicExponent());
                KeyFactory kf = KeyFactory.getInstance("RSA");
                return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK));
            }

            return new PEMEncodable(pk);
        } else if (object instanceof SubjectPublicKeyInfo) {
            return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object));
        } else if (object instanceof X509CertificateHolder) {
            JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC");
            return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object));
        } else {
            throw new IOException(
                    "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received "
                            + object.getClass().getName());
        }
    } catch (OperatorCreationException e) {
        throw new IOException(e.getMessage(), e);
    } catch (PKCSException | InvalidKeySpecException e) {
        LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e);
        throw new UnrecoverableKeyException();
    } catch (CertificateException e) {
        throw new IOException("Could not read certificate", e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(
                "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html");
    }
}

From source file:jenkins.security.RSAConfidentialKey.java

/**
 * Obtains the private key (lazily.)//from w ww .  j a v  a2  s.c o m
 * <p>
 * This method is not publicly exposed as per the design principle of {@link ConfidentialKey}.
 * Instead of exposing private key, define methods that use them in specific way, such as
 * {@link RSADigitalSignatureConfidentialKey}.
 *
 * @throws Error
 *      If key cannot be loaded for some reasons, we fail.
 */
protected synchronized RSAPrivateKey getPrivateKey() {
    try {
        if (priv == null) {
            byte[] payload = load();
            if (payload == null) {
                KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
                gen.initialize(2048, new SecureRandom()); // going beyond 2048 requires crypto extension
                KeyPair keys = gen.generateKeyPair();
                priv = (RSAPrivateKey) keys.getPrivate();
                pub = (RSAPublicKey) keys.getPublic();
                store(priv.getEncoded());
            } else {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                priv = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(payload));

                RSAPrivateCrtKey pks = (RSAPrivateCrtKey) priv;
                pub = (RSAPublicKey) keyFactory
                        .generatePublic(new RSAPublicKeySpec(pks.getModulus(), pks.getPublicExponent()));
            }
        }
        return priv;
    } catch (IOException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    } catch (GeneralSecurityException e) {
        throw new Error("Failed to load the key: " + getId(), e);
    }
}

From source file:io.kodokojo.config.module.SecurityModule.java

@Provides
@Singleton/*  www.j av  a 2 s.  c  o m*/
SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) {
    if (securityConfig == null) {
        throw new IllegalArgumentException("securityConfig must be defined.");
    }
    if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) {

        File pemFile = new File(securityConfig.wildcardPemPath());
        try {
            String content = IOUtils.toString(new FileReader(pemFile));
            String contentPrivate = RSAUtils.extractPrivateKey(content);
            String contentPublic = RSAUtils.extractPublic(content);

            RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate));
            X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic));
            RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();

            X509Certificate[] certificates = new X509Certificate[1];
            certificates[0] = certificate;
            LOGGER.info(
                    "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ",
                    certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath());
            return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e);
        }
    } else {
        try {
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")),
                    System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray());

            RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(),
                    securityConfig.sslRootCaKsPassword().toCharArray());
            if (key == null) {
                return null;
            }

            RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias());
            List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream()
                    .map(c -> (X509Certificate) c).collect(Collectors.toList());
            LOGGER.info(
                    "Using a CA SSL certificat {} from keystore  to provide Certificat to all instances of Kodo Kojo. ",
                    securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore"));
            return new SSLKeyPair(key, publicKey,
                    x509Certificates.toArray(new X509Certificate[x509Certificates.size()]));
        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
                | InvalidKeySpecException | CertificateException | IOException e) {

            throw new RuntimeException("Unable to open default Keystore", e);
        }
    }
}

From source file:org.ebayopensource.fido.uaf.crypto.KeyCodec.java

static public RSAKeyParameters generatePrivateKeyParameter(RSAPrivateKey key) {
    if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey k = (RSAPrivateCrtKey) key;
        return new RSAPrivateCrtKeyParameters(k.getModulus(), k.getPublicExponent(), k.getPrivateExponent(),
                k.getPrimeP(), k.getPrimeQ(), k.getPrimeExponentP(), k.getPrimeExponentQ(),
                k.getCrtCoefficient());/*from w  w w  .  j  av  a 2s.c  om*/
    } else {
        RSAPrivateKey k = key;
        return new RSAKeyParameters(true, k.getModulus(), k.getPrivateExponent());
    }
}

From source file:org.opensaml.xml.security.SecurityHelper.java

/**
 * Derives the public key from either a DSA or RSA private key.
 * //from w ww  . jav a2 s.co  m
 * @param key the private key to derive the public key from
 * 
 * @return the derived public key
 * 
 * @throws KeyException thrown if the given private key is not a DSA or RSA key or there is a problem generating the
 *             public key
 */
public static PublicKey derivePublicKey(PrivateKey key) throws KeyException {
    KeyFactory factory;
    if (key instanceof DSAPrivateKey) {
        DSAPrivateKey dsaKey = (DSAPrivateKey) key;
        DSAParams keyParams = dsaKey.getParams();
        BigInteger y = keyParams.getQ().modPow(dsaKey.getX(), keyParams.getP());
        DSAPublicKeySpec pubKeySpec = new DSAPublicKeySpec(y, keyParams.getP(), keyParams.getQ(),
                keyParams.getG());

        try {
            factory = KeyFactory.getInstance("DSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from DSA private key", e);
        }
    } else if (key instanceof RSAPrivateCrtKey) {
        RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaKey.getModulus(), rsaKey.getPublicExponent());

        try {
            factory = KeyFactory.getInstance("RSA");
            return factory.generatePublic(pubKeySpec);
        } catch (GeneralSecurityException e) {
            throw new KeyException("Unable to derive public key from RSA private key", e);
        }
    } else {
        throw new KeyException("Private key was not a DSA or RSA key");
    }
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Converts a given RSA PrivateKey instance to a KeyPair instance. The
 * PublicKey will be extracted from PrivateKey instance.
 * //w w  w  . j av  a  2  s . c  o  m
 * @param pKey
 *            The RSA PrivateKey used to generate the KeyPair
 * @return KeyPair instance including the private and public key.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static KeyPair privateKeyToKeyPair(PrivateKey pKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.KEY_FACTORY, new BouncyCastleProvider());
    RSAPrivateCrtKey rsaPKey = (RSAPrivateCrtKey) pKey;
    RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPKey.getModulus(),
            rsaPKey.getPublicExponent());
    return new KeyPair(keyFactory.generatePublic(publicKeySpec), pKey);
}