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.gluu.oxtrust.action.ManageCertificateAction.java

@Restrict("#{s:hasPermission('configuration', 'access')}")
public boolean compare(String fileName) {
    KeyPair pair = getKeyPair(fileName);
    X509Certificate cert = sslService.getCertificate(getTempCertDir() + fileName);

    boolean noFilesPresent = (pair == null) && (cert == null);

    boolean filesPresent = (pair != null) && (cert != null);
    boolean filesValid = false;
    if (filesPresent) {
        filesValid = (pair.getPublic() != null) && (pair.getPublic().equals(cert.getPublicKey()));
    }//from  w ww  .  jav  a2s . co m

    boolean compareResult = (noFilesPresent || (filesPresent && filesValid));
    log.debug(fileName + " compare result: " + compareResult);
    return compareResult;
}

From source file:org.texai.x509.X509Utils.java

/** Initializes the installer keystore on the trusted development system, from where it is copied into the distributed code. */
public static synchronized void initializeInstallerKeyStore() {
    if (!X509Utils.isTrustedDevelopmentSystem()) {
        return;/*  w  ww  .j a  va2  s.  c o m*/
    }
    String filePath = "data/installer-keystore.uber";
    File file = new File(filePath);
    if (file.exists()) {
        // do not overwrite it
        return;
    }
    try {
        LOGGER.info("creating the installer keystores");
        // the installer keystore consists of the single client X.509 certificate, which is generated and signed by
        // the Texai root certificate on the developement system that has the root private key.
        final KeyPair installerKeyPair = X509Utils.generateRSAKeyPair2048();
        final X509Certificate installerX509Certificate = X509Utils.generateX509Certificate(
                installerKeyPair.getPublic(), X509Utils.getRootPrivateKey(), X509Utils.getRootX509Certificate(),
                null);

        // proceed as though the JCE unlimited strength jurisdiction policy files are installed, which they will be on the
        // trusted development system.
        LOGGER.info("creating installer-keystore.uber");
        assert X509Utils.isJCEUnlimitedStrengthPolicy();
        KeyStore installerKeyStore = X509Utils.findOrCreateKeyStore(filePath, INSTALLER_KEYSTORE_PASSWORD);
        installerKeyStore.setKeyEntry(X509Utils.ENTRY_ALIAS, installerKeyPair.getPrivate(),
                INSTALLER_KEYSTORE_PASSWORD,
                new Certificate[] { installerX509Certificate, X509Utils.getRootX509Certificate() });
        installerKeyStore.store(new FileOutputStream(filePath), INSTALLER_KEYSTORE_PASSWORD);

        // then proceed after disabling the JCE unlimited strength jurisdiction policy files indicator
        X509Utils.setIsJCEUnlimitedStrengthPolicy(false);
        filePath = "data/installer-keystore.jceks";
        LOGGER.info("creating installer-keystore.jceks");
        installerKeyStore = X509Utils.findOrCreateKeyStore(filePath, INSTALLER_KEYSTORE_PASSWORD);
        installerKeyStore.setKeyEntry(X509Utils.ENTRY_ALIAS, installerKeyPair.getPrivate(),
                INSTALLER_KEYSTORE_PASSWORD,
                new Certificate[] { installerX509Certificate, X509Utils.getRootX509Certificate() });
        installerKeyStore.store(new FileOutputStream(filePath), INSTALLER_KEYSTORE_PASSWORD);
        // restore the JCE unlimited strength jurisdiction policy files indicator
        X509Utils.setIsJCEUnlimitedStrengthPolicy(true);
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException
            | SignatureException | InvalidKeyException | IOException | KeyStoreException
            | CertificateException ex) {
        LOGGER.error(StringUtils.getStackTraceAsString(ex));
        throw new TexaiException(ex);
    }

    //Postconditions
    assert !isTrustedDevelopmentSystem()
            || X509Utils.isJCEUnlimitedStrengthPolicy() : "JCE unlimited strength policy must be in effect";
}

From source file:org.apache.accumulo.test.util.CertUtils.java

private X509CertificateObject generateCert(String keyName, KeyPair kp, boolean isCertAuthority,
        PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException, CertIOException,
        OperatorCreationException, CertificateException, NoSuchAlgorithmException {
    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.YEAR, 100);

    BigInteger serialNumber = BigInteger.valueOf((startDate.getTimeInMillis()));
    X500Name issuer = new X500Name(IETFUtils.rDNsFromString(issuerDirString, RFC4519Style.INSTANCE));
    JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer, serialNumber,
            startDate.getTime(), endDate.getTime(), issuer, kp.getPublic());
    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    certGen.addExtension(Extension.subjectKeyIdentifier, false,
            extensionUtils.createSubjectKeyIdentifier(kp.getPublic()));
    certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(isCertAuthority));
    certGen.addExtension(Extension.authorityKeyIdentifier, false,
            extensionUtils.createAuthorityKeyIdentifier(signerPublicKey));
    if (isCertAuthority) {
        certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
    }//from  w  w  w.  ja va2 s.  com
    X509CertificateHolder cert = certGen
            .build(new JcaContentSignerBuilder(signingAlgorithm).build(signerPrivateKey));
    return new X509CertificateObject(cert.toASN1Structure());
}

From source file:mitm.common.security.ca.hibernate.CertificateRequestStoreImplTest.java

@Test
public void testAddRequest() throws Exception {
    AutoTransactDelegator delegator = AutoTransactDelegator.createProxy();

    X500PrincipalBuilder builder = new X500PrincipalBuilder();

    builder.setCommonName("john doe");
    builder.setEmail("johndoe@example.com");

    KeyPair keyPair = generateKeyPair();

    delegator.addRequest(builder.buildPrincipal(), "test@example.com", 365, "SHA1", "http://example.com",
            "dummy", new byte[] { 1, 2, 3 }, new Date(), "Some message", keyPair);

    List<? extends CertificateRequest> found = delegator.getRequestsByEmail("test@example.com", null, null,
            null);//w  w w . j a va  2  s.co  m

    assertEquals(1, found.size());

    CertificateRequest request = found.get(0);

    KeyPair keyPairCopy = request.getKeyPair(encryptor);

    assertNotNull(keyPairCopy);
    assertEquals(keyPair.getPublic(), keyPairCopy.getPublic());
    assertEquals(keyPair.getPrivate(), keyPairCopy.getPrivate());
}

From source file:org.apache.stratos.keystore.mgt.KeyStoreGenerator.java

/**
 * This method generates the keypair and stores it in the keystore
 *
 * @param keyStore A keystore instance//from w  w  w  .j a  v  a2  s.co  m
 * @return Generated public key for the tenant
 * @throws KeyStoreMgtException Error when generating key pair
 */
private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException {
    try {
        CryptoUtil.getDefaultCryptoUtil();
        //generate key pair
        KeyPairGenerator keyPairGenerator = null;
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // Common Name and alias for the generated certificate
        String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None";

        //generate certificates
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()));
        v3CertGen.setIssuerDN(new X509Principal(commonName));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal(commonName));
        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
        X509Certificate PKCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        //add private key to KS
        keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[] { PKCertificate });
        return PKCertificate;
    } catch (Exception ex) {
        String msg = "Error while generating the certificate for tenant :" + tenantDomain + ".";
        log.error(msg, ex);
        throw new KeyStoreMgtException(msg, ex);
    }

}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#verifyFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *//*w  ww .jav a 2  s.  co m*/
public synchronized FileSecurityResponse verifyFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#verifyFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            // read in the file signature
            byte[] sigToVerify = IOUtils.toByteArray(new FileInputStream(request.getSignedFile()));

            if (DEBUG) {
                DEBUGGER.debug("sigToVerify: {}", sigToVerify);
            }

            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initVerify(keyPair.getPublic());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            response.setIsSignatureValid(signature.verify(sigToVerify));
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.VERIFYFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:cybervillains.ca.KeyStoreManager.java

/**
 * This method returns the duplicated certificate mapped to the passed in cert, or
 * creates and returns one if no mapping has yet been performed.  If a naked public
 * key has already been mapped that matches the key in the cert, the already mapped
 * keypair will be reused for the mapped cert.
 * @param cert/* w w  w . j av  a  2  s  .  c o  m*/
 * @return
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws CertificateException
 * @throws CertificateNotYetValidException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws SignatureException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public synchronized X509Certificate getMappedCertificate(final X509Certificate cert)
        throws CertificateEncodingException, InvalidKeyException, CertificateException,
        CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException,
        KeyStoreException, UnrecoverableKeyException {

    String thumbprint = ThumbprintUtil.getThumbprint(cert);

    String mappedCertThumbprint = _certMap.get(thumbprint);

    if (mappedCertThumbprint == null) {

        // Check if we've already mapped this public key from a KeyValue
        PublicKey mappedPk = getMappedPublicKey(cert.getPublicKey());
        PrivateKey privKey;

        if (mappedPk == null) {
            PublicKey pk = cert.getPublicKey();

            String algo = pk.getAlgorithm();

            KeyPair kp;

            if (algo.equals("RSA")) {
                kp = getRSAKeyPair();
            } else if (algo.equals("DSA")) {
                kp = getDSAKeyPair();
            } else {
                throw new InvalidKeyException("Key algorithm " + algo + " not supported.");
            }
            mappedPk = kp.getPublic();
            privKey = kp.getPrivate();

            mapPublicKeys(cert.getPublicKey(), mappedPk);
        } else {
            privKey = getPrivateKey(mappedPk);
        }

        X509Certificate replacementCert = CertificateCreator.mitmDuplicateCertificate(cert, mappedPk,
                getSigningCert(), getSigningPrivateKey());

        addCertAndPrivateKey(null, replacementCert, privKey);

        mappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert);

        _certMap.put(thumbprint, mappedCertThumbprint);
        _certMap.put(mappedCertThumbprint, thumbprint);
        _subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint);

        if (persistImmediately) {
            persist();
        }
        return replacementCert;
    }
    return getCertificateByAlias(mappedCertThumbprint);

}

From source file:org.panbox.desktop.linux.dbus.PanboxInterfaceImpl.java

@Override
public byte addContact(String mail, String firstname, String lastname) {
    logger.debug("[DBUS] addContact(" + mail + ", " + firstname + ", " + lastname + ")");
    byte ret = StatusCode.DBUS_OK;

    try {// w ww  .jav  a2 s  .  com
        PanboxContact contact = new PanboxContact();
        contact.setEmail(mail);
        contact.setFirstName(firstname);
        contact.setName(lastname);

        KeyPair ownerKeySign = CryptCore.generateKeypair();
        KeyPair ownerKeyEnc = CryptCore.generateKeypair();

        contact.setCertEnc(CryptCore.createSelfSignedX509Certificate(ownerKeyEnc.getPrivate(),
                ownerKeyEnc.getPublic(), contact));
        contact.setCertSign(CryptCore.createSelfSignedX509Certificate(ownerKeySign.getPrivate(),
                ownerKeySign.getPublic(), contact));

        PanboxClient.getInstance().getIdentity().getAddressbook().addContact(contact);
        IdentityManager.getInstance().storeMyIdentity(PanboxClient.getInstance().getIdentity());
    } catch (Exception e) {
        ret = StatusCode.getAndLog(logger, e);
    }

    return ret;
}

From source file:org.apache.hadoop.gateway.services.security.impl.BaseKeystoreService.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/*w  ww  .j  a  v a  2 s  .co  m*/
 * @param days how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 */
protected X509Certificate generateCertificate(String dn, KeyPair pair, int days, String algorithm)
        throws GeneralSecurityException, IOException {
    PrivateKey privkey = pair.getPrivate();
    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(dn);

    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(pair.getPublic()));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));

    // Sign the cert to identify the algorithm that's used.
    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(privkey, algorithm);

    // Update the algorith, and resign.
    algo = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
    info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
    cert = new X509CertImpl(info);
    cert.sign(privkey, algorithm);
    return cert;
}

From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java

@Test
public void testGetKeyPair01() {
    KeyPair keyPair = this.generator.generateKeyPair();

    assertNotNull("The key pair should not be null.", keyPair);

    assertEquals("The algorithm is not correct.", KeyFileUtilities.keyAlgorithm,
            keyPair.getPrivate().getAlgorithm());
    assertEquals("The algorithm is not correct.", KeyFileUtilities.keyAlgorithm,
            keyPair.getPublic().getAlgorithm());
}