List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.gluu.super_gluu.u2f.v2.device.U2FKeyImpl.java
@Override public EnrollmentResponse register(EnrollmentRequest enrollmentRequest) throws U2FException { if (BuildConfig.DEBUG) Log.d(TAG, ">> register"); String application = enrollmentRequest.getApplication(); String challenge = enrollmentRequest.getChallenge(); if (BuildConfig.DEBUG) Log.d(TAG, "-- Inputs --"); if (BuildConfig.DEBUG) Log.d(TAG, "application: " + application); if (BuildConfig.DEBUG) Log.d(TAG, "challenge: " + challenge); byte userPresent = userPresenceVerifier.verifyUserPresence(); if ((userPresent & AuthenticateRequest.USER_PRESENT_FLAG) == 0) { throw new U2FException("Cannot verify user presence"); }/*from w w w .ja v a 2 s.com*/ KeyPair keyPair = keyPairGenerator.generateKeyPair(); byte[] keyHandle = keyPairGenerator.generateKeyHandle(); TokenEntry tokenEntry = new TokenEntry(keyPairGenerator.keyPairToJson(keyPair), enrollmentRequest.getApplication(), enrollmentRequest.getOxPush2Request().getIssuer()); tokenEntry.setCreatedDate(enrollmentRequest.getOxPush2Request().getCreated()); tokenEntry.setUserName(enrollmentRequest.getOxPush2Request().getUserName()); tokenEntry.setAuthenticationMode(enrollmentRequest.getOxPush2Request().getMethod()); tokenEntry.setKeyHandle(keyHandle); String keyHandleTitle = tokenEntry.getIssuer(); ; tokenEntry.setKeyName(keyHandleTitle); final boolean oneStep = Utils.isEmpty(enrollmentRequest.getOxPush2Request().getUserName()); String authenticationType = GluuApplication.get() .getString(oneStep ? R.string.one_step : R.string.two_step); tokenEntry.setAuthenticationType(authenticationType); dataStore.storeTokenEntry(tokenEntry); byte[] userPublicKey = keyPairGenerator.encodePublicKey(keyPair.getPublic()); byte[] applicationSha256 = DigestUtils.sha256(application); byte[] challengeSha256 = DigestUtils.sha256(challenge); byte[] signedData = rawMessageCodec.encodeRegistrationSignedBytes(applicationSha256, challengeSha256, keyHandle, userPublicKey); if (BuildConfig.DEBUG) Log.d(TAG, "Signing bytes " + Utils.encodeHexString(signedData)); byte[] signature = keyPairGenerator.sign(signedData, certificatePrivateKey); if (BuildConfig.DEBUG) Log.d(TAG, "-- Outputs --"); if (BuildConfig.DEBUG) Log.d(TAG, "userPublicKey: " + Utils.encodeHexString(userPublicKey)); if (BuildConfig.DEBUG) Log.d(TAG, "keyHandle: " + Utils.base64UrlEncode(keyHandle)); if (BuildConfig.DEBUG) Log.d(TAG, "vendorCertificate: " + vendorCertificate); if (BuildConfig.DEBUG) Log.d(TAG, "signature: " + Utils.encodeHexString(signature)); if (BuildConfig.DEBUG) Log.d(TAG, "<< register"); return new EnrollmentResponse(userPublicKey, keyHandle, vendorCertificate, signature); }
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./*from w ww . j ava 2 s. c o m*/ * * @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; }
From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java
/** * Method that generates the keys that will be used by the CAToken. * The method can be used to generate keys for an initial CA token or to renew Certificate signing keys. * If setstatustowaiting is true and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN. * If setstatustowaiting is false and you generate new keys, the new keys will be available as SecConst.CAKEYPURPOSE_CERTSIGN_NEXT. * //from w w w .j a va 2 s . c om * @param authenticationCode the password used to encrypt the keystore, later needed to activate CA Token * @param renew flag indicating if the keys are renewed instead of created fresh. Renewing keys does not * create new encryption keys, since this would make it impossible to decrypt old stuff. * @param activate flag indicating if the new keys should be activated immediately or or they should be added as "next" signing key. * Using true here makes it possible to generate certificate renewal requests for external CAs still using the old keys until the response is received. */ public void generateKeys(final String authenticationCode, final boolean renew, final boolean activate) throws Exception { if (log.isTraceEnabled()) { log.trace(">generateKeys: " + (authenticationCode == null ? "null" : "hidden") + ", renew=" + renew + ", activate=" + activate); } CATokenInfo catokeninfo = getCATokenInfo(); // First we start by setting a new sequence for our new keys String oldSequence = getKeySequence(); log.debug("Current sequence: " + oldSequence); String newSequence = StringTools.incrementKeySequence(getCATokenInfo().getKeySequenceFormat(), oldSequence); // We store the sequence permanently in the object last, when we know everything went well // If we don't give an authentication code, perhaps we have autoactivation enabled char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode); String tokentype = null; // Then we can move on to actually generating the keys if (catokeninfo instanceof SoftCATokenInfo) { // If we have an existing soft keystore verify that the password is correct checkSoftKeystorePassword(authenticationCode); SoftCATokenInfo info = (SoftCATokenInfo) catokeninfo; Properties properties = getProperties(); PublicKey pubEnc = null; PrivateKey privEnc = null; PublicKey previousPubSign = null; PrivateKey previousPrivSign = null; PublicKey oldPreviousPubSign = null; PrivateKey oldPreviousPrivSign = null; if (!renew) { log.debug("We are generating initial keys."); // Generate encryption keys. // Encryption keys must be RSA still KeyPair enckeys = KeyTools.genKeys(info.getEncKeySpec(), info.getEncKeyAlgorithm()); pubEnc = enckeys.getPublic(); privEnc = enckeys.getPrivate(); } else { log.debug("We are renewing keys."); // Get the already existing encryption and signature keys ICAToken token = getCAToken(); pubEnc = token.getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); privEnc = token.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); previousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN); previousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN); oldPreviousPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS); oldPreviousPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_PREVIOUS); } // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key // If the user did not specify this, we try to generate a key with the same specification as the currently used key. String keyspec = info.getSignKeySpec(); // can be "unknown" if (StringUtils.equals(keyspec, AlgorithmTools.KEYSPEC_UNKNOWN)) { keyspec = null; } AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(previousPubSign); if (log.isDebugEnabled()) { if (keyspec != null) { log.debug("Generating new Soft key with specified spec " + keyspec + " with label " + SoftCAToken.PRIVATESIGNKEYALIAS); } else { int keySize = KeyTools.getKeyLength(previousPubSign); String alg = previousPubSign.getAlgorithm(); log.debug("Generating new Soft " + alg + " key with spec " + paramspec + " (size=" + keySize + ") with label " + SoftCAToken.PRIVATESIGNKEYALIAS); } } // Generate signature keys. KeyPair newsignkeys = KeyTools.genKeys(keyspec, paramspec, info.getSignKeyAlgorithm()); // Create the new keystore and add the new signature keys KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // PLay with aliases depending on if we activate the new key or not String newSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS; String previousSignKeyAlias = SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS; if (!activate) { // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS) newSignKeyAlias = SoftCAToken.NEXTPRIVATESIGNKEYALIAS; previousSignKeyAlias = SoftCAToken.PRIVATESIGNKEYALIAS; } log.debug("Setting newsignkeys as " + newSignKeyAlias + " in soft CA token."); Certificate[] certchain = new Certificate[1]; // generate dummy certificate String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(newsignkeys.getPublic()).iterator() .next(); certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, newsignkeys.getPrivate(), newsignkeys.getPublic(), sigAlg, true); keystore.setKeyEntry(newSignKeyAlias, newsignkeys.getPrivate(), null, certchain); if (!activate) { log.debug("Set next sequence: " + newSequence); properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence); log.debug("Set nextCertSignKey: " + newSignKeyAlias); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newSignKeyAlias); } // If we have an old key (i.e. generating new keys), we will store the old one as "previous" if (previousPrivSign != null) { log.debug("Setting previousPrivSign as " + previousSignKeyAlias + " in soft CA token."); sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(previousPubSign).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, previousPrivSign, previousPubSign, sigAlg, true); keystore.setKeyEntry(previousSignKeyAlias, previousPrivSign, null, certchain); // Now this keystore should have this previous key if (activate) { // This key pair is now moved down to previous sign key properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, previousSignKeyAlias); // Set previous sequence so we can create link certificates log.debug("Set previous sequence : " + oldSequence); properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence); } else { // If we have an old previous key and we are not activating the new key, we will keep this one as "previous" // If the new keys are activate the old previous keys are trashed and replaced by the old active signature key String prevProp = properties.getProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS); // If we don't have a previous key don't try to add it if ((oldPreviousPrivSign != null) && (prevProp != null)) { log.debug("Setting old previousprivatesignkeyalias as " + SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS + " in soft CA token."); sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(oldPreviousPubSign).iterator() .next(); certchain[0] = CertTools.genSelfCert("CN=dummy3", 36500, null, oldPreviousPrivSign, oldPreviousPubSign, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS, oldPreviousPrivSign, null, certchain); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS); } else { log.debug("No previousprivatesignkeyalias exists, not setting any previous key."); } } } // Finally install the old encryption/decryption keys as well sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(pubEnc).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, privEnc, pubEnc, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, privEnc, null, certchain); storeSoftKeyStore(authCode, info, properties, keystore); tokentype = "Soft"; // for logging } else if (catokeninfo instanceof HardCATokenInfo) { ICAToken token = getCAToken(); if (token instanceof PKCS11CAToken) { Properties properties = getProperties(); PublicKey pubK = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN); String keyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CERTSIGN); log.debug("Old key label is: " + keyLabel); String crlKeyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CRLSIGN); // The key label to use for the new key // Remove the old sequence from the end of the key label and replace it with the // new label. If no label was present just concatenate the new label String newKeyLabel = StringUtils.removeEnd(keyLabel, oldSequence) + newSequence; log.debug("New key label is: " + newKeyLabel); final KeyStore.PasswordProtection pwp = new KeyStore.PasswordProtection(authCode); // As first choice we check if the used have specified which type of key should be generated, this can be different from the currently used key // If the user did not specify this, we try to generate a key with the same specification as the currently used key. String keyspec = properties.getProperty(ICAToken.KEYSPEC_PROPERTY); // can be null, and that is ok AlgorithmParameterSpec paramspec = KeyTools.getKeyGenSpec(pubK); if (log.isDebugEnabled()) { String sharedLibrary = properties.getProperty(PKCS11CAToken.SHLIB_LABEL_KEY); String slot = properties.getProperty(PKCS11CAToken.SLOT_LABEL_KEY); String attributesFile = properties.getProperty(PKCS11CAToken.ATTRIB_LABEL_KEY); if (keyspec != null) { log.debug("Generating new PKCS#11 key with specified spec " + keyspec + " with label " + newKeyLabel + ", on slot " + slot + ", using sharedLibrary " + sharedLibrary + ", and attributesFile " + attributesFile); } else { int keySize = KeyTools.getKeyLength(pubK); String alg = pubK.getAlgorithm(); log.debug("Generating new PKCS#11 " + alg + " key with spec " + paramspec + " (size=" + keySize + ") with label " + newKeyLabel + ", on slot " + slot + ", using sharedLibrary " + sharedLibrary + ", and attributesFile " + attributesFile); } } KeyStoreContainer cont = KeyStoreContainerFactory .getInstance(KeyStoreContainer.KEYSTORE_TYPE_PKCS11, token.getProvider(), pwp); cont.setPassPhraseLoadSave(authCode); if (keyspec != null) { log.debug("Generating from string keyspec: " + keyspec); cont.generate(keyspec, newKeyLabel); } else { log.debug("Generating from AlgorithmParameterSpec: " + paramspec); cont.generate(paramspec, newKeyLabel); } // Set properties so that we will start using the new key, or not, depending on the activate argument KeyStrings kstr = new KeyStrings(properties); String certsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CERTSIGN); log.debug("CAKEYPURPOSE_CERTSIGN keystring is: " + certsignkeystr); String crlsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CRLSIGN); log.debug("CAKEYPURPOSE_CRLSIGN keystring is: " + crlsignkeystr); if (!activate) { // If the new keys are not activated we must still use the old key as active signing key (PRIVATESIGNKEYALIAS) log.debug("Set nextCertSignKey: " + newKeyLabel); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_NEXT, newKeyLabel); log.debug("Set next sequence: " + newSequence); properties.setProperty(ICAToken.NEXT_SEQUENCE_PROPERTY, newSequence); } else { properties.setProperty(certsignkeystr, newKeyLabel); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, keyLabel); // If the key strings are not equal, i.e. crtSignKey and crlSignKey was used instead of just defaultKey // and the keys are the same. Then we need to set both keys to use the new key label if (!StringUtils.equals(certsignkeystr, crlsignkeystr) && StringUtils.equals(keyLabel, crlKeyLabel)) { log.debug("Also setting crlsignkeystr to " + newKeyLabel); properties.setProperty(crlsignkeystr, newKeyLabel); } // Also set the previous sequence properties.setProperty(ICAToken.PREVIOUS_SEQUENCE_PROPERTY, oldSequence); } setProperties(properties); tokentype = "PKCS#11"; // for logging } } else { String msg = intres.getLocalizedMessage("catoken.genkeysnotavail"); log.error(msg); return; } // Store the new sequence permanently. We should not do this earlier, because if an error is thrown generating keys we should not have updated the CA token object if (activate) { log.debug("Setting new sequence: " + newSequence); setKeySequence(newSequence); } // Finally reset the token so it will be re-read when we want to use it this.catoken = null; String msg = intres.getLocalizedMessage("catoken.generatedkeys", tokentype); log.info(msg); if (log.isTraceEnabled()) { log.trace("<generateKeys"); } }
From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java
@Test public void test09CrmfWrongIssuerAndDoNotCheckAdmin() throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException, EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception { this.cmpConfiguration.setAuthenticationParameters(cmpAlias, "-;foo123"); this.cmpConfiguration.setOmitVerificationsInECC(cmpAlias, true); this.globalConfigurationSession.saveConfiguration(this.admin, this.cmpConfiguration); //-----------------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 w w w .ja va 2 s . c om 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)); KeyPair nonAdminKeys = KeyTools.genKeys("1024", "RSA"); Certificate nonAdminCert = CertTools.genSelfCert("CN=cmpTestAdmin,C=SE", 365, null, nonAdminKeys.getPrivate(), nonAdminKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false); CMPCertificate[] cmpcert = getCMPCert(nonAdminCert); crmfMsg = CmpMessageHelper.buildCertBasedPKIProtection(crmfMsg, cmpcert, nonAdminKeys.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"); 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); //final byte[] resp = sendCmpHttp(myPKIMessage.toASN1Primitive().toASN1Object().getEncoded(), 200); // 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); assertNotNull("CrmfRequest did not return a certificate", cert); assertTrue(cert instanceof X509Certificate); log.debug("Subject DN of created certificate: " + X500Name.getInstance(((X509Certificate) cert).getSubjectX500Principal().getEncoded())); }
From source file:org.gluu.com.ox_push2.u2f.v2.device.U2FKeyImpl.java
@Override public EnrollmentResponse register(EnrollmentRequest enrollmentRequest) throws U2FException { if (BuildConfig.DEBUG) Log.d(TAG, ">> register"); String application = enrollmentRequest.getApplication(); String challenge = enrollmentRequest.getChallenge(); if (BuildConfig.DEBUG) Log.d(TAG, "-- Inputs --"); if (BuildConfig.DEBUG) Log.d(TAG, "application: " + application); if (BuildConfig.DEBUG) Log.d(TAG, "challenge: " + challenge); byte userPresent = userPresenceVerifier.verifyUserPresence(); if ((userPresent & AuthenticateRequest.USER_PRESENT_FLAG) == 0) { throw new U2FException("Cannot verify user presence"); }/*from w ww. j av a2 s . c o m*/ KeyPair keyPair = keyPairGenerator.generateKeyPair(); byte[] keyHandle = keyPairGenerator.generateKeyHandle(); TokenEntry tokenEntry = new TokenEntry(keyPairGenerator.keyPairToJson(keyPair), enrollmentRequest.getApplication(), enrollmentRequest.getOxPush2Request().getIssuer()); tokenEntry.setCreatedDate(enrollmentRequest.getOxPush2Request().getCreated()); tokenEntry.setUserName(enrollmentRequest.getOxPush2Request().getUserName()); tokenEntry.setAuthenticationMode(enrollmentRequest.getOxPush2Request().getMethod()); tokenEntry.setKeyHandle(keyHandle); String serverName = tokenEntry.getIssuer(); String prefixKeyHandle = "Key for "; String keyHandleTitle = prefixKeyHandle + " " + serverName; tokenEntry.setKeyName(keyHandleTitle); final boolean oneStep = Utils.isEmpty(enrollmentRequest.getOxPush2Request().getUserName()); String authenticationType = oneStep ? ONE_STEP : TWO_STEP; tokenEntry.setAuthenticationType(authenticationType); dataStore.storeTokenEntry(keyHandle, tokenEntry); byte[] userPublicKey = keyPairGenerator.encodePublicKey(keyPair.getPublic()); byte[] applicationSha256 = DigestUtils.sha256(application); byte[] challengeSha256 = DigestUtils.sha256(challenge); byte[] signedData = rawMessageCodec.encodeRegistrationSignedBytes(applicationSha256, challengeSha256, keyHandle, userPublicKey); if (BuildConfig.DEBUG) Log.d(TAG, "Signing bytes " + Utils.encodeHexString(signedData)); byte[] signature = keyPairGenerator.sign(signedData, certificatePrivateKey); if (BuildConfig.DEBUG) Log.d(TAG, "-- Outputs --"); if (BuildConfig.DEBUG) Log.d(TAG, "userPublicKey: " + Utils.encodeHexString(userPublicKey)); if (BuildConfig.DEBUG) Log.d(TAG, "keyHandle: " + Utils.base64UrlEncode(keyHandle)); if (BuildConfig.DEBUG) Log.d(TAG, "vendorCertificate: " + vendorCertificate); if (BuildConfig.DEBUG) Log.d(TAG, "signature: " + Utils.encodeHexString(signature)); if (BuildConfig.DEBUG) Log.d(TAG, "<< register"); return new EnrollmentResponse(userPublicKey, keyHandle, vendorCertificate, signature); }
From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java
protected Certificate generateCertificate(KeyPair keyPair, String alias) throws GeneralSecurityException { //test that Bouncy Castle provider is present and add it if it's not if (Security.getProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); }/*ww w .j a va2 s. c o m*/ X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); // X509Name nameInfo = new X509Name(false,"CN=" + alias); certificateGenerator.setSignatureAlgorithm("MD5WithRSA"); certificateGenerator.setSerialNumber(new java.math.BigInteger("1")); X509Principal nameInfo = new X509Principal("CN=" + alias); certificateGenerator.setIssuerDN(nameInfo); certificateGenerator.setSubjectDN(nameInfo); // note: same as issuer for self signed certificateGenerator.setNotBefore(new Date()); Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, CLIENT_CERT_EXPIRATION_DAYS); certificateGenerator.setNotAfter(c.getTime()); certificateGenerator.setPublicKey(keyPair.getPublic()); return certificateGenerator.generate(keyPair.getPrivate(), org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected static PKIMessage genRenewalReq(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid, KeyPair keys, boolean raVerifiedPopo, X500Name reqSubjectDN, String reqIssuerDN, AlgorithmIdentifier pAlg, DEROctetString senderKID) throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateEncodingException { CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); ASN1EncodableVector optionalValidityV = 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()); optionalValidityV.add(new DERTaggedObject(true, 0, nb)); optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); myCertTemplate.setValidity(myOptionalValidity); if (reqSubjectDN != null) { myCertTemplate.setSubject(reqSubjectDN); }//from w w w .j a v a 2 s.co m if (reqIssuerDN != null) { myCertTemplate.setIssuer(new X500Name(reqIssuerDN)); } byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try { SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); } finally { dIn.close(); } CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); // POPO /* * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8, * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 })); * * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new * byte[] { 44 }), 2); //take choice pos tag 2 * * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput( * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2, * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 })); */ ProofOfPossession myProofOfPossession = null; if (raVerifiedPopo) { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream mout = new DEROutputStream(baos); mout.writeObject(myCertRequest); mout.close(); byte[] popoProtectionBytes = baos.toByteArray(); String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm()) .getId(); Signature sig = Signature.getInstance(sigalg); sig.initSign(keys.getPrivate()); sig.update(popoProtectionBytes); DERBitString bs = new DERBitString(sig.sign()); POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs); myProofOfPossession = new ProofOfPossession(myPOPOSigningKey); } // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new // DERInteger(1122334455))); 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(userDN), new GeneralName(new JcaX509CertificateHolder((X509Certificate) cacert).getSubject())); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(pAlg); myPKIHeader.setSenderKID(senderKID); PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.texai.x509.X509Utils.java
/** Generates the X.509 security information. * * @param keyPair the key pair for the generated certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's certificate * @param uid the generated certificate's subject UID * @param keystorePassword the keystore password * @param isJCEUnlimitedStrengthPolicy the indicator whether the generated X.509 security information will be * hosted on a system with unlimited strength policy * @param domainComponent the domain component * @return the X509 security information *//*from ww w . j a va2 s . c o m*/ public static X509SecurityInfo generateX509SecurityInfo(final KeyPair keyPair, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid, final char[] keystorePassword, final boolean isJCEUnlimitedStrengthPolicy, final String domainComponent) { //Preconditions assert keyPair != null : "keyPair must not be null"; assert issuerPrivateKey != null : "issuerPrivateKey must not be null"; assert issuerCertificate != null : "issuerCertificate must not be null"; assert uid != null : "uid must not be null"; assert keystorePassword != null : "keystorePassword must not be null"; try { final X509Certificate x509Certificate = generateX509Certificate(keyPair.getPublic(), issuerPrivateKey, issuerCertificate, uid, domainComponent); assert X509Utils.isJCEUnlimitedStrengthPolicy(); final KeyStore keyStore; if (isJCEUnlimitedStrengthPolicy) { keyStore = KeyStore.getInstance("UBER", BOUNCY_CASTLE_PROVIDER); } else { keyStore = KeyStore.getInstance("JCEKS"); } keyStore.load(null, null); keyStore.setKeyEntry(X509Utils.ENTRY_ALIAS, keyPair.getPrivate(), keystorePassword, new Certificate[] { x509Certificate, X509Utils.getRootX509Certificate() }); return new X509SecurityInfo(X509Utils.getTruststore(), keyStore, keystorePassword, null); } catch (NoSuchProviderException | NoSuchAlgorithmException | SignatureException | InvalidKeyException | IOException | KeyStoreException | CertificateException ex) { throw new TexaiException(ex); } }
From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java
@Override public void init(final CryptoToken cryptoToken, final CA ca, final AvailableCustomCertificateExtensionsConfiguration cceConfig) throws Exception { if (log.isTraceEnabled()) { log.trace(">init"); }/* w ww . ja v a 2 s . c o m*/ if (info.getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) { if (log.isDebugEnabled()) { log.debug("Not generating certificates for inactive service"); } } else { // lookup keystore passwords final String keystorepass = StringTools.passwordDecryption(EjbcaConfiguration.getCaCmsKeyStorePass(), "ca.cmskeystorepass"); // Currently only RSA keys are supported final CmsCAServiceInfo info = (CmsCAServiceInfo) getExtendedCAServiceInfo(); // Create KeyStore final KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); final KeyPair cmskeys = KeyTools.genKeys(info.getKeySpec(), info.getKeyAlgorithm()); // A simple hard coded certificate profile that works for the CMS CA service final CertificateProfile certProfile = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); certProfile.setUseKeyUsage(true); certProfile.setKeyUsage(new boolean[9]); certProfile.setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true); certProfile.setKeyUsage(CertificateConstants.KEYENCIPHERMENT, true); certProfile.setKeyUsage(CertificateConstants.DATAENCIPHERMENT, true); certProfile.setKeyUsageCritical(true); final EndEntityInformation eeInformation = new EndEntityInformation("NOUSERNAME", info.getSubjectDN(), 0, info.getSubjectAltName(), "NOEMAIL", 0, new EndEntityType(), 0, 0, null, null, 0, 0, null); final Certificate certificate = ca.generateCertificate(cryptoToken, eeInformation, cmskeys.getPublic(), -1, null, ca.getEncodedValidity(), certProfile, null, cceConfig); certificatechain = new ArrayList<Certificate>(); certificatechain.add(certificate); certificatechain.addAll(ca.getCertificateChain()); privKey = cmskeys.getPrivate(); keystore.setKeyEntry(PRIVATESIGNKEYALIAS, cmskeys.getPrivate(), null, (Certificate[]) certificatechain.toArray(new Certificate[certificatechain.size()])); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, keystorepass.toCharArray()); data.put(KEYSTORE, new String(Base64.encode(baos.toByteArray()))); } setStatus(info.getStatus()); this.info = new CmsCAServiceInfo(info.getStatus(), getSubjectDN(), getSubjectAltName(), (String) data.get(KEYSPEC), (String) data.get(KEYALGORITHM), certificatechain); if (log.isTraceEnabled()) { log.trace("<init"); } }
From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java
/** * Method that import CA token keys from a P12 file. Was originally used when upgrading from * old EJBCA versions. Only supports SHA1 and SHA256 with RSA or ECDSA and SHA1 with DSA. *//*from www .j ava2s. com*/ public void importKeys(String authenticationCode, PrivateKey privatekey, PublicKey publickey, PrivateKey privateEncryptionKey, PublicKey publicEncryptionKey, Certificate[] caSignatureCertChain) throws Exception { // If we don't give an authentication code, perhaps we have autoactivation enabled char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode); // Currently only RSA keys are supported KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // The CAs certificate is first in chain Certificate cacert = caSignatureCertChain[0]; // Assume that the same hash algorithm is used for signing that was used to sign this CA cert String signatureAlgorithm = CertTools.getSignatureAlgorithm(cacert); String keyAlg = AlgorithmTools.getKeyAlgorithm(publickey); if (keyAlg == null) { throw new Exception( "Unknown public key type: " + publickey.getAlgorithm() + " (" + publickey.getClass() + ")"); } // If this is a CVC CA we need to find out the sequence if (cacert instanceof CardVerifiableCertificate) { CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert; log.debug("Getting sequence from holderRef in CV certificate."); String sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence(); log.debug("Setting sequence " + sequence); setKeySequence(sequence); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); } else { log.debug("Setting default sequence " + CATokenConstants.DEFAULT_KEYSEQUENCE); setKeySequence(CATokenConstants.DEFAULT_KEYSEQUENCE); log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); } // import sign keys. String keyspec = AlgorithmTools.getKeySpecification(publickey); Certificate[] certchain = new Certificate[1]; certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, privatekey, publickey, signatureAlgorithm, true); keystore.setKeyEntry(SoftCAToken.PRIVATESIGNKEYALIAS, privatekey, null, certchain); // generate enc keys. // Encryption keys must be RSA still String encryptionSignatureAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm); keyAlg = AlgorithmTools.getKeyAlgorithmFromSigAlg(encryptionSignatureAlgorithm); keyspec = "2048"; KeyPair enckeys = null; if (publicEncryptionKey == null || privateEncryptionKey == null) { enckeys = KeyTools.genKeys(keyspec, keyAlg); } else { enckeys = new KeyPair(publicEncryptionKey, privateEncryptionKey); } // generate dummy certificate certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, enckeys.getPrivate(), enckeys.getPublic(), encryptionSignatureAlgorithm, true); keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, enckeys.getPrivate(), null, certchain); // Store keystore SoftCATokenInfo info = new SoftCATokenInfo(); info.setEncKeyAlgorithm(keyAlg); info.setEncKeySpec(keyspec); info.setEncryptionAlgorithm(encryptionSignatureAlgorithm); info.setSignKeyAlgorithm(keyAlg); info.setSignKeySpec(keyspec); info.setSignatureAlgorithm(signatureAlgorithm); storeSoftKeyStore(authCode, info, null, keystore); // Finally reset the token so it will be re-read when we want to use it this.catoken = null; }