List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java
@Test public void testSaveKeysToProviders03() throws ClassNotFoundException, IllegalAccessException, InstantiationException { String pn = "com.nicholaswilliams.last"; RSAKeyPairGeneratorInterface.GeneratedClassDescriptor privateKPDescriptor = new RSAKeyPairGeneratorInterface.GeneratedClassDescriptor(); privateKPDescriptor.setPackageName(pn); privateKPDescriptor.setClassName("TestPrivateKeyProvider03"); RSAKeyPairGeneratorInterface.GeneratedClassDescriptor publicKPDescriptor = new RSAKeyPairGeneratorInterface.GeneratedClassDescriptor(); publicKPDescriptor.setPackageName(pn); publicKPDescriptor.setClassName("TestPublicKeyProvider03"); KeyPair keyPair = this.generator.generateKeyPair(); this.generator.saveKeyPairToProviders(keyPair, privateKPDescriptor, publicKPDescriptor, "finalPasswordOne03".toCharArray(), "finalPasswordTwo03".toCharArray()); /////////////////////// assertNotNull("The private key code should not be null.", privateKPDescriptor.getJavaFileContents()); assertTrue("The private key code should have length.", privateKPDescriptor.getJavaFileContents().length() > 0); Class<?> privateKPClass = this .compileClass(pn + ".TestPrivateKeyProvider03", privateKPDescriptor.getJavaFileContents()) .getClassLoader(null).loadClass(pn + ".TestPrivateKeyProvider03"); PrivateKeyDataProvider privateKeyDataProvider = (PrivateKeyDataProvider) privateKPClass.newInstance(); assertNotNull("The private key data provider should not be null.", privateKeyDataProvider); byte[] privateKeyData = privateKeyDataProvider.getEncryptedPrivateKeyData(); assertNotNull("The private key data should not be null.", privateKeyData); assertTrue("The private key data should have length.", privateKeyData.length > 0); PrivateKey privateKey = KeyFileUtilities.readEncryptedPrivateKey(privateKeyData, "finalPasswordOne03".toCharArray()); assertNotNull("The private key should not be null.", privateKey); assertEquals("The private key is not correct.", keyPair.getPrivate(), privateKey); /////////////////////// assertNotNull("The public key code should not be null.", publicKPDescriptor.getJavaFileContents()); assertTrue("The public key code should have length.", publicKPDescriptor.getJavaFileContents().length() > 0); Class<?> publicKPClass = this .compileClass(pn + ".TestPublicKeyProvider03", publicKPDescriptor.getJavaFileContents()) .getClassLoader(null).loadClass(pn + ".TestPublicKeyProvider03"); PublicKeyDataProvider publicKeyDataProvider = (PublicKeyDataProvider) publicKPClass.newInstance(); assertNotNull("The public key data provider should not be null.", publicKeyDataProvider); byte[] publicKeyData = publicKeyDataProvider.getEncryptedPublicKeyData(); assertNotNull("The public key data should not be null.", publicKeyData); assertTrue("The public key data should have length.", publicKeyData.length > 0); PublicKey publicKey = KeyFileUtilities.readEncryptedPublicKey(publicKeyData, "finalPasswordTwo03".toCharArray()); assertNotNull("The public key should not be null.", publicKey); assertEquals("The public key is not correct.", keyPair.getPublic(), publicKey); }
From source file:com.netscape.cmstools.CRMFPopClient.java
public CertRequest createCertRequest(boolean self_sign, CryptoToken token, X509Certificate transportCert, String algorithm, KeyPair keyPair, Name subject, KeyWrapAlgorithm keyWrapAlgorithm) throws Exception { CertTemplate certTemplate = createCertTemplate(subject, keyPair.getPublic()); SEQUENCE seq = new SEQUENCE(); if (transportCert != null) { // add key archive Option byte[] iv = CryptoUtil.getNonceData(keyWrapAlgorithm.getBlockSize()); OBJECT_IDENTIFIER kwOID = CryptoUtil.getOID(keyWrapAlgorithm); /* TODO(alee)// www .ja v a 2s .co m * * HACK HACK! * algorithms like AES KeyWrap do not require an IV, but we need to include one * in the AlgorithmIdentifier above, or the creation and parsing of the * PKIArchiveOptions options will fail. So we include an IV in aid, but null it * later to correctly encrypt the data */ AlgorithmIdentifier aid = new AlgorithmIdentifier(kwOID, new OCTET_STRING(iv)); Class<?>[] iv_classes = keyWrapAlgorithm.getParameterClasses(); if (iv_classes == null || iv_classes.length == 0) iv = null; WrappingParams params = getWrappingParams(keyWrapAlgorithm, iv); PKIArchiveOptions opts = CryptoUtil.createPKIArchiveOptions(token, transportCert.getPublicKey(), (PrivateKey) keyPair.getPrivate(), params, aid); seq.addElement(new AVA(new OBJECT_IDENTIFIER("1.3.6.1.5.5.7.5.1.4"), opts)); } // key archival option /* OCTET_STRING ostr = createIDPOPLinkWitness(); seq.addElement(new AVA(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness, ostr)); */ if (self_sign) { // per rfc 5272 System.out.println("CRMFPopClient: self_sign true. Generating SubjectKeyIdentifier extension."); KeyIdentifier subjKeyId = CryptoUtil.createKeyIdentifier(keyPair); OBJECT_IDENTIFIER oid = new OBJECT_IDENTIFIER(PKIXExtensions.SubjectKey_Id.toString()); SEQUENCE extns = new SEQUENCE(); extns.addElement(new AVA(oid, new OCTET_STRING(subjKeyId.getIdentifier()))); certTemplate.setExtensions(extns); } return new CertRequest(new INTEGER(1), certTemplate, seq); }
From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java
/** * Checks for an existing certificate to use for secure communication between the server and * client. If no certficate exists, this will generate a new one. * /* ww w. j a v a 2 s .c o m*/ */ private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword) throws Exception { final String certificateAlias = "mirthconnect"; if (!keyStore.containsAlias(certificateAlias)) { // Common CA and SSL cert attributes Date startDate = new Date(); // time from which certificate is valid Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider); keyPairGenerator.initialize(2048); KeyPair caKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for CA cert using provider: " + provider.getName()); // Generate CA cert X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority"); SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE, startDate, expiryDate, caSubjectName, caSubjectKey); certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true, new BasicConstraints(0)); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate caCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(certBuilder.build(sigGen)); // Generate SSL cert KeyPair sslKeyPair = keyPairGenerator.generateKeyPair(); logger.debug("generated new key pair for SSL cert using provider: " + provider.getName()); X500Name sslSubjectName = new X500Name("CN=mirth-connect"); SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded())); X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName, new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(caCert.getEncoded())); sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded())); sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider) .build(caKeyPair.getPrivate()); Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider) .getCertificate(sslCertBuilder.build(sigGen)); logger.debug("generated new certificate with serial number: " + ((X509Certificate) sslCert).getSerialNumber()); // add the generated SSL cert to the keystore using the key password keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword, new Certificate[] { sslCert }); } else { logger.debug("found certificate in keystore"); } }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test11EECrmfCheckAdminAuthorization() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA"); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); String adminName = "cmpTestUnauthorizedAdmin"; createUser(adminName, "CN=" + adminName + ",C=SE", "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); KeyPair admkeys = KeyTools.genKeys("512", "RSA"); Certificate admCert = this.signSession.createCertificate(ADMIN, adminName, "foo123", new PublicKeyWrapper(admkeys.getPublic())); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg);//from www.jav a 2 s .c o m final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject()); assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); assertEquals("'CN=cmpTestUnauthorizedAdmin,C=SE' is not an authorized administrator.", errMsg); } finally { inputStream.close(); } }
From source file:mitm.common.security.ca.SMIMEKeyAndCertificateIssuer.java
@Override public KeyAndCertificate issueKeyAndCertificate(RequestParameters parameters, KeyAndCertificate signer) throws CAException { try {//from w ww . ja va2s. c om if (StringUtils.isBlank(parameters.getEmail())) { throw new CAException("email must be specified."); } if (parameters.getSubject() == null) { throw new CAException("subject must be specified."); } if (signer == null || signer.getCertificate() == null || signer.getPrivateKey() == null) { throw new CAException("issuer fields must be non-null."); } KeyPair keyPair = generateKeyPair(parameters); Set<KeyUsageType> keyUsage = new TreeSet<KeyUsageType>(); keyUsage.add(KeyUsageType.DIGITALSIGNATURE); keyUsage.add(KeyUsageType.KEYENCIPHERMENT); Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); SerialNumberGenerator serialNumberGenerator = new StandardSerialNumberGenerator(); BigInteger serialNumber = serialNumberGenerator.generate(); AltNamesBuilder altNamesBuider = new AltNamesBuilder(); altNamesBuider.setRFC822Names(parameters.getEmail()); X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); Date now = new Date(); certificateBuilder.setAltNames(altNamesBuider.buildAltNames(), false); certificateBuilder.setSubject(parameters.getSubject()); certificateBuilder.setIssuer(signer.getCertificate().getSubjectX500Principal()); certificateBuilder.setKeyUsage(keyUsage, true); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false); certificateBuilder.setNotBefore(DateUtils.addDays(now, -1)); certificateBuilder.setNotAfter(DateUtils.addDays(now, parameters.getValidity())); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm(parameters.getSignatureAlgorithm()); certificateBuilder.addSubjectKeyIdentifier(true); if (StringUtils.isNotBlank(parameters.getCRLDistributionPoint())) { certificateBuilder .setCRLDistributionPoints(Collections.singleton(parameters.getCRLDistributionPoint())); } X509Certificate certificate = certificateBuilder.generateCertificate(signer.getPrivateKey(), signer.getCertificate()); return new KeyAndCertificateImpl(keyPair.getPrivate(), certificate); } catch (NoSuchAlgorithmException e) { throw new CAException(e); } catch (NoSuchProviderException e) { throw new CAException(e); } catch (CertificateBuilderException e) { throw new CAException(e); } catch (IllegalStateException e) { throw new CAException(e); } catch (IOException e) { throw new CAException(e); } }
From source file:com.netscape.cmsutil.crypto.CryptoUtil.java
public static PKCS10 createCertificationRequest(String subjectName, KeyPair keyPair, Extensions exts) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, IOException, CertificateException, SignatureException { String method = "CryptoUtil: createCertificationRequest: "; String alg = "SHA256withRSA"; PublicKey pubk = keyPair.getPublic(); X509Key key = convertPublicKeyToX509Key(pubk); if (pubk instanceof RSAPublicKey) { alg = "SHA256withRSA"; } else if (isECCKey(key)) { alg = "SHA256withEC"; } else {//from www . j a v a 2 s. co m throw new NoSuchAlgorithmException(method + alg); } return createCertificationRequest(subjectName, key, (org.mozilla.jss.crypto.PrivateKey) keyPair.getPrivate(), alg, exts); }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test08EECrmfReqMultipleAuthModules() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { String modules = CmpConfiguration.AUTHMODULE_HMAC + ";" + CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE; String parameters = "foo123" + ";" + "TestCA"; this.cmpConfiguration.setAuthenticationModule(ALIAS, modules); this.cmpConfiguration.setAuthenticationParameters(ALIAS, parameters); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE", this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg);/*from ww w . ja va2 s . c om*/ //******************************************** final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(admCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //******************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert2 = checkCmpCertRepMessage(USER_DN, this.cacert, resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert2); removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test12EECrmfNotCheckAdmin() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA"); this.cmpConfiguration.setOmitVerificationsInECC(ALIAS, true); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Generating CrmfRequest failed.", msg); String adminName = "cmpTestAdmin"; KeyPair admkeys = KeyTools.genKeys("1024", "RSA"); AuthenticationToken adminToken = createAdminToken(admkeys, adminName, "CN=" + adminName + ",C=SE", this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate admCert = getCertFromCredentials(adminToken); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg);// w w w. j a v a 2s .co m //******************************************** final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(admCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //******************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); try { PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject()); assertNotNull(respObject); PKIBody body = respObject.getBody(); assertEquals(23, body.getType()); ErrorMsgContent err = (ErrorMsgContent) body.getContent(); String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrmsg = "Omitting some verifications can only be accepted in RA mode and when the CMP request has already been authenticated, for example, through the use of NestedMessageContent"; assertEquals(expectedErrmsg, errMsg); } finally { inputStream.close(); } removeAuthenticationToken(adminToken, admCert, adminName); }
From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java
void install(String[] redirectEndpointUrls, String[] postLogoutRedirectUrls, String logoutUrl) throws Exception { String domainControllerFQDN = this.relyingPartyConfig.getOpFQDN(); int domainControllerPort = Integer.parseInt(this.relyingPartyConfig.getOpListeningPort()); String tenant = this.relyingPartyConfig.getTenant(); // retrieve OIDC meta data MetadataHelper metadataHelper = new MetadataHelper.Builder(domainControllerFQDN) .domainControllerPort(domainControllerPort).tenant(tenant).keyStore(this.keyStore).build(); ProviderMetadata providerMetadata = metadataHelper.getProviderMetadata(); RSAPublicKey providerPublicKey = metadataHelper.getProviderRSAPublicKey(providerMetadata); // create a non-registered OIDC client and get bearer tokens by admin user name/password ConnectionConfig connectionConfig = new ConnectionConfig(providerMetadata, providerPublicKey, this.keyStore); ClientConfig clientConfig = new ClientConfig(connectionConfig, null, null); OIDCClient nonRegisteredClient = new OIDCClient(clientConfig); TokenSpec tokenSpec = new TokenSpec.Builder(TokenType.BEARER) .resourceServers(Arrays.asList("rs_admin_server")).build(); OIDCTokens oidcTokens = nonRegisteredClient.acquireTokensByPassword( this.relyingPartyConfig.getAdminUsername(), this.relyingPartyConfig.getAdminPassword(), tokenSpec); // create a private/public key pair, generate a certificate and assign it to a solution user name. Security.addProvider(new BouncyCastleProvider()); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); String solutionUserName = this.relyingPartyConfig.getClientPrefix() + UUID.randomUUID().toString(); X509Certificate clientCertificate = generateCertificate(keypair, solutionUserName); // create REST idm client IdmClient idmClient = createIdmClient(oidcTokens.getAccessToken(), domainControllerFQDN, domainControllerPort);/*from w ww .ja v a 2 s . c o m*/ VmdirClient vmdirClient = createVMdirClient(oidcTokens.getAccessToken(), domainControllerFQDN, domainControllerPort); // create a solution user CertificateDTO certificateDTO = new CertificateDTO.Builder() .withEncoded(convertToBase64PEMString(clientCertificate)).build(); SolutionUserDTO solutionUserDTO = new SolutionUserDTO.Builder().withName(solutionUserName) .withDomain(tenant).withCertificate(certificateDTO).build(); vmdirClient.solutionUser().create(tenant, solutionUserDTO); // add the solution user to ActAs group List<String> members = Arrays.asList(solutionUserName + "@" + tenant); vmdirClient.group().addMembers(tenant, "ActAsUsers", tenant, members, com.vmware.directory.rest.common.data.MemberType.USER); // register a OIDC client OIDCClientMetadataDTO oidcClientMetadataDTO = new OIDCClientMetadataDTO.Builder() .withRedirectUris(Arrays.asList(redirectEndpointUrls)) .withPostLogoutRedirectUris(Arrays.asList(postLogoutRedirectUrls)).withLogoutUri(logoutUrl) .withTokenEndpointAuthMethod("private_key_jwt") .withCertSubjectDN(clientCertificate.getSubjectDN().getName()) .withAuthnRequestClientAssertionLifetimeMS(2 * 60 * 1000L).build(); OIDCClientDTO oidcClientDTO = idmClient.oidcClient().register(tenant, oidcClientMetadataDTO); // persist data involved installation in files so they can be picked up in case server reboots savePublicKey(this.relyingPartyConfig.getOpPublickeyFile(), providerPublicKey); savePrivateKey(this.relyingPartyConfig.getRpPrivatekeyFile(), keypair.getPrivate()); writeObject(this.relyingPartyConfig.getRpCertificateFile(), clientCertificate); writeObject(this.relyingPartyConfig.getRpInfoFile(), oidcClientDTO.getClientId()); writeObject(this.relyingPartyConfig.getRpListeningPortFile(), this.relyingPartyConfig.getRpListeningPort()); }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
@Test public void test05EECrmfReq() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA"); this.cmpConfiguration.setRAMode(ALIAS, true); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); final X500Name testUserDN = new X500Name("CN=cmptestuser5,C=SE"); final String testUsername = "cmptestuser5"; String fingerprint = null;//from www . j a v a2 s . c o m String fingerprint2 = null; AuthenticationToken admToken = null; Certificate admCert = null; try { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, new DEROctetString(this.nonce)); assertNotNull("Generating CrmfRequest failed.", msg); KeyPair admkeys = KeyTools.genKeys("512", "RSA"); admToken = createAdminToken(admkeys, testUsername, testUserDN.toString(), this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); admCert = getCertFromCredentials(admToken); fingerprint = CertTools.getFingerprintAsString(admCert); CMPCertificate[] extraCert = getCMPCert(admCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(admCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); boolean verified = sig.verify(msg.getProtection().getBytes()); assertTrue("Signing the message failed.", verified); //*************************************************** final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(msg); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200, ALIAS); checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert2); fingerprint2 = CertTools.getFingerprintAsString(cert2); } finally { removeAuthenticationToken(admToken, admCert, testUsername); // also removes testUsername this.internalCertStoreSession.removeCertificate(fingerprint); this.internalCertStoreSession.removeCertificate(fingerprint2); } }