Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

In this page you can find the example usage for java.security KeyPair getPrivate.

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static Properties getProperties(File properties, File keystore) {
    Properties props = new Properties();
    if (!properties.exists())
        return props;

    InputStream stream = null;//from  w w  w . ja  v  a2  s .c o  m
    try {
        byte[] bytes = FileUtils.readFileToByteArray(properties);
        stream = new ByteArrayInputStream(bytes);
        if (keystore.exists()) {
            KeyPair keyPair = load(keystore);
            try {
                byte[] decrypt = decrypt(keyPair.getPrivate(), bytes);
                stream = new ByteArrayInputStream(decrypt);
            } catch (Exception e) {
                logger.trace(e);
            }
        }
        props.load(stream);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(stream);
    }

    return props;
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * ?//from   w ww  .j  a  v a  2 s . c o  m
 *
 * @return Map Map
 * @throws Exception
 */
public static Map<String, String> initKey(UUID licenseCode) throws Exception {
    // ?
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

    // ??
    //        keyPairGen.initialize(KEY_SIZE);
    keyPairGen.initialize(KEY_SIZE, new SecureRandom(licenseCode.toString().getBytes(UTF_8)));

    // ?
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // 
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    // ?
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    // ?
    Map<String, String> keyMap = new HashMap<String, String>();

    keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
    keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
    keyMap.put(LICENSE_CODE, licenseCode.toString());

    return keyMap;
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

private static KeyPair createKeyFile(String filename)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
    keyGenerator.initialize(2048, new SecureRandom());
    KeyPair myKeyPair = keyGenerator.generateKeyPair();

    PublicKey publicKey = myKeyPair.getPublic();
    PrivateKey privateKey = myKeyPair.getPrivate();

    System.out.println("keys created... " + filename);

    saveKeyPair(filename, myKeyPair);//from  w  w w  . j  av a  2  s .  c  om
    return myKeyPair;
}

From source file:net.link.util.test.pkix.PkiTestUtils.java

public static X509Certificate generateTestSelfSignedCert(@Nullable URI ocspUri) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, IOException, OperatorCreationException, CertificateException {

    KeyPair keyPair = generateKeyPair();
    DateTime now = new DateTime();
    DateTime notBefore = now.minusDays(1);
    DateTime notAfter = now.plusDays(1);
    return generateCertificate(keyPair.getPublic(), "CN=Test", keyPair.getPrivate(), null, notBefore, notAfter,
            null, true, true, false, ocspUri);
}

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

/**
 * ?/*from  w w w  . j  a va 2 s  . c om*/
 * 
 * @throws Exception
 */
static void generatorKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM_RSA);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
    byte[] keyBs = rsaPublicKey.getEncoded();
    publicKey = encodeBase64(keyBs);
    System.out.println("?\r\n" + publicKey);
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    keyBs = rsaPrivateKey.getEncoded();
    privateKey = encodeBase64(keyBs);
    System.out.println("??\r\n" + privateKey);
}

From source file:com.github.aynu.mosir.core.standard.util.SecurityHelper.java

/**
 * RSA???//from  www.ja  v  a2  s . c om
 * <dl>
 * <dt>?
 * <dd>RSA??????2048??????
 * </dl>
 * @return RSA?
 */
public static KeyPair createKeyPair() {
    try {
        final KeyPairGenerator generator = KeyPairGenerator.getInstance(ALGO_KEY);
        generator.initialize(2048);
        final KeyPair pair = generator.generateKeyPair();
        if (LOG.isDebugEnabled()) {
            final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();
            final RSAPrivateKey privateKey = (RSAPrivateKey) pair.getPrivate();
            LOG.debug("public-modulus={}", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
            LOG.debug("public-exponent={}",
                    Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
            LOG.debug("private-modulus={}", Base64.encodeBase64String(privateKey.getModulus().toByteArray()));
            LOG.debug("private-exponent={}",
                    Base64.encodeBase64String(privateKey.getPrivateExponent().toByteArray()));
        }
        return pair;
    } catch (final NoSuchAlgorithmException e) {
        throw new StandardRuntimeException(e);
    }
}

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>// w w  w .  ja va2s .  co  m
 * ?(?)
 * </p>
 * 
 * @return Map<String, Object>
 * @throws Exception Exception
 */
public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    Map<String, Object> keyMap = new HashMap<String, Object>(2);
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}

From source file:io.vertx.config.vault.utils.Certificates.java

/**
 * Called by the constructor method prior to configuring and launching the Vault instance.  Uses Bouncy Castle
 * (https://www.bouncycastle.org) to programmatically generate a private key and X509 certificate for use by
 * the Vault server instance in accepting SSL connections.
 *///from  w  w w.  j  a  v a2s . co  m
public static void createVaultCertAndKey() throws Exception {
    if (SSL_DIRECTORY.isDirectory() && CERT_PEMFILE.isFile()) {
        try (FileInputStream fis = new FileInputStream(CERT_PEMFILE)) {
            CertificateFactory fact = CertificateFactory.getInstance("X.509");
            vaultCertificate = (X509Certificate) fact.generateCertificate(fis);
        }
        return;
    }

    SSL_DIRECTORY.mkdirs();

    // Generate a certificate and private key for Vault, and write them to disk in PEM format.  Also store the
    // original X509Certificate object in a member variable, so it can later be used by "createClientCertAndKey()".
    final KeyPair keyPair = generateKeyPair();
    vaultCertificate = generateCert(keyPair,
            "C=AU, O=The Legion of the Bouncy Castle, OU=Vault Server Certificate, CN=localhost");
    writeCertToPem(vaultCertificate, CERT_PEMFILE);
    writePrivateKeyToPem(keyPair.getPrivate(), PRIVATE_KEY_PEMFILE);
}

From source file:Main.java

/**
 * save private key and public key of a keypair in the directory
 *
 * @param dir/*from ww w .  java  2s .c  om*/
 * @param keyPair
 * @param name keys will be stored as name_private.key and name_public.key
 * @throws IOException
 */
public static void saveKeyPair(File dir, KeyPair keyPair, String name) throws IOException {

    // Store Public Key.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());
    FileOutputStream fos = new FileOutputStream(new File(dir, name + "_public.key"));
    fos.write(x509EncodedKeySpec.getEncoded());
    fos.close();

    // Store Private Key.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());
    fos = new FileOutputStream(new File(dir, name + "_private.key"));
    fos.write(pkcs8EncodedKeySpec.getEncoded());
    fos.close();
}

From source file:org.apache.hadoop.gateway.services.security.impl.X509CertificateUtil.java

/**
 * Create a self-signed X.509 Certificate
 * @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair the KeyPair//ww w .  j  a  va 2s. c o  m
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
        throws GeneralSecurityException, IOException {

    PrivateKey privkey = pair.getPrivate();
    Object x509CertImplObject = null;
    try {
        Date from = new Date();
        Date to = new Date(from.getTime() + days * 86400000l);

        Class<?> certInfoClass = Class.forName(getX509CertInfoModuleName());
        Constructor<?> certInfoConstr = certInfoClass.getConstructor();
        Object certInfoObject = certInfoConstr.newInstance();

        // CertificateValidity interval = new CertificateValidity(from, to);
        Class<?> certValidityClass = Class.forName(getX509CertifValidityModuleName());
        Constructor<?> certValidityConstr = certValidityClass
                .getConstructor(new Class[] { Date.class, Date.class });
        Object certValidityObject = certValidityConstr.newInstance(from, to);

        BigInteger sn = new BigInteger(64, new SecureRandom());

        // X500Name owner = new X500Name(dn);
        Class<?> x500NameClass = Class.forName(getX509X500NameModuleName());
        Constructor<?> x500NameConstr = x500NameClass.getConstructor(new Class[] { String.class });
        Object x500NameObject = x500NameConstr.newInstance(dn);

        Method methodSET = certInfoObject.getClass().getMethod("set", String.class, Object.class);

        // info.set(X509CertInfo.VALIDITY, interval);
        methodSET.invoke(certInfoObject, getSetField(certInfoObject, "VALIDITY"), certValidityObject);

        // info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
        Class<?> certificateSerialNumberClass = Class.forName(getCertificateSerialNumberModuleName());
        Constructor<?> certificateSerialNumberConstr = certificateSerialNumberClass
                .getConstructor(new Class[] { BigInteger.class });
        Object certificateSerialNumberObject = certificateSerialNumberConstr.newInstance(sn);
        methodSET.invoke(certInfoObject, getSetField(certInfoObject, "SERIAL_NUMBER"),
                certificateSerialNumberObject);

        // info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
        try {
            Class<?> certificateSubjectNameClass = Class.forName(getCertificateSubjectNameModuleName());
            Constructor<?> certificateSubjectNameConstr = certificateSubjectNameClass
                    .getConstructor(new Class[] { x500NameClass });
            Object certificateSubjectNameObject = certificateSubjectNameConstr.newInstance(x500NameObject);
            methodSET.invoke(certInfoObject, getSetField(certInfoObject, "SUBJECT"),
                    certificateSubjectNameObject);
        } catch (InvocationTargetException ite) {
            methodSET.invoke(certInfoObject, getSetField(certInfoObject, "SUBJECT"), x500NameObject);
        }

        // info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
        try {
            Class<?> certificateIssuerNameClass = Class.forName(getCertificateIssuerNameModuleName());
            Constructor<?> certificateIssuerNameConstr = certificateIssuerNameClass
                    .getConstructor(new Class[] { x500NameClass });
            Object certificateIssuerNameObject = certificateIssuerNameConstr.newInstance(x500NameObject);
            methodSET.invoke(certInfoObject, getSetField(certInfoObject, "ISSUER"),
                    certificateIssuerNameObject);
        } catch (InvocationTargetException ite) {
            methodSET.invoke(certInfoObject, getSetField(certInfoObject, "ISSUER"), x500NameObject);
        }

        // info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
        Class<?> certificateX509KeyClass = Class.forName(getCertificateX509KeyModuleName());
        Constructor<?> certificateX509KeyConstr = certificateX509KeyClass
                .getConstructor(new Class[] { PublicKey.class });
        Object certificateX509KeyObject = certificateX509KeyConstr.newInstance(pair.getPublic());
        methodSET.invoke(certInfoObject, getSetField(certInfoObject, "KEY"), certificateX509KeyObject);
        // info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
        Class<?> certificateVersionClass = Class.forName(getCertificateVersionModuleName());
        Constructor<?> certificateVersionConstr = certificateVersionClass
                .getConstructor(new Class[] { int.class });
        Constructor<?> certificateVersionConstr0 = certificateVersionClass.getConstructor();
        Object certInfoObject0 = certificateVersionConstr0.newInstance();
        Field v3IntField = certInfoObject0.getClass().getDeclaredField("V3");
        v3IntField.setAccessible(true);
        int fValue = (int) v3IntField.getInt(certInfoObject0);
        Object certificateVersionObject = certificateVersionConstr.newInstance(fValue);
        methodSET.invoke(certInfoObject, getSetField(certInfoObject, "VERSION"), certificateVersionObject);

        // AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
        Class<?> algorithmIdClass = Class.forName(getAlgorithmIdModuleName());
        Field md5WithRSAField = algorithmIdClass.getDeclaredField("md5WithRSAEncryption_oid");
        md5WithRSAField.setAccessible(true);
        Class<?> objectIdentifierClass = Class.forName(getObjectIdentifierModuleName());

        Object md5WithRSAValue = md5WithRSAField.get(algorithmIdClass);

        Constructor<?> algorithmIdConstr = algorithmIdClass
                .getConstructor(new Class[] { objectIdentifierClass });
        Object algorithmIdObject = algorithmIdConstr.newInstance(md5WithRSAValue);

        // info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
        Class<?> certificateAlgorithmIdClass = Class.forName(getCertificateAlgorithmIdModuleName());
        Constructor<?> certificateAlgorithmIdConstr = certificateAlgorithmIdClass
                .getConstructor(new Class[] { algorithmIdClass });
        Object certificateAlgorithmIdObject = certificateAlgorithmIdConstr.newInstance(algorithmIdObject);
        methodSET.invoke(certInfoObject, getSetField(certInfoObject, "ALGORITHM_ID"),
                certificateAlgorithmIdObject);

        // Sign the cert to identify the algorithm that's used.
        // X509CertImpl cert = new X509CertImpl(info);
        Class<?> x509CertImplClass = Class.forName(getX509CertImplModuleName());
        Constructor<?> x509CertImplConstr = x509CertImplClass.getConstructor(new Class[] { certInfoClass });
        x509CertImplObject = x509CertImplConstr.newInstance(certInfoObject);

        // cert.sign(privkey, algorithm);
        Method methoSIGN = x509CertImplObject.getClass().getMethod("sign", PrivateKey.class, String.class);
        methoSIGN.invoke(x509CertImplObject, privkey, algorithm);

        // Update the algorith, and resign.
        // algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
        Method methoGET = x509CertImplObject.getClass().getMethod("get", String.class);
        String sig_alg = getSetField(x509CertImplObject, "SIG_ALG");

        String certAlgoIdNameValue = getSetField(certificateAlgorithmIdObject, "NAME");
        String certAlgoIdAlgoValue = getSetField(certificateAlgorithmIdObject, "ALGORITHM");
        // info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
        methodSET.invoke(certInfoObject, certAlgoIdNameValue + "." + certAlgoIdAlgoValue,
                methoGET.invoke(x509CertImplObject, sig_alg));

        // cert = new X509CertImpl(info);
        x509CertImplObject = x509CertImplConstr.newInstance(certInfoObject);
        // cert.sign(privkey, algorithm);
        methoSIGN.invoke(x509CertImplObject, privkey, algorithm);
    } catch (Exception e) {
        LOG.failedToGenerateCertificate(e);
    }
    return (X509Certificate) x509CertImplObject;
}