Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

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

Prototype

public PublicKey getPublic() 

Source Link

Document

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

Usage

From source file:org.umit.icm.mobile.utils.ProfilerRun.java

private static void profileRSADecrypt() {
    Profiler profiler = new Profiler();
    profiler.runProfiler(new TaskInterface() {
        public void task() {
            try {
                KeyPair keyPair = RSACrypto.generateKey();
                String cipherText = RSACrypto.encryptPublic(keyPair.getPublic(), "This is a test string");
                RSACrypto.decryptPrivate(keyPair.getPrivate(), cipherText);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from w  w  w .  jav a  2s .co  m
            }
        }

        public String taskName() {
            return "RSA Public Decryption";
        }
    });
}

From source file:cl.nic.dte.util.XMLUtil.java

public static AUTORIZACIONDocument generateAuthorization(AUTORIZACIONDocument template, PrivateKey pKey)
        throws NoSuchAlgorithmException, SignatureException, TransformerException, InvalidKeyException,
        IOException {// ww  w  .j a v  a  2 s .  c  o m
    // Generation of keys

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();

    CAFType caf = template.getAUTORIZACION().getCAF();
    CAFType.DA.RSAPK rsapk = caf.getDA().addNewRSAPK();

    rsapk.setM(((RSAPublicKey) kp.getPublic()).getModulus().toByteArray());
    rsapk.setE(((RSAPublicKey) kp.getPublic()).getPublicExponent().toByteArray());

    ResourceBundle labels = ResourceBundle.getBundle("cl.nic.dte.resources.VerifyResults");

    Signature sig = null;
    if (pKey.getAlgorithm().equals("RSA")) {
        sig = Signature.getInstance("SHA1withRSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withRSA");
    } else if (pKey.getAlgorithm().equals("DSA")) {
        sig = Signature.getInstance("SHA1withDSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withDSA");
    } else {
        throw new NoSuchAlgorithmException(
                labels.getString("ALGORITHM_NOT_SUPPORTED").replaceAll("%1", pKey.getAlgorithm()));
    }

    template.getAUTORIZACION()
            .setRSASK("-----BEGIN RSA PRIVATE KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPrivate().getEncoded(), true))
                    + "-----END RSA PRIVATE KEY-----\n");

    template.getAUTORIZACION()
            .setRSAPUBK("-----BEGIN RSA PUBLIC KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPublic().getEncoded(), true))
                    + "-----END RSA PUBLIC KEY-----\n");

    sig.initSign(pKey);
    sig.update(XMLUtil.getCleaned(caf.getDA()));

    caf.getFRMA().setByteArrayValue(Base64.encodeBase64(sig.sign()));
    return template;
}

From source file:org.wso2.emm.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *///from  w  ww  . ja va 2s . c o  m
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.emm.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException e) {
                        Log.e(TAG, e.getMessage());
                    } catch (KeyStoreException e) {
                        e.printStackTrace();
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }

    }

}

From source file:com.ligadata.EncryptUtils.EncryptionUtil.java

/**
 * Generate key which contains a pair of private and public key using 1024
 * bytes. Store the set of keys in given files publicKeyFile,privateKeyFile
 * @param algorithm//  w  w w  .j a  va 2  s. c  om
 *          : algorithm used
 * @param publicKeyFile
 *          :The file containing public key
 * @param privateKeyFile
 *          :The file containing private key
 */
public static void generateSampleKeys(String algorithm, String publicKeyFile, String privateKeyFile) {
    try {
        if (areKeysPresent(publicKeyFile, privateKeyFile)) {
            return;
        }
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
        keyGen.initialize(1024);
        final KeyPair key = keyGen.generateKeyPair();

        File privateKeyFD = new File(privateKeyFile);
        File publicKeyFD = new File(publicKeyFile);

        // Create files to store public and private key
        if (privateKeyFD.getParentFile() != null) {
            privateKeyFD.getParentFile().mkdirs();
        }
        privateKeyFD.createNewFile();

        if (publicKeyFD.getParentFile() != null) {
            publicKeyFD.getParentFile().mkdirs();
        }
        publicKeyFD.createNewFile();

        // Saving the Public key in a file
        ObjectOutputStream publicKeyOS = new ObjectOutputStream(new FileOutputStream(publicKeyFD));
        publicKeyOS.writeObject(key.getPublic());
        publicKeyOS.close();

        // Saving the Private key in a file
        ObjectOutputStream privateKeyOS = new ObjectOutputStream(new FileOutputStream(privateKeyFD));
        privateKeyOS.writeObject(key.getPrivate());
        privateKeyOS.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:bftsmart.tom.util.RSAKeyPairGenerator.java

/**
 * Generate the key pair for the process with id = <id> and put it on the
 * files config/keys/publickey<id> and config/keys/privatekey<id>
 *
 * @param id the id of the process to generate key
 * @throws Exception something goes wrong when writing the files
 *//*from w  w  w . ja  va2s .  c  o  m*/
public void run(int id, int size) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(size);
    KeyPair kp = keyGen.generateKeyPair();
    PublicKey puk = kp.getPublic();
    PrivateKey prk = kp.getPrivate();
    saveToFile(id, puk, prk);
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 *///from  w ww. java  2 s .co m
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn,
        String signingAlgorithm, int certificateDurationDays) throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)),
                getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);

        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                        | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign
                        | KeyUsage.keyCertSign));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(
                new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));

        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}

From source file:org.umit.icm.mobile.utils.ProfilerRun.java

private static void profileRSAPrivateDecrypt() {
    Profiler profiler = new Profiler();
    profiler.runProfiler(new TaskInterface() {
        public void task() {
            try {
                KeyPair keyPair = RSACrypto.generateKey();
                String cipherText = RSACrypto.encryptPrivate(keyPair.getPrivate(), "This is a test string");
                RSACrypto.decryptPublic(keyPair.getPublic(), cipherText);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from ww  w  .j a  va 2 s.c  o  m
            }
        }

        public String taskName() {
            return "RSA Private Decryption";
        }
    });
}

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

public static X509Certificate generateCertificate(String domain, int days, KeyPair keyPair)
        throws GeneralSecurityException, IOException {
    X509CertInfo info = new X509CertInfo();
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000l);
    CertificateValidity interval = new CertificateValidity(from, to);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X500Name owner = new X500Name("DC=" + domain);

    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));

    AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));

    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(keyPair.getPrivate(), "MD5WithRSA");

    return cert;//from  w  w w  .ja v  a 2  s .c o  m
}

From source file:org.apache.cloudstack.utils.auth.SAMLUtils.java

public static X509Certificate generateRandomX509Certificate(KeyPair keyPair) throws NoSuchAlgorithmException,
        NoSuchProviderException, CertificateEncodingException, SignatureException, InvalidKeyException {
    Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    Date validityEndDate = new Date(System.currentTimeMillis() + 3 * 365 * 24 * 60 * 60 * 1000);
    X500Principal dnName = new X500Principal("CN=ApacheCloudStack");
    X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setSubjectDN(dnName);/*from   www .j  a  v  a  2  s . c o  m*/
    certGen.setIssuerDN(dnName);
    certGen.setNotBefore(validityBeginDate);
    certGen.setNotAfter(validityEndDate);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    return certGen.generate(keyPair.getPrivate(), "BC");
}

From source file:info.fcrp.keepitsafe.bean.UserBeanTest.java

private String generatePublicKey() throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubKey = kp.getPublic();

    return Base64.encodeBase64String(pubKey.getEncoded());
}