List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:com.thoughtworks.go.security.X509CertificateGenerator.java
private X509Certificate createTypeOneX509Certificate(Date startDate, String principalDn, KeyPair keyPair) { X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal principal = new X500Principal(principalDn); certGen.setSerialNumber(serialNumber()); certGen.setIssuerDN(principal);//from ww w .j a va 2 s . c o m certGen.setNotBefore(startDate); DateTime now = new DateTime(new Date()); certGen.setNotAfter(now.plusYears(YEARS).toDate()); certGen.setSubjectDN(principal); // note: same as issuer certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(new SystemEnvironment().get(GO_SSL_CERTS_ALGORITHM)); try { return certGen.generate(keyPair.getPrivate(), "BC"); } catch (Exception e) { throw bomb(e); } }
From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java
/** * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#decryptFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest) *//*from ww w. ja v a2 s .c o m*/ public synchronized FileSecurityResponse decryptFile(final FileSecurityRequest request) throws FileSecurityException { final String methodName = IFileSecurityProcessor.CNAME + "#decryptFile(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) { Cipher cipher = Cipher.getInstance(fileSecurityConfig.getEncryptionAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic()); if (DEBUG) { DEBUGGER.debug("Cipher: {}", cipher); } IOUtils.write( IOUtils.toByteArray( new CipherInputStream(new FileInputStream(request.getEncryptedFile()), cipher)), new FileOutputStream(request.getDecryptedFile())); if ((request.getEncryptedFile().exists()) && (request.getEncryptedFile().length() != 0)) { response.setSignedFile(request.getEncryptedFile()); response.setRequestStatus(SecurityRequestStatus.SUCCESS); } else { response.setRequestStatus(SecurityRequestStatus.FAILURE); } } else { response.setRequestStatus(SecurityRequestStatus.FAILURE); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new FileSecurityException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { ERROR_RECORDER.error(nsax.getMessage(), nsax); throw new FileSecurityException(nsax.getMessage(), nsax); } catch (NoSuchPaddingException nspx) { ERROR_RECORDER.error(nspx.getMessage(), nspx); throw new FileSecurityException(nspx.getMessage(), nspx); } catch (InvalidKeyException ikx) { ERROR_RECORDER.error(ikx.getMessage(), ikx); throw new FileSecurityException(ikx.getMessage(), ikx); } 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.DECRYPTFILE); 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:org.apache.cloudstack.saml.SAML2AuthManagerImpl.java
protected boolean initSP() { KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR); if (keyStoreVO == null) { try {/* w w w. j ava 2 s . c om*/ KeyPair keyPair = SAMLUtils.generateRandomKeyPair(); _ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.savePrivateKey(keyPair.getPrivate()), SAMLUtils.savePublicKey(keyPair.getPublic()), "samlsp-keypair"); keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR); s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair"); } catch (NoSuchProviderException | NoSuchAlgorithmException e) { s_logger.error("Unable to create and save SAML keypair: " + e.toString()); } } String spId = SAMLServiceProviderID.value(); String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value(); String spSloUrl = SAMLServiceProviderSingleLogOutURL.value(); String spOrgName = SAMLServiceProviderOrgName.value(); String spOrgUrl = SAMLServiceProviderOrgUrl.value(); String spContactPersonName = SAMLServiceProviderContactPersonName.value(); String spContactPersonEmail = SAMLServiceProviderContactEmail.value(); KeyPair spKeyPair = null; X509Certificate spX509Key = null; if (keyStoreVO != null) { PrivateKey privateKey = SAMLUtils.loadPrivateKey(keyStoreVO.getCertificate()); PublicKey publicKey = SAMLUtils.loadPublicKey(keyStoreVO.getKey()); if (privateKey != null && publicKey != null) { spKeyPair = new KeyPair(publicKey, privateKey); KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT); if (x509VO == null) { try { spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(spX509Key); out.flush(); _ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT, Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert"); bos.close(); } catch (NoSuchAlgorithmException | NoSuchProviderException | CertificateEncodingException | SignatureException | InvalidKeyException | IOException e) { s_logger.error("SAML Plugin won't be able to use X509 signed authentication"); } } else { try { ByteArrayInputStream bi = new ByteArrayInputStream( Base64.decodeBase64(x509VO.getCertificate())); ObjectInputStream si = new ObjectInputStream(bi); spX509Key = (X509Certificate) si.readObject(); bi.close(); } catch (IOException | ClassNotFoundException ignored) { s_logger.error( "SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database."); } } } } if (spKeyPair != null && spX509Key != null && spId != null && spSsoUrl != null && spSloUrl != null && spOrgName != null && spOrgUrl != null && spContactPersonName != null && spContactPersonEmail != null) { _spMetadata.setEntityId(spId); _spMetadata.setOrganizationName(spOrgName); _spMetadata.setOrganizationUrl(spOrgUrl); _spMetadata.setContactPersonName(spContactPersonName); _spMetadata.setContactPersonEmail(spContactPersonEmail); _spMetadata.setSsoUrl(spSsoUrl); _spMetadata.setSloUrl(spSloUrl); _spMetadata.setKeyPair(spKeyPair); _spMetadata.setSigningCertificate(spX509Key); _spMetadata.setEncryptionCertificate(spX509Key); return true; } return false; }
From source file:cybervillains.ca.KeyStoreManager.java
/** * This method returns the mapped certificate for a hostname, or generates a "standard" * SSL server certificate issued by the CA to the supplied subject if no mapping has been * created. This is not a true duplication, just a shortcut method * that is adequate for web browsers./*from www . j a va 2 s .co m*/ * * @param hostname * @return * @throws CertificateParsingException * @throws InvalidKeyException * @throws CertificateExpiredException * @throws CertificateNotYetValidException * @throws SignatureException * @throws CertificateException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyStoreException * @throws UnrecoverableKeyException */ public X509Certificate getMappedCertificateForHostname(String hostname) throws CertificateParsingException, InvalidKeyException, CertificateExpiredException, CertificateNotYetValidException, SignatureException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException { String subject = getSubjectForHostname(hostname); String thumbprint = _subjectMap.get(subject); if (thumbprint == null) { KeyPair kp = getRSAKeyPair(); X509Certificate newCert = CertificateCreator.generateStdSSLServerCertificate(kp.getPublic(), getSigningCert(), getSigningPrivateKey(), subject); addCertAndPrivateKey(hostname, newCert, kp.getPrivate()); thumbprint = ThumbprintUtil.getThumbprint(newCert); _subjectMap.put(subject, thumbprint); if (persistImmediately) { persist(); } return newCert; } return getCertificateByAlias(thumbprint); }
From source file:edu.vt.middleware.crypt.signature.SignatureAlgorithmTest.java
/** * @param signature A crypto signature algorithm to test. * @param keys Public/private key pair used for signing. * @param converter Converter used to convert sig bytes to String. * * @throws Exception On test failure.//from ww w.j a v a 2 s . c o m */ @Test(groups = { "functest", "signature" }, dataProvider = "testdata") public void testSignVerifyOnStream(final SignatureAlgorithm signature, final KeyPair keys, final Converter converter) throws Exception { logger.info("Testing signature stream handling for " + signature + " with converter " + converter); final InputStream in1 = getClass().getResourceAsStream(BIG_FILE_PATH); final InputStream in2 = getClass().getResourceAsStream(BIG_FILE_PATH); try { signature.setRandomProvider(new SecureRandom()); signature.setSignKey(keys.getPrivate()); signature.initSign(); if (converter == null) { final byte[] signedBytes = signature.sign(in1); signature.setVerifyKey(keys.getPublic()); signature.initVerify(); AssertJUnit.assertTrue(signature.verify(in2, signedBytes)); } else { final String sig = signature.sign(in1, converter); signature.setVerifyKey(keys.getPublic()); signature.initVerify(); AssertJUnit.assertTrue(signature.verify(in2, sig, converter)); } } finally { if (in1 != null) { in1.close(); } if (in2 != null) { in2.close(); } } }
From source file:org.ejbca.util.keystore.KeyStoreContainerBase.java
private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair) throws Exception { final long currentTime = new Date().getTime(); final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000); final Date lastDate = new Date(currentTime + validity * 1000); // Add all mandatory attributes log.debug("keystore signing algorithm " + sigAlg); final PublicKey publicKey = keyPair.getPublic(); if (publicKey == null) { throw new Exception("Public key is null"); }//from w w w .ja v a 2 s.c o m final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(new X500Name(myname), BigInteger.valueOf(firstDate.getTime()), firstDate, lastDate, new X500Name(myname), pkinfo); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); return (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); }
From source file:org.candlepin.util.X509CRLStreamWriterTest.java
@Test public void testKeySizeChange() throws Exception { int[] sizes = { 1024, 4096 }; for (int size : sizes) { X509CRLHolder holder = createCRL(); File crlToChange = writeCRL(holder); generator.initialize(size);/* ww w.j a va2 s. co m*/ KeyPair differentKeyPair = generator.generateKeyPair(); X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) differentKeyPair.getPrivate(), (RSAPublicKey) differentKeyPair.getPublic()); stream.preScan(crlToChange).lock(); OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile)); stream.write(o); o.close(); X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder); X509CRL changedCrl = readCRL(differentKeyPair.getPublic()); Set<BigInteger> discoveredSerials = new HashSet<BigInteger>(); for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) { discoveredSerials.add(entry.getSerialNumber()); } Set<BigInteger> expected = new HashSet<BigInteger>(); expected.add(new BigInteger("100")); assertEquals(expected, discoveredSerials); // Since the key changed, the authorityKeyIdentifier must change byte[] oldAkiBytes = originalCrl.getExtensionValue(X509Extension.authorityKeyIdentifier.getId()); byte[] newAkiBytes = changedCrl.getExtensionValue(X509Extension.authorityKeyIdentifier.getId()); AuthorityKeyIdentifierStructure oldAki = new AuthorityKeyIdentifierStructure(oldAkiBytes); AuthorityKeyIdentifierStructure newAki = new AuthorityKeyIdentifierStructure(newAkiBytes); assertArrayEquals(oldAki.getKeyIdentifier(), new AuthorityKeyIdentifierStructure(keyPair.getPublic()).getKeyIdentifier()); assertArrayEquals(newAki.getKeyIdentifier(), new AuthorityKeyIdentifierStructure(differentKeyPair.getPublic()).getKeyIdentifier()); } }
From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
private X509Certificate generateCertificate(KeyPair keyPair, String dn) throws Exception { ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()); Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + dn), new BigInteger(64, new SecureRandom()), startDate, endDate, new X500Name("CN=" + dn), keyPair.getPublic()); X509CertificateHolder certHolder = v3CertGen.build(sigGen); X509Certificate x509Certificate = new JcaX509CertificateConverter().getCertificate(certHolder); return x509Certificate; }
From source file:org.teknux.jettybootstrap.keystore.JettyKeystore.java
private static Certificate generateCertificate(KeyPair keyPair, String domainName, String signatureAlgorithm, String rdnOuValue, String rdnOValue, int dateNotBeforeNumberOfDays, int dateNotAfterNumberOfDays) throws JettyKeystoreException { X500NameBuilder issuerX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE); if (rdnOuValue != null) { issuerX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue); }/*ww w . ja v a 2 s . com*/ if (rdnOValue != null) { issuerX500Namebuilder.addRDN(BCStyle.O, rdnOValue); } X500Name issuer = issuerX500Namebuilder.addRDN(BCStyle.CN, domainName).build(); BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())); Date dateNotBefore = new Date(System.currentTimeMillis() - (dateNotBeforeNumberOfDays * DAY_IN_MILLIS)); Date dateNotAfter = new Date(System.currentTimeMillis() + (dateNotAfterNumberOfDays * DAY_IN_MILLIS)); X500NameBuilder subjectX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE); if (rdnOuValue != null) { subjectX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue); } if (rdnOValue != null) { subjectX500Namebuilder.addRDN(BCStyle.O, rdnOValue); } X500Name subject = subjectX500Namebuilder.addRDN(BCStyle.CN, domainName).build(); SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(keyPair.getPublic().getEncoded())); X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, serial, dateNotBefore, dateNotAfter, subject, publicKeyInfo); Provider provider = new BouncyCastleProvider(); try { ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider) .build(keyPair.getPrivate()); return new JcaX509CertificateConverter().setProvider(provider) .getCertificate(x509v3CertificateBuilder.build(signer)); } catch (OperatorCreationException | CertificateException e) { throw new JettyKeystoreException(JettyKeystoreException.ERROR_CREATE_CERTIFICATE, "Can not generate certificate", e); } }
From source file:com.thoughtworks.go.security.X509CertificateGenerator.java
private X509Certificate createIntermediateCertificate(PrivateKey caPrivKey, X509Certificate caCert, Date startDate, KeyPair keyPair) throws Exception { X500Name issuerDn = JcaX500NameUtil.getSubject(caCert); X500NameBuilder subjectBuilder = new X500NameBuilder(BCStyle.INSTANCE); subjectBuilder.addRDN(BCStyle.OU, INTERMEDIATE_CERT_OU); subjectBuilder.addRDN(BCStyle.EmailAddress, CERT_EMAIL); X500Name subjectDn = subjectBuilder.build(); X509CertificateGenerator.V3X509CertificateGenerator v3CertGen = new V3X509CertificateGenerator(startDate, issuerDn, subjectDn, keyPair.getPublic(), serialNumber()); // extensions v3CertGen.addSubjectKeyIdExtension(keyPair.getPublic()); v3CertGen.addAuthorityKeyIdExtension(caCert); v3CertGen.addBasicConstraintsExtension(); X509Certificate cert = v3CertGen.generate(caPrivKey); Date now = new Date(); cert.checkValidity(now);/* w ww . j av a 2 s . c o m*/ cert.verify(caCert.getPublicKey()); PKCS12BagAttributeSetter.usingBagAttributeCarrier(cert).setFriendlyName(INTERMEDIATE_CERT_OU); PKCS12BagAttributeSetter.usingBagAttributeCarrier(keyPair.getPrivate()).setFriendlyName(FRIENDLY_NAME) .setLocalKeyId(keyPair.getPublic()); return cert; }