List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
private KeyPair createUserCert(int caid) throws AuthorizationDeniedException, UserDoesntFullfillEndEntityProfile, ApprovalException, WaitingForApprovalException, Exception, ObjectNotFoundException, AuthStatusException, AuthLoginException, IllegalKeyException, CADoesntExistsException { final String USERNAME = "ocsptest"; if (!endEntityManagementSession.existsUser(USERNAME)) { endEntityManagementSession.addUser(admin, USERNAME, "foo123", "C=SE,O=AnaTom,CN=OCSPTest", null, "ocsptest@anatom.se", false, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.TOKEN_SOFT_PEM, 0, caid); log.debug("created user: ocsptest, foo123, C=SE, O=AnaTom, CN=OCSPTest"); } else {//from ww w.j av a2s . c o m log.debug("User ocsptest already exists."); EndEntityInformation userData = new EndEntityInformation(USERNAME, "C=SE,O=AnaTom,CN=OCSPTest", caid, null, "ocsptest@anatom.se", EndEntityConstants.STATUS_NEW, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_PEM, 0, null); userData.setPassword("foo123"); endEntityManagementSession.changeUser(admin, userData, false); log.debug("Reset status to NEW"); } // Generate certificate for the new user KeyPair keys = KeyTools.genKeys("512", "RSA"); // user that we know exists... ocspTestCert = (X509Certificate) signSession.createCertificate(admin, USERNAME, "foo123", new PublicKeyWrapper(keys.getPublic())); assertNotNull("Failed to create new certificate", ocspTestCert); return keys; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java
/** * This test tests that the OCSP response contains the extension "id_pkix_ocsp_archive_cutoff" if "ocsp.expiredcert.retentionperiod" * is set in the condfiguration file/*from w ww . jav a2 s.c o m*/ * * @throws Exception */ @Test public void testExpiredCertArchiveCutoffExtension() throws Exception { final String username = "expiredCertUsername"; String cpname = "ValidityCertProfile"; String eepname = "ValidityEEProfile"; X509Certificate xcert = null; CertificateProfileSessionRemote certProfSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CertificateProfileSessionRemote.class); EndEntityProfileSessionRemote eeProfSession = EjbRemoteHelper.INSTANCE .getRemoteSession(EndEntityProfileSessionRemote.class); try { if (certProfSession.getCertificateProfile(cpname) == null) { final CertificateProfile cp = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); cp.setAllowValidityOverride(true); try { certProfSession.addCertificateProfile(admin, cpname, cp); } catch (CertificateProfileExistsException e) { log.error("Certificate profile exists: ", e); } } final int cpId = certProfSession.getCertificateProfileId(cpname); if (eeProfSession.getEndEntityProfile(eepname) == null) { final EndEntityProfile eep = new EndEntityProfile(true); eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId); try { eeProfSession.addEndEntityProfile(admin, eepname, eep); } catch (EndEntityProfileExistsException e) { log.error("Could not create end entity profile.", e); } } final int eepId = eeProfSession.getEndEntityProfileId(eepname); if (!endEntityManagementSession.existsUser(username)) { endEntityManagementSession.addUser(admin, username, "foo123", "CN=expiredCertUsername", null, "ocsptest@anatom.se", false, eepId, cpId, EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.TOKEN_SOFT_PEM, 0, caid); log.debug("created user: expiredCertUsername, foo123, CN=expiredCertUsername"); } else { log.debug("User expiredCertUsername already exists."); EndEntityInformation userData = new EndEntityInformation(username, "CN=expiredCertUsername", caid, null, "ocsptest@anatom.se", EndEntityConstants.STATUS_NEW, EndEntityTypes.ENDUSER.toEndEntityType(), eepId, cpId, null, null, SecConst.TOKEN_SOFT_PEM, 0, null); userData.setPassword("foo123"); endEntityManagementSession.changeUser(admin, userData, false); log.debug("Reset status to NEW"); } // Generate certificate for the new user KeyPair keys = KeyTools.genKeys("512", "RSA"); long now = (new Date()).getTime(); long notAfter = now + 1000; xcert = (X509Certificate) signSession.createCertificate(admin, username, "foo123", new PublicKeyWrapper(keys.getPublic()), -1, new Date(), new Date(notAfter)); assertNotNull("Failed to create new certificate", xcert); Thread.sleep(2000L); // wait for the certificate to expire // -------- Testing with default config value OCSPReqBuilder gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); OCSPReq req = gen.build(); BasicOCSPResp response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); SingleResp resp = response.getResponses()[0]; Extension singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNotNull("No extension sent with reply", singleExtension); ASN1GeneralizedTime extvalue = ASN1GeneralizedTime.getInstance(singleExtension.getParsedValue()); long expectedValue = (new Date()).getTime() - (31536000L * 1000); long actualValue = extvalue.getDate().getTime(); long diff = expectedValue - actualValue; assertTrue("Wrong archive cutoff value.", diff < 60000); // -------- Send a request where id_pkix_ocsp_archive_cutoff SHOULD NOT be used // set ocsp configuration Map<String, String> map = new HashMap<String, String>(); map.put(OcspConfiguration.EXPIREDCERT_RETENTIONPERIOD, "-1"); this.helper.alterConfig(map); gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); req = gen.build(); response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); resp = response.getResponses()[0]; singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNull("The wrong extension was sent with reply", singleExtension); // ------------ Send a request where id_pkix_ocsp_archive_cutoff SHOULD be used // set ocsp configuration map = new HashMap<String, String>(); map.put(OcspConfiguration.EXPIREDCERT_RETENTIONPERIOD, "63072000"); // 2 years this.helper.alterConfig(map); gen = new OCSPReqBuilder(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert, xcert.getSerialNumber())); req = gen.build(); response = helper.sendOCSPGet(req.getEncoded(), null, OCSPRespBuilder.SUCCESSFUL, 200); assertNotNull("Could not retrieve response, test could not continue.", response); resp = response.getResponses()[0]; singleExtension = resp.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_archive_cutoff); assertNotNull("No extension sent with reply", singleExtension); extvalue = ASN1GeneralizedTime.getInstance(singleExtension.getParsedValue()); expectedValue = (new Date()).getTime() - (63072000L * 1000); actualValue = extvalue.getDate().getTime(); diff = expectedValue - actualValue; assertTrue("Wrong archive cutoff value.", diff < 60000); } finally { endEntityManagementSession.revokeAndDeleteUser(admin, username, CRLReason.unspecified); eeProfSession.removeEndEntityProfile(admin, eepname); certProfSession.removeCertificateProfile(admin, cpname); } }
From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java
/** * Generates a self signed certificate using the given properties. * * @param commonName the subject's common name * @param organization the subject's organization name * @param organizationUnit the subject's organization unit name * @param stateOrProvince the subject's state or province * @param country the subject's country code * @param locality the subject's locality * @param algorithm the algorithm to use * @param keySize the keysize to use// www . ja v a 2 s . co m * @param signatureAlgorithm the signature algorithm to use * @param validFrom when the certificate is valid from * @param validTo when the certificate is valid until * @return The generated certificate * @throws Exception */ protected Pair<X509Certificate, PrivateKey> generateCertificate(String commonName, String organization, String organizationUnit, String stateOrProvince, String country, String locality, String algorithm, int keySize, String signatureAlgorithm, String validFrom, String validTo) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); // "RSA","BC" keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Generate self-signed certificate X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.C, country); builder.addRDN(BCStyle.ST, stateOrProvince); builder.addRDN(BCStyle.L, locality); builder.addRDN(BCStyle.OU, organizationUnit); builder.addRDN(BCStyle.O, organization); builder.addRDN(BCStyle.CN, commonName); Date notBefore = null; Date notAfter = null; if (validFrom == null) { notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); } else { DateTime notBeforeDateTime = DateUtil.getDateUtil().parseIfDate(validFrom); if (notBeforeDateTime == null) { throw new InternalServerErrorException("Invalid date format for 'validFrom' property"); } else { notBefore = notBeforeDateTime.toDate(); } } if (validTo == null) { Calendar date = Calendar.getInstance(); date.setTime(new Date()); date.add(Calendar.YEAR, 10); notAfter = date.getTime(); } else { DateTime notAfterDateTime = DateUtil.getDateUtil().parseIfDate(validTo); if (notAfterDateTime == null) { throw new InternalServerErrorException("Invalid date format for 'validTo' property"); } else { notAfter = notAfterDateTime.toDate(); } } BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore, notAfter, builder.build(), keyPair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC) .build(keyPair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC) .getCertificate(v3CertGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); return Pair.of(cert, keyPair.getPrivate()); }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
/** * Tests that EndEntityAuthentication module can be successfully used in client mode when the end entity's password is not stored in clear text. * /*from ww w . j av a2 s.c om*/ * @throws Exception */ @Test public void test21CrmfRequestClientModeEECNotClearPassword() throws Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-"); this.cmpConfiguration.setRAMode(ALIAS, false); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); final X500Name testUserDN = new X500Name("CN=cmptestuser21,C=SE"); final String testUsername = "cmptestuser21"; String fingerprint = null; String fingerprint2 = null; try { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123", new PublicKeyWrapper(keys.getPublic())); fingerprint = CertTools.getFingerprintAsString(cert); //Edit the status of the user to NEW createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(cert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(cert.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); 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 { try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } catch (Exception e) {// do nothing } this.internalCertStoreSession.removeCertificate(fingerprint); this.internalCertStoreSession.removeCertificate(fingerprint2); } }
From source file:com.qut.middleware.esoemanager.manager.logic.impl.ServiceCryptoImpl.java
public void createServiceKey(String serviceID) throws ServiceCryptoCreationException { String keyStorePassphrase;//w w w .j a v a2 s. c o m String keyPairName; String keyPairPassphrase; String keyPairSubjectDN; KeyPair spKeyPair; KeyStore keyStore; byte[] keyStoreBytes; try { Integer entID = new Integer(serviceID); if (entID.intValue() == this.esoeENTID) { keyPairSubjectDN = this.generateSubjectDN(this.esoeEntityID); } else { String serviceURL = null; Map<String, Object> description = this.managerDAO.queryServiceDescription(entID); if (description == null) throw new ServiceCryptoCreationException("Unable to retrieve serviceURL for this service"); serviceURL = (String) description.get(Constants.FIELD_SERVICE_URL); keyPairSubjectDN = this.generateSubjectDN(serviceURL); } keyPairName = this.identifierGenerator.generateXMLKeyName(); keyStorePassphrase = this.generatePassphrase(); keyPairPassphrase = this.generatePassphrase(); keyStore = this.cryptoProcessor.generateKeyStore(); spKeyPair = this.cryptoProcessor.generateKeyPair(); this.cryptoProcessor.addKeyPair(keyStore, keyStorePassphrase, spKeyPair, keyPairName, keyPairPassphrase, keyPairSubjectDN); keyStoreBytes = this.cryptoProcessor.convertKeystoreByteArray(keyStore, keyStorePassphrase); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(keyPairName); /* Determine expiry date of PKI data */ Calendar expiryDate = Calendar.getInstance(); expiryDate.add(Calendar.YEAR, this.cryptoProcessor.getCertExpiryIntervalInYears()); if (entID.intValue() == this.esoeENTID) { /** Commit key data to IDP reference */ Integer descID_IDP = this.managerDAO.getDescID(entID, Constants.IDP_DESCRIPTOR); this.managerDAO.insertPublicKey(descID_IDP, expiryDate.getTime(), keyPairName, this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(), this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic())); this.managerDAO.insertPKIData(descID_IDP, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase, keyPairName, keyPairPassphrase); /** Commit key data to PDP reference */ Integer descID_PDP = this.managerDAO.getDescID(entID, Constants.LXACML_PDP_DESCRIPTOR); this.managerDAO.insertPublicKey(descID_PDP, expiryDate.getTime(), keyPairName, this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(), this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic())); this.managerDAO.insertPKIData(descID_PDP, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase, keyPairName, keyPairPassphrase); /** Commit key data to Attribute Authority reference */ Integer descID_AA = this.managerDAO.getDescID(entID, Constants.ATTRIBUTE_AUTHORITY_DESCRIPTOR); this.managerDAO.insertPublicKey(descID_AA, expiryDate.getTime(), keyPairName, this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(), this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic())); this.managerDAO.insertPKIData(descID_AA, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase, keyPairName, keyPairPassphrase); } else { Integer descID = this.managerDAO.getDescID(entID, Constants.SP_DESCRIPTOR); this.managerDAO.insertPublicKey(descID, expiryDate.getTime(), keyPairName, this.cryptoProcessor.getCertIssuerDN(), certificate.getSerialNumber().toString(), this.cryptoProcessor.convertPublicKeyByteArray(spKeyPair.getPublic())); this.managerDAO.insertPKIData(descID, expiryDate.getTime(), keyStoreBytes, keyStorePassphrase, keyPairName, keyPairPassphrase); } } catch (NumberFormatException e) { throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e); } catch (ManagerDAOException e) { throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e); } catch (CryptoException e) { throw new ServiceCryptoCreationException(e.getLocalizedMessage(), e); } catch (KeyStoreException e) { throw new ServiceCryptoCreationException("Could not obtain certificate from new keystore.", e); } }
From source file:org.hyperledger.fabric.sdk.transaction.TransactionContext.java
private void processConfidentiality(Transaction transaction) throws CryptoException, IOException { // is confidentiality required? if (transaction.getTxBuilder().getConfidentialityLevel() != Chaincode.ConfidentialityLevel.CONFIDENTIAL) { // No confidentiality is required return;//from w ww. jav a 2s. c o m } logger.debug("Process Confidentiality ..."); // Set confidentiality level and protocol version transaction.getTxBuilder().setConfidentialityProtocolVersion("1.2"); // Generate transaction key. Common to all type of transactions KeyPair txKey = this.chain.getCryptoPrimitives().eciesKeyGen(); ASN1Encodable privBytes = this.chain.getCryptoPrimitives().ecdsaPrivateKeyToASN1(txKey.getPrivate()); // Generate stateKey. Transaction type dependent step. byte[] stateKey; if (transaction.getTxBuilder().getType() == Fabric.Transaction.Type.CHAINCODE_DEPLOY) { // The request is for a deploy stateKey = this.chain.getCryptoPrimitives().aesKeyGen(); } else if (transaction.getTxBuilder().getType() == Fabric.Transaction.Type.CHAINCODE_INVOKE) { // The request is for an execute // Empty state key stateKey = new byte[0]; } else { // The request is for a query logger.debug("Generate state key..."); stateKey = this.chain.getCryptoPrimitives().hmacAESTruncated( Hex.decode(this.member.getEnrollment().getQueryStateKey()), Arrays.concatenate(CONFIDENTIALITY_1_2_STATE_KD_C6, this.nonce)); } // Prepare ciphertexts // Encrypts message to validators using self.enrollChainKey ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { DERSequenceGenerator seq = new DERSequenceGenerator(byteArrayOutputStream); seq.addObject(new DEROctetString(privBytes)); seq.addObject(new DEROctetString(stateKey)); seq.close(); } catch (IOException e) { // ignore } logger.debug("Using chain key: " + this.member.getEnrollment().getChainKey()); PublicKey ecdsaChainKey = this.chain.getCryptoPrimitives() .ecdsaPEMToPublicKey(this.member.getEnrollment().getChainKey()); byte[] encMsgToValidators = this.chain.getCryptoPrimitives().eciesEncryptECDSA(ecdsaChainKey, byteArrayOutputStream.toByteArray()); transaction.getTxBuilder().setToValidators(ByteString.copyFrom(encMsgToValidators)); // Encrypts chaincodeID using txKey // logger.debug('CHAINCODE ID %s', transaction.chaincodeID); byte[] encryptedChaincodeID = this.chain.getCryptoPrimitives().eciesEncrypt(txKey.getPublic(), transaction.getTxBuilder().getChaincodeID().toByteArray()); transaction.getTxBuilder().setChaincodeID(ByteString.copyFrom(encryptedChaincodeID)); // Encrypts payload using txKey byte[] encryptedPayload = this.chain.getCryptoPrimitives().eciesEncrypt(txKey.getPublic(), transaction.getTxBuilder().getPayload().toByteArray()); transaction.getTxBuilder().setPayload(ByteString.copyFrom(encryptedPayload)); // Encrypt metadata using txKey if (transaction.getTxBuilder().getMetadata() != null && transaction.getTxBuilder().getMetadata().toByteArray() != null) { byte[] encryptedMetadata = this.chain.getCryptoPrimitives().eciesEncrypt(txKey.getPublic(), transaction.getTxBuilder().getMetadata().toByteArray()); transaction.getTxBuilder().setMetadata(ByteString.copyFrom(encryptedMetadata)); } }
From source file:org.asimba.wa.integrationtest.saml2.model.Response.java
public String getSignedMessage(SignatureHelper signatureHelper) { if (_responseDocument == null) { try {// w w w .j a va 2 s . c om _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true); } catch (OAException | XMLStreamException e) { _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e); return null; } } signatureHelper.tagIdAttributes(_responseDocument); KeyPair keypair = signatureHelper.getKeyPairFromKeystore(); // Set signing context with PrivateKey and root of the Document DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), _responseDocument.getDocumentElement()); // Get SignatureFactory for creating signatures in DOM: XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference ref = null; SignedInfo si = null; XMLSignature signature = null; try { // Create reference for "" -> root of the document // SAML requires enveloped transform List<Transform> transformsList = new ArrayList<>(); transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null)); ref = fac.newReference("#" + getId(), fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null); // Create SignedInfo (SAML2: Exclusive with or without comments is specified) // .. some selection here; nothing fancy, just trying to switch based on signing key format String sigMethod; String keyAlg = keypair.getPrivate().getAlgorithm(); if (keyAlg.contains("RSA")) { sigMethod = SignatureMethod.RSA_SHA1; } else if (keyAlg.contains("DSA")) { sigMethod = SignatureMethod.DSA_SHA1; } else { _logger.error("Unknown signing key algorithm: {}", keyAlg); return null; } si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigMethod, null), Collections.singletonList(ref)); // Add KeyInfo to the document: KeyInfoFactory kif = fac.getKeyInfoFactory(); // .. get key from the generated keypair: KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); signature = fac.newXMLSignature(si, ki); // Sign! signature.sign(dsc); String s = XMLUtils.getStringFromDocument(_responseDocument); _logger.info("Document after signing whole message:\n{}", s); return s; } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { _logger.error("Could not create reference to signable content: {}", e.getMessage(), e); return null; } catch (KeyException e) { _logger.error("Could not establish key info: {}", e.getMessage(), e); return null; } catch (MarshalException | XMLSignatureException e) { _logger.error("Error signing document: {}", e.getMessage(), e); return null; } catch (OAException e) { _logger.error("Error creating string from XML document: {}", e.getMessage(), e); return null; } }
From source file:org.hyperledger.fabric.sdk.MemberServicesFabricCAImpl.java
/** * Enroll the user with member service/* www .ja v a2s.c o m*/ * * @param req Enrollment request with the following fields: name, enrollmentSecret * @return enrollment */ public Enrollment enroll(EnrollmentRequest req) throws EnrollmentException { logger.debug(String.format("[MemberServicesFabricCAImpl.enroll] [%s]", req)); if (req == null) { throw new RuntimeException("req is not set"); } final String user = req.getEnrollmentID(); final String secret = req.getEnrollmentSecret(); if (StringUtil.isNullOrEmpty(user)) { throw new RuntimeException("req.enrollmentID is not set"); } if (StringUtil.isNullOrEmpty(secret)) { throw new RuntimeException("req.enrollmentSecret is not set"); } logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys..."); try { // generate ECDSA keys: signing and encryption keys KeyPair signingKeyPair = cryptoPrimitives.ecdsaKeyGen(); logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!"); // KeyPair encryptionKeyPair = cryptoPrimitives.ecdsaKeyGen(); PKCS10CertificationRequest csr = cryptoPrimitives.generateCertificationRequest(user, signingKeyPair); String pem = cryptoPrimitives.certificationRequestToPEM(csr); JsonObjectBuilder factory = Json.createObjectBuilder(); factory.add("certificate_request", pem); JsonObject postObject = factory.build(); StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = Json.createWriter(new PrintWriter(stringWriter)); jsonWriter.writeObject(postObject); jsonWriter.close(); String str = stringWriter.toString(); logger.debug("[MemberServicesFabricCAImpl.enroll] Generating keys...done!"); String responseBody = httpPost(url + COP_ENROLLMENBASE, str, new UsernamePasswordCredentials(user, secret)); logger.debug("response" + responseBody); JsonReader reader = Json.createReader(new StringReader(responseBody)); JsonObject jsonst = (JsonObject) reader.read(); String result = jsonst.getString("result"); boolean success = jsonst.getBoolean("success"); logger.debug(String.format("[MemberServicesFabricCAImpl] enroll success:[%s], result:[%s]", success, result)); if (!success) { EnrollmentException e = new EnrollmentException("COP Failed response success is false. " + result, new Exception()); logger.error(e.getMessage()); throw e; } Base64.Decoder b64dec = Base64.getDecoder(); String signedPem = new String(b64dec.decode(result.getBytes())); logger.info(String.format("[MemberServicesFabricCAImpl] enroll returned pem:[%s]", signedPem)); Enrollment enrollment = new Enrollment(); enrollment.setKey(signingKeyPair); enrollment.setPublicKey(Hex.toHexString(signingKeyPair.getPublic().getEncoded())); enrollment.setCert(signedPem); return enrollment; } catch (Exception e) { EnrollmentException ee = new EnrollmentException(String.format("Failed to enroll user %s ", user), e); logger.error(ee.getMessage(), ee); throw ee; } }
From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java
/** Test CMP initial request against EJBCA CMP in client mode (operationmode=normal) using End Entity certificate signature authentication, * i.e. the request is signed by a certificate of the same end entity making the request, and this signature is used for authenticating the end entity. * Test://from w ww . j a v a 2 s .c om * - Request signed by a fake certificate, i.e. one that is not in the database (FAIL) * - Request signed by a certificate that beloongs to another user (FAIL) * - Request signed by a proper certificate but where user status is not NEW (FAIL) * - Request signed by a proper, but revoked certificate (FAIL) * - A working request signed by a proper, unrevoked certificate and user status is NEW (SUCCESS) * * @throws Exception on some errors */ @Test public void test18CrmfReqClientModeEESignature() throws Exception { this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE); this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-"); this.cmpConfiguration.setRAMode(ALIAS, false); this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration); final X500Name testUserDN = new X500Name("CN=cmptestuser16,C=SE"); final String testUsername = "cmptestuser16"; final String otherUserDN = "CN=cmptestotheruser16,C=SE"; final String otherUsername = "cmptestotheruser16"; String fingerprint = null; String fingerprint2 = null; String fingerprint3 = null; try { KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); KeyPair fakeKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); createUser(testUsername, testUserDN.toString(), "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // A real certificate that can be used to sign the message Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123", new PublicKeyWrapper(keys.getPublic())); fingerprint = CertTools.getFingerprintAsString(cert); // A fake certificate that should not be valid Certificate fakeCert = CertTools.genSelfCert(testUserDN.toString(), 30, null, fakeKeys.getPrivate(), fakeKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false); // Step 1 sign with fake certificate, should not be valid as end entity authentication { AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(fakeCert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, fakeKeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(fakeCert.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); // This should have failed checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp)); PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject()); try { 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 = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database."; assertEquals(expectedErrMsg, errMsg); } finally { inputStream.close(); } } // Step 2, sign the request with a certificate that does not belong to the user { KeyPair otherKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); createUser(otherUsername, otherUserDN, "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // A real certificate that can be used to sign the message Certificate othercert = this.signSession.createCertificate(ADMIN, otherUsername, "foo123", new PublicKeyWrapper(otherKeys.getPublic())); fingerprint2 = CertTools.getFingerprintAsString(cert); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(othercert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, otherKeys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(othercert.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); // This should have failed checkCmpResponseGeneral(resp, issuerDN, testUserDN, 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 = "The End Entity certificate attached to the PKIMessage in the extraCert field does not belong to user '" + testUsername + "'"; assertEquals(expectedErrMsg, errMsg); } finally { inputStream.close(); } } // Step 3 sign with the real certificate, but user status is not NEW AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption); PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false, null, null, null, null, pAlg, null); assertNotNull("Generating CrmfRequest failed.", msg); CMPCertificate[] extraCert = getCMPCert(cert); msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(), pAlg.getAlgorithm().getId(), "BC"); assertNotNull(msg); //******************************************'''''' final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(cert.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(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); // This should have failed 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 = "Got request with status GENERATED (40), NEW, FAILED or INPROCESS required: cmptestuser16."; assertEquals(expectedErrMsg, errMsg); // Step 4 now set status to NEW, and a clear text password, then it should finally work createUser(testUsername, testUserDN.toString(), "randompasswordhere", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); // Send request and receive response final byte[] resp2 = sendCmpHttp(ba, 200, ALIAS); CertReqMessages ir = (CertReqMessages) msg.getBody().getContent(); Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp2, ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue()); assertNotNull("CrmfRequest did not return a certificate", cert2); fingerprint3 = CertTools.getFingerprintAsString(cert2); // Step 5, revoke the certificate and try again { this.certificateStoreSession.setRevokeStatus(ADMIN, cert, RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION, null); final byte[] resp3 = sendCmpHttp(ba, 200, ALIAS); // This should have failed checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert, msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(), false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId()); ASN1InputStream inputStream3 = new ASN1InputStream(new ByteArrayInputStream(resp3)); try { PKIMessage respObject3 = PKIMessage.getInstance(inputStream3.readObject()); assertNotNull(respObject); PKIBody body3 = respObject3.getBody(); assertEquals(23, body3.getType()); err = (ErrorMsgContent) body3.getContent(); String errMsg3 = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString(); String expectedErrMsg3 = "The certificate attached to the PKIMessage in the extraCert field is not active."; assertEquals(expectedErrMsg3, errMsg3); } finally { inputStream3.close(); } } } finally { inputStream.close(); } } finally { try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused); } catch (Exception e) {// do nothing } try { this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, otherUsername, ReasonFlags.unused); } catch (Exception e) {// do nothing } this.internalCertStoreSession.removeCertificate(fingerprint); this.internalCertStoreSession.removeCertificate(fingerprint2); this.internalCertStoreSession.removeCertificate(fingerprint3); } }
From source file:org.asimba.wa.integrationtest.saml2.model.Response.java
/** * Requires the responseDocument to be already initialized, just adding another * Signature section to the existing documnet * @param signatureHelper// ww w . jav a 2 s . c o m * @return */ public String getMessageWithSignedAssertion(SignatureHelper signatureHelper) { if (_responseDocument == null) { try { _responseDocument = XMLUtils.getDocumentFromString(getResponse(plain), true); } catch (OAException | XMLStreamException e) { _logger.error("Problem when establishing XML document to sign: {}", e.getMessage(), e); return null; } } KeyPair keypair = signatureHelper.getKeyPairFromKeystore(); // Set signing context with PrivateKey and root of the Document Node localRoot = _assertion.getAssertionNode(); signatureHelper.tagIdAttributes(localRoot.getOwnerDocument()); DOMSignContext dsc = new DOMSignContext(keypair.getPrivate(), localRoot); // Get SignatureFactory for creating signatures in DOM: XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); Reference refAssertion = null; SignedInfo si = null; XMLSignature signature = null; try { // Create reference for "" -> Assertion in the document // SAML requires enveloped transform List<Transform> transformsList = new ArrayList<>(); transformsList.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // transformsList.add(fac.newTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS, (TransformParameterSpec) null)); refAssertion = fac.newReference("#" + getAssertion().getId(), fac.newDigestMethod(DigestMethod.SHA1, null), transformsList, null, null); // Create SignedInfo (SAML2: Exclusive with or without comments is specified) // .. some selection here; nothing fancy, just trying to switch based on signing key format String sigMethod; String keyAlg = keypair.getPrivate().getAlgorithm(); if (keyAlg.contains("RSA")) { sigMethod = SignatureMethod.RSA_SHA1; } else if (keyAlg.contains("DSA")) { sigMethod = SignatureMethod.DSA_SHA1; } else { _logger.error("Unknown signing key algorithm: {}", keyAlg); return null; } si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigMethod, null), Collections.singletonList(refAssertion)); // Add KeyInfo to the document: KeyInfoFactory kif = fac.getKeyInfoFactory(); // .. get key from the generated keypair: KeyValue kv = kif.newKeyValue(keypair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); signature = fac.newXMLSignature(si, ki); // before: _logger.info("Signing assertion in document"); // _logger.info("Document to sign:\n{}", XMLUtils.getStringFromDocument(localRoot.getOwnerDocument())); // Sign! signature.sign(dsc); return XMLUtils.getStringFromDocument(localRoot.getOwnerDocument()); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) { _logger.error("Could not create reference to signable content: {}", e.getMessage(), e); return null; } catch (KeyException e) { _logger.error("Could not establish key info: {}", e.getMessage(), e); return null; } catch (MarshalException | XMLSignatureException e) { _logger.error("Error signing document: {}", e.getMessage(), e); return null; } catch (OAException e) { _logger.error("Error creating string from XML document: {}", e.getMessage(), e); return null; } }