List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:net.maritimecloud.identityregistry.controllers.BaseControllerWithCertificate.java
protected PemCertificate issueCertificate(CertificateModel certOwner, Organization org, String type, HttpServletRequest request) throws McBasicRestException { // Generate keypair for user KeyPair userKeyPair = CertificateUtil.generateKeyPair(); // Find special MC attributes to put in the certificate HashMap<String, String> attrs = getAttr(certOwner); String o = org.getMrn();// w w w . j ava2 s.co m String name = getName(certOwner); String email = getEmail(certOwner); String uid = getUid(certOwner); if (uid == null || uid.trim().isEmpty()) { throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.ENTITY_ORG_ID_MISSING, request.getServletPath()); } BigInteger serialNumber = certUtil.generateSerialNumber(); X509Certificate userCert = certUtil.generateCertForEntity(serialNumber, org.getCountry(), o, type, name, email, uid, userKeyPair.getPublic(), attrs); String pemCertificate; try { pemCertificate = CertificateUtil.getPemFromEncoded("CERTIFICATE", userCert.getEncoded()).replace("\n", "\\n"); } catch (CertificateEncodingException e) { throw new RuntimeException(e.getMessage(), e); } String pemPublicKey = CertificateUtil.getPemFromEncoded("PUBLIC KEY", userKeyPair.getPublic().getEncoded()) .replace("\n", "\\n"); String pemPrivateKey = CertificateUtil .getPemFromEncoded("PRIVATE KEY", userKeyPair.getPrivate().getEncoded()).replace("\n", "\\n"); PemCertificate ret = new PemCertificate(pemPrivateKey, pemPublicKey, pemCertificate); // Create the certificate Certificate newMCCert = new Certificate(); certOwner.assignToCert(newMCCert); newMCCert.setCertificate(pemCertificate); newMCCert.setSerialNumber(serialNumber); // The dates we extract from the cert is in localtime, so they are converted to UTC before saving into the DB Calendar cal = Calendar.getInstance(); long offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); newMCCert.setStart(new Date(userCert.getNotBefore().getTime() - offset)); newMCCert.setEnd(new Date(userCert.getNotAfter().getTime() - offset)); this.certificateService.saveCertificate(newMCCert); return ret; }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
@Test public void test06NotNestedMessage() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { ASN1EncodableVector optionaValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); optionaValidityV.add(new DERTaggedObject(true, 0, nb)); optionaValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionaValidityV)); KeyPair keys = KeyTools.genKeys("1024", "RSA"); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); myCertTemplate.setIssuer(new X500Name(this.issuerDN)); myCertTemplate.setSubject(SUBJECT_DN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try {/*ww w . j a v a 2s .c o m*/ SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); // If we did not pass any extensions as parameter, we will create some of our own, standard ones } finally { dIn.close(); } final Extensions exts; { // SubjectAltName ByteArrayOutputStream bOut = new ByteArrayOutputStream(); DEROutputStream dOut = new DEROutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); // KeyUsage int bcku = 0; bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation; X509KeyUsage ku = new X509KeyUsage(bcku); bOut = new ByteArrayOutputStream(); dOut = new DEROutputStream(bOut); dOut.writeObject(ku); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value)); // Make the complete extension package exts = extgen.generate(); } myCertTemplate.setExtensions(exts); CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); ProofOfPossession myProofOfPossession = new ProofOfPossession(); AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("foo123")); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(SUBJECT_DN), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); PKIBody myPKIBody = new PKIBody(20, myCertReqMessages); // nestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raSignerTest06", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null, "BC"); assertNotNull("Failed to create PKIHeader", myPKIHeader); assertNotNull("Failed to create PKIBody", myPKIBody); assertNotNull("Failed to create PKIMessage", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); assertEquals("unknown object in getInstance: org.bouncycastle.asn1.DERSequence", errMsg); }
From source file:eu.contrail.security.DelegatedUserCertClientTest.java
@Test public void testGetDelegatedUserCert() throws Exception { System.out.println("getDelegatedUserCert w/o server pass"); /*//from ww w . j ava2 s.com * If the propsFile property isn't set, read the properties files from a hard-wired locationn * */ String propsFile = System.getProperty("propsFile", "./src/test/resources/ucstest.properties"); Properties props = null; try { props = new Properties(); props.load(new FileInputStream(propsFile)); } catch (Exception ex) { System.err.println(ex); } // System.setProperty("javax.net.debug", "ssl"); /* * If the targetUrl property isn't set, use a hard-wired URL * */ //String uriSpec = "https://one-test.contrail.rl.ac.uk:8443/ca/delegateduser"; String uriSpec = "https://contrail.federation.ca:8445/ca/delegateduser"; KeyPair keyPair = sc.generateKeyPair("RSA", 2048); String signatureAlgorithm = "SHA256withRSA"; /* * Use a well-known username/password combination * */ System.setProperty("javax.net.debug", "ssl"); String proxyHost = null; String proxyPortSpec = null; String proxyScheme = null; DelegatedCertClient instance = new DelegatedCertClient(uriSpec, true, "contrail-federation-web-key-store.pkcs12", "contrail", "egi-cloud-ca-keystore.jks", "contrail"); X509Certificate result = null; String userID = "1"; try { System.out.printf("Calling %s.%n", uriSpec); result = instance.getCert(keyPair, signatureAlgorithm, userID, true); if (result == null) { throw new Exception(); // Throw an Exception to signal test has failed } System.out.println("Delegated User Private Key:"); sc.writeKey(System.out, keyPair.getPrivate()); System.out.println("\nDelegated User Certificate from CA Server:"); sc.writeCertificate(System.out, result); } catch (IllegalArgumentException ex) { System.err.printf(ex.getLocalizedMessage()); } }
From source file:org.apache.drill.exec.server.rest.WebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings * they will be used else a self-signed certificate is generated and used. * * @return Initialized {@link ServerConnector} for HTTPS connectios. * @throws Exception//from w ww .j a v a2 s . com */ private ServerConnector createHttpsConnector() throws Exception { logger.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) { logger.info("Using configured SSL settings for web server"); sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // TrustStore and TrustStore password are optional if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { sslContextFactory .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); } } } else { logger.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)") .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress()); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT)); return sslConnector; }
From source file:org.apache.drill.yarn.appMaster.http.WebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has * specified keystore/truststore settings they will be used else a self-signed * certificate is generated and used.//from ww w .j a v a 2s. c o m * <p> * This is a shameless copy of * {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}. * The two should be merged at some point. The primary issue is that the Drill * version is tightly coupled to Drillbit configuration. * * @return Initialized {@link ServerConnector} for HTTPS connections. * @throws Exception */ private ServerConnector createHttpsConnector(Config config) throws Exception { LOG.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); // if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && // !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) // { // LOG.info("Using configured SSL settings for web server"); // sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); // sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // // // TrustStore and TrustStore password are optional // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { // sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { // sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); // } // } // } else { LOG.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, "Drill AM"); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); // } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(jettyServer, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT)); return sslConnector; }
From source file:org.dasein.cloud.google.compute.server.ServerSupport.java
private String decryptPassword(String message, KeyPair keys) throws InternalException { try {//from w w w. j a v a2 s . c o m Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Cipher rsaOAEPPadding = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC"); rsaOAEPPadding.init(Cipher.DECRYPT_MODE, keys.getPrivate()); return new String(rsaOAEPPadding.doFinal(Base64.decodeBase64(message)), "UTF8"); } catch (Exception e) { throw new InternalException(e); } }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
@Test public void test03RevReq() throws NoSuchAlgorithmException, AuthorizationDeniedException, EjbcaException, IOException, InvalidAlgorithmParameterException, RoleNotFoundException, InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException, ObjectNotFoundException, CertificateException, CADoesntExistsException, IllegalKeyException, CertificateCreateException, IllegalNameException, CertificateRevokeException, CertificateSerialNumberException, CryptoTokenOfflineException, IllegalValidityException, CAOfflineException, InvalidAlgorithmException, CustomCertificateSerialNumberException, UserDoesntFullfillEndEntityProfile, RemoveException, WaitingForApprovalException, FinderException { Collection<Certificate> certs = this.certificateStoreSession .findCertificatesBySubjectAndIssuer(SUBJECT_DN.toString(), this.issuerDN); log.debug("Found " + certs.size() + " certificates for userDN \"" + SUBJECT_DN + "\""); Certificate cert = null;/*from w ww . jav a 2s. c om*/ for (Certificate tmp : certs) { if (!this.certificateStoreSession.isRevoked(this.issuerDN, CertTools.getSerialNumber(tmp))) { cert = tmp; break; } } assertNotNull("Could not find a suitable certificate to revoke.", cert); //----------- creating the revocation signed request------------------- final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage revMsg = genRevReq(this.issuerDN, SUBJECT_DN, CertTools.getSerialNumber(cert), this.cacert, nonce, transid, false, pAlg, new DEROctetString(nonce)); assertNotNull("Generating CrmfRequest failed." + revMsg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE"); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] cmpcert = getCMPCert(admCert); revMsg = CmpMessageHelper.buildCertBasedPKIProtection(revMsg, cmpcert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(revMsg); //----------------- Creating the nested PKIMessage ----------------------- String reqSubjectDN = "CN=bogusSubjectNested"; final byte[] reqNonce = CmpMessageHelper.createSenderNonce(); final byte[] reqTransid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(reqNonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(reqTransid)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(revMsg); DERSequence seq = new DERSequence(v); PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); createRACertificate("raRevSigner", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert, nonce, transid, false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); int revStatus = checkRevokeStatus(this.issuerDN, CertTools.getSerialNumber(cert)); assertNotEquals("Revocation request failed to revoke the certificate", Integer.valueOf(RevokedCertInfo.NOT_REVOKED), Integer.valueOf(revStatus)); removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:mitm.common.security.certificate.GenerateSSLCertificate.java
private void generateSSLCertificate() throws Exception { X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); SecureRandom randomSource = securityFactory.createSecureRandom(); keyPairGenerator.initialize(1024, randomSource); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder(); subjectBuilder.setCommonName("www.example.com"); subjectBuilder.setCountryCode("NL"); subjectBuilder.setLocality("Amsterdam"); subjectBuilder.setState("NH"); X500Principal subject = subjectBuilder.buildPrincipal(); Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); extendedKeyUsage.add(ExtendedKeyUsageType.SERVERAUTH); SerialNumberGenerator sng = new StandardSerialNumberGenerator(); BigInteger serialNumber = sng.generate(); Date now = new Date(); certificateBuilder.setSubject(subject); certificateBuilder.setIssuer(subject); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false); certificateBuilder.setNotBefore(DateUtils.addDays(now, -20)); certificateBuilder.setNotAfter(DateUtils.addYears(now, 20)); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption"); X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null); assertNotNull(certificate);//from w w w .j a v a2s .c om certificates.add(certificate); Certificate[] chain = new Certificate[] { certificate }; keyStore.setKeyEntry("djigzo", keyPair.getPrivate(), null, chain); }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
@Test public void test01CrmfReq() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { //-----------------Creating CRMF request //PKIMessage crmfMsg = createEESignedCrmfReq(this.subjectDN); byte[] senderNonce = CmpMessageHelper.createSenderNonce(); byte[] transactionID = CmpMessageHelper.createSenderNonce(); Date nb = new Date((new Date()).getTime() - 31536000000L); // not before a year ago Date na = new Date((new Date()).getTime() + 31536000000L); // not afer a yeat from now assertNotNull(nb);/*from ww w . j a va 2 s . co m*/ assertNotNull(na); KeyPair keys = KeyTools.genKeys("1024", "RSA"); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage crmfMsg = genCertReq(this.issuerDN, SUBJECT_DN, keys, this.cacert, senderNonce, transactionID, false, null, nb, na, null, pAlg, new DEROctetString(senderNonce)); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE"); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] cmpcert = getCMPCert(admCert); crmfMsg = CmpMessageHelper.buildCertBasedPKIProtection(crmfMsg, cmpcert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(crmfMsg); CertReqMessages ir = (CertReqMessages) crmfMsg.getBody().getContent(); int reqID = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue(); //------------------Creating NestedMessageContent String reqSubjectDN = "CN=bogusSubjectNested"; final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name(reqSubjectDN)), new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(crmfMsg); DERSequence seq = new DERSequence(v); PKIBody myPKIBody = new PKIBody(20, seq); // NestedMessageContent assertNotNull("Failed to create nested Message PKIBody", myPKIBody); PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); assertNotNull("Failed to created nested message PKIMessage", myPKIMessage); KeyPair raKeys = KeyTools.genKeys("1024", "RSA"); assertEquals( "RACertPath is suppose to be '" + this.raCertsPath + "', instead it is '" + this.cmpConfiguration.getRACertPath(cmpAlias) + "'.", this.cmpConfiguration.getRACertPath(cmpAlias), this.raCertsPath); createRACertificate("raCrmfSigner", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null, CMPTESTPROFILE, this.caid); myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull("Failed to create myPKIHeader", myPKIHeader); assertNotNull("myPKIBody is null", myPKIBody); assertNotNull("myPKIMessage is null", myPKIMessage); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(myPKIMessage); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, cmpAlias); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, this.issuerDN, SUBJECT_DN, this.cacert, crmfMsg.getHeader().getSenderNonce().getOctets(), crmfMsg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); final Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqID); assertTrue(cert instanceof X509Certificate); log.debug("Subject DN of created certificate: " + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded())); assertNotNull("CrmfRequest did not return a certificate", cert); removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:org.apache.drill.cv.exec.server.rest.CvDrillWebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has specified * keystore/truststore settings they will be used else a self-signed certificate is generated and * used.// ww w . ja v a 2 s .com * * @return Initialized {@link ServerConnector} for HTTPS connectios. * @throws Exception */ private ServerConnector createHttpsConnector() throws Exception { CvDrillWebServer.logger.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) { CvDrillWebServer.logger.info("Using configured SSL settings for web server"); sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // TrustStore and TrustStore password are optional if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { sslContextFactory .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); } } } else { CvDrillWebServer.logger.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)") .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress()); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(getWebserverPort()); return sslConnector; }