List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java
public KeyStore addKeyPair(KeyStore keyStore, String keyStorePassphrase, KeyPair keyPair, String keyPairName, String keyPairPassphrase, String keyPairSubjectDN) throws CryptoException { logger.debug("Adding key pair to existing key store"); try {//from www. ja v a2 s.c o m // Create the public key certificate for storage in the key store. X509Certificate cert = generateV3Certificate(keyPair, keyPairSubjectDN); X500PrivateCredential privateCredentials = new X500PrivateCredential(cert, keyPair.getPrivate(), keyPairName); Certificate[] certChain = new X509Certificate[1]; certChain[0] = privateCredentials.getCertificate(); // Load our generated key store up. They all have the same password, which we set. keyStore.load(null, keyStorePassphrase.toCharArray()); /* Add certificate which contains the public key and set the private key as a key entry in the key store */ keyStore.setCertificateEntry(privateCredentials.getAlias(), privateCredentials.getCertificate()); keyStore.setKeyEntry(privateCredentials.getAlias(), keyPair.getPrivate(), keyPairPassphrase.toCharArray(), certChain); return keyStore; } catch (NoSuchAlgorithmException e) { this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (CertificateException e) { this.logger.error("CertificateException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (KeyStoreException e) { this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (IOException e) { this.logger.error("IOException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } }
From source file:org.gluu.com.ox_push2.u2f.v2.device.U2FKeyImpl.java
@Override public AuthenticateResponse authenticate(AuthenticateRequest authenticateRequest) throws U2FException { if (BuildConfig.DEBUG) Log.d(TAG, ">> authenticate"); byte control = authenticateRequest.getControl(); String application = authenticateRequest.getApplication(); String challenge = authenticateRequest.getChallenge(); byte[] keyHandle = authenticateRequest.getKeyHandle(); if (BuildConfig.DEBUG) Log.d(TAG, "-- Inputs --"); if (BuildConfig.DEBUG) Log.d(TAG, "control: " + control); if (BuildConfig.DEBUG) Log.d(TAG, "application: " + application); if (BuildConfig.DEBUG) Log.d(TAG, "challenge: " + challenge); if (BuildConfig.DEBUG) Log.d(TAG, "keyHandle: " + Utils.base64UrlEncode(keyHandle)); TokenEntry tokenEntry = dataStore.getTokenEntry(keyHandle); if (tokenEntry == null) { Log.e(TAG, "There is no keyPair for keyHandle: " + Utils.base64UrlEncode(keyHandle)); return null; }//w ww .j a v a 2 s . co m if (!application.equals(tokenEntry.getApplication())) { throw new U2FException("KeyHandle " + Utils.base64UrlEncode(keyHandle) + " is associated with application: " + tokenEntry.getApplication()); } String keyPairJson = tokenEntry.getKeyPair(); if (keyPairJson == null) { Log.e(TAG, "There is no keyPair for keyHandle: " + Utils.base64UrlEncode(keyHandle)); return null; } KeyPair keyPair; try { keyPair = keyPairGenerator.keyPairFromJson(keyPairJson); } catch (U2FException ex) { Log.e(TAG, "There is no keyPair for keyHandle: " + Utils.base64UrlEncode(keyHandle)); return null; } int counter = dataStore.incrementCounter(keyHandle); byte userPresence = userPresenceVerifier.verifyUserPresence(); byte[] applicationSha256 = DigestUtils.sha256(application); byte[] challengeSha256 = DigestUtils.sha256(challenge); byte[] signedData = rawMessageCodec.encodeAuthenticateSignedBytes(applicationSha256, userPresence, counter, challengeSha256); if (BuildConfig.DEBUG) Log.d(TAG, "Signing bytes " + Utils.encodeHexString(signedData)); byte[] signature = keyPairGenerator.sign(signedData, keyPair.getPrivate()); if (BuildConfig.DEBUG) Log.d(TAG, "-- Outputs --"); if (BuildConfig.DEBUG) Log.d(TAG, "userPresence: " + userPresence); if (BuildConfig.DEBUG) Log.d(TAG, "counter: " + counter); if (BuildConfig.DEBUG) Log.d(TAG, "signature: " + Utils.encodeHexString(signature)); if (BuildConfig.DEBUG) Log.d(TAG, "<< authenticate"); return new AuthenticateResponse(userPresence, counter, signature); }
From source file:cybervillains.ca.KeyStoreManager.java
/** * This method returns the duplicated certificate mapped to the passed in cert, or * creates and returns one if no mapping has yet been performed. If a naked public * key has already been mapped that matches the key in the cert, the already mapped * keypair will be reused for the mapped cert. * @param cert/*from ww w .jav a 2 s . co m*/ * @return * @throws CertificateEncodingException * @throws InvalidKeyException * @throws CertificateException * @throws CertificateNotYetValidException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws SignatureException * @throws KeyStoreException * @throws UnrecoverableKeyException */ public synchronized X509Certificate getMappedCertificate(final X509Certificate cert) throws CertificateEncodingException, InvalidKeyException, CertificateException, CertificateNotYetValidException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, KeyStoreException, UnrecoverableKeyException { String thumbprint = ThumbprintUtil.getThumbprint(cert); String mappedCertThumbprint = _certMap.get(thumbprint); if (mappedCertThumbprint == null) { // Check if we've already mapped this public key from a KeyValue PublicKey mappedPk = getMappedPublicKey(cert.getPublicKey()); PrivateKey privKey; if (mappedPk == null) { PublicKey pk = cert.getPublicKey(); String algo = pk.getAlgorithm(); KeyPair kp; if (algo.equals("RSA")) { kp = getRSAKeyPair(); } else if (algo.equals("DSA")) { kp = getDSAKeyPair(); } else { throw new InvalidKeyException("Key algorithm " + algo + " not supported."); } mappedPk = kp.getPublic(); privKey = kp.getPrivate(); mapPublicKeys(cert.getPublicKey(), mappedPk); } else { privKey = getPrivateKey(mappedPk); } X509Certificate replacementCert = CertificateCreator.mitmDuplicateCertificate(cert, mappedPk, getSigningCert(), getSigningPrivateKey()); addCertAndPrivateKey(null, replacementCert, privKey); mappedCertThumbprint = ThumbprintUtil.getThumbprint(replacementCert); _certMap.put(thumbprint, mappedCertThumbprint); _certMap.put(mappedCertThumbprint, thumbprint); _subjectMap.put(replacementCert.getSubjectX500Principal().getName(), thumbprint); if (persistImmediately) { persist(); } return replacementCert; } return getCertificateByAlias(mappedCertThumbprint); }
From source file:mitm.common.security.ca.hibernate.CertificateRequestStoreImplTest.java
@Test public void testAddRequest() throws Exception { AutoTransactDelegator delegator = AutoTransactDelegator.createProxy(); X500PrincipalBuilder builder = new X500PrincipalBuilder(); builder.setCommonName("john doe"); builder.setEmail("johndoe@example.com"); KeyPair keyPair = generateKeyPair(); delegator.addRequest(builder.buildPrincipal(), "test@example.com", 365, "SHA1", "http://example.com", "dummy", new byte[] { 1, 2, 3 }, new Date(), "Some message", keyPair); List<? extends CertificateRequest> found = delegator.getRequestsByEmail("test@example.com", null, null, null);/*from w w w . j a v a2 s . c o m*/ assertEquals(1, found.size()); CertificateRequest request = found.get(0); KeyPair keyPairCopy = request.getKeyPair(encryptor); assertNotNull(keyPairCopy); assertEquals(keyPair.getPublic(), keyPairCopy.getPublic()); assertEquals(keyPair.getPrivate(), keyPairCopy.getPrivate()); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.X509SecurityHandler.java
@Override public X509SecurityManagerMaterial generateMaterial(X509MaterialParameter materialParameter) throws Exception { if (!isHopsTLSEnabled()) { return null; }//from ww w . j ava 2 s . c o m ApplicationId appId = materialParameter.getApplicationId(); String appUser = materialParameter.appUser; Integer cryptoMaterialVersion = materialParameter.cryptoMaterialVersion; KeyPair keyPair = generateKeyPair(); PKCS10CertificationRequest csr = generateCSR(appId, appUser, keyPair, cryptoMaterialVersion); CertificateBundle certificateBundle = sendCSRAndGetSigned(csr); long expirationEpoch = certificateBundle.certificate.getNotAfter().getTime(); KeyStoresWrapper keyStoresWrapper = createApplicationStores(certificateBundle, keyPair.getPrivate(), appUser, appId); byte[] rawProtectedKeyStore = keyStoresWrapper.getRawKeyStore(TYPE.KEYSTORE); byte[] rawTrustStore = keyStoresWrapper.getRawKeyStore(TYPE.TRUSTSTORE); certificateLocalizationService.materializeCertificates(appUser, appId.toString(), appUser, ByteBuffer.wrap(rawProtectedKeyStore), String.valueOf(keyStoresWrapper.keyStorePassword), ByteBuffer.wrap(rawTrustStore), String.valueOf(keyStoresWrapper.trustStorePassword)); return new X509SecurityManagerMaterial(appId, rawProtectedKeyStore, keyStoresWrapper.keyStorePassword, rawTrustStore, keyStoresWrapper.trustStorePassword, expirationEpoch); }
From source file:io.getlime.security.powerauth.app.server.service.behavior.ActivationServiceBehavior.java
/** * Init activation with given parameters * * @param applicationId Application ID * @param userId User ID * @param maxFailedCount Maximum failed attempt count (5) * @param activationExpireTimestamp Timestamp after which activation can no longer be completed * @param keyConversionUtilities Utility class for key conversion * @return Response with activation initialization data * @throws GenericServiceException If invalid values are provided. * @throws InvalidKeySpecException If invalid key is provided * @throws InvalidKeyException If invalid key is provided *//*from ww w . ja va2 s . c o m*/ public InitActivationResponse initActivation(Long applicationId, String userId, Long maxFailedCount, Date activationExpireTimestamp, CryptoProviderUtil keyConversionUtilities) throws GenericServiceException, InvalidKeySpecException, InvalidKeyException { // Generate timestamp in advance Date timestamp = new Date(); if (userId == null) { throw localizationProvider.buildExceptionForCode(ServiceError.NO_USER_ID); } if (applicationId == 0L) { throw localizationProvider.buildExceptionForCode(ServiceError.NO_APPLICATION_ID); } // Get number of max attempts from request or from constants, if not provided Long maxAttempt = maxFailedCount; if (maxAttempt == null) { maxAttempt = PowerAuthConfiguration.SIGNATURE_MAX_FAILED_ATTEMPTS; } // Get activation expiration date from request or from constants, if not provided Date timestampExpiration = activationExpireTimestamp; if (timestampExpiration == null) { timestampExpiration = new Date( timestamp.getTime() + PowerAuthConfiguration.ACTIVATION_VALIDITY_BEFORE_ACTIVE); } // Fetch the latest master private key MasterKeyPairEntity masterKeyPair = masterKeyPairRepository .findFirstByApplicationIdOrderByTimestampCreatedDesc(applicationId); if (masterKeyPair == null) { GenericServiceException ex = localizationProvider .buildExceptionForCode(ServiceError.NO_MASTER_SERVER_KEYPAIR); Logger.getLogger(PowerAuthServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw ex; } byte[] masterPrivateKeyBytes = BaseEncoding.base64().decode(masterKeyPair.getMasterKeyPrivateBase64()); PrivateKey masterPrivateKey = keyConversionUtilities.convertBytesToPrivateKey(masterPrivateKeyBytes); if (masterPrivateKey == null) { GenericServiceException ex = localizationProvider .buildExceptionForCode(ServiceError.INCORRECT_MASTER_SERVER_KEYPAIR_PRIVATE); Logger.getLogger(PowerAuthServiceImpl.class.getName()).log(Level.SEVERE, null, ex); throw ex; } // Generate new activation data, generate a unique activation ID String activationId = null; for (int i = 0; i < PowerAuthConfiguration.ACTIVATION_GENERATE_ACTIVATION_ID_ITERATIONS; i++) { String tmpActivationId = powerAuthServerActivation.generateActivationId(); ActivationRecordEntity record = powerAuthRepository.findFirstByActivationId(tmpActivationId); if (record == null) { activationId = tmpActivationId; break; } // ... else this activation ID has a collision, reset it and try to find another one } if (activationId == null) { throw localizationProvider.buildExceptionForCode(ServiceError.UNABLE_TO_GENERATE_ACTIVATION_ID); } // Generate a unique short activation ID for created and OTP used states String activationIdShort = null; Set<io.getlime.security.powerauth.app.server.repository.model.ActivationStatus> states = ImmutableSet.of( io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.CREATED, io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.OTP_USED); for (int i = 0; i < PowerAuthConfiguration.ACTIVATION_GENERATE_ACTIVATION_SHORT_ID_ITERATIONS; i++) { String tmpActivationIdShort = powerAuthServerActivation.generateActivationIdShort(); ActivationRecordEntity record = powerAuthRepository .findFirstByApplicationIdAndActivationIdShortAndActivationStatusInAndTimestampActivationExpireAfter( applicationId, tmpActivationIdShort, states, timestamp); // this activation short ID has a collision, reset it and find // another one if (record == null) { activationIdShort = tmpActivationIdShort; break; } } if (activationIdShort == null) { throw localizationProvider.buildExceptionForCode(ServiceError.UNABLE_TO_GENERATE_SHORT_ACTIVATION_ID); } // Generate activation OTP String activationOtp = powerAuthServerActivation.generateActivationOTP(); // Compute activation signature byte[] activationSignature = powerAuthServerActivation.generateActivationSignature(activationIdShort, activationOtp, masterPrivateKey); // Happens only when there is a crypto provider setup issue (SignatureException). if (activationSignature == null) { throw localizationProvider.buildExceptionForCode(ServiceError.UNABLE_TO_COMPUTE_SIGNATURE); } // Encode the signature String activationSignatureBase64 = BaseEncoding.base64().encode(activationSignature); // Generate server key pair KeyPair serverKeyPair = powerAuthServerActivation.generateServerKeyPair(); byte[] serverKeyPrivateBytes = keyConversionUtilities.convertPrivateKeyToBytes(serverKeyPair.getPrivate()); byte[] serverKeyPublicBytes = keyConversionUtilities.convertPublicKeyToBytes(serverKeyPair.getPublic()); // Store the new activation ActivationRecordEntity activation = new ActivationRecordEntity(); activation.setActivationId(activationId); activation.setActivationIdShort(activationIdShort); activation.setActivationName(null); activation.setActivationOTP(activationOtp); activation.setActivationStatus( io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.CREATED); activation.setCounter(0L); activation.setDevicePublicKeyBase64(null); activation.setExtras(null); activation.setFailedAttempts(0L); activation.setApplication(masterKeyPair.getApplication()); activation.setMasterKeyPair(masterKeyPair); activation.setMaxFailedAttempts(maxAttempt); activation.setServerPrivateKeyBase64(BaseEncoding.base64().encode(serverKeyPrivateBytes)); activation.setServerPublicKeyBase64(BaseEncoding.base64().encode(serverKeyPublicBytes)); activation.setTimestampActivationExpire(timestampExpiration); activation.setTimestampCreated(timestamp); activation.setTimestampLastUsed(timestamp); activation.setUserId(userId); powerAuthRepository.save(activation); callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(), activation.getActivationId()); // Return the server response InitActivationResponse response = new InitActivationResponse(); response.setActivationId(activationId); response.setActivationIdShort(activationIdShort); response.setUserId(userId); response.setActivationOTP(activationOtp); response.setActivationSignature(activationSignatureBase64); response.setApplicationId(activation.getApplication().getId()); return response; }
From source file:com.poscoict.license.service.BoardService.java
public Map<String, Object> passwordPop(HttpSession session) throws Exception { logger.info("get passwordPopForm"); Map<String, Object> map = new HashMap<String, Object>(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);// www. j a va2s . com KeyPair keyPair = generator.genKeyPair(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // ? ? ?? ? . session.setAttribute("__rsaPrivateKey__", privateKey); // ? JavaScript RSA ?? . RSAPublicKeySpec publicSpec = (RSAPublicKeySpec) keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class); map.put("publicKeyModulus", publicSpec.getModulus().toString(16)); map.put("publicKeyExponent", publicSpec.getPublicExponent().toString(16)); logger.info("return passwordPopForm"); return map; }
From source file:org.gluu.oxtrust.action.ManageCertificateAction.java
@Restrict("#{s:hasPermission('configuration', 'access')}") public String generateCSR(String fileName) { if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { Security.addProvider(new BouncyCastleProvider()); }//ww w . ja va 2 s .c om KeyPair pair = getKeyPair(fileName); boolean result = false; if (pair != null) { String url = applicationConfiguration.getIdpUrl().replaceFirst(".*//", ""); String csrPrincipal = String.format("CN=%s", url); X500Principal principal = new X500Principal(csrPrincipal); PKCS10CertificationRequest csr = null; try { csr = new PKCS10CertificationRequest("SHA1withRSA", principal, pair.getPublic(), null, pair.getPrivate()); } catch (GeneralSecurityException e) { log.error(e.getMessage(), e); return OxTrustConstants.RESULT_FAILURE; } // Form download responce StringBuilder response = new StringBuilder(); response.append(BEGIN_CERT_REQ + "\n"); response.append(WordUtils.wrap(new String(Base64.encode(csr.getDEREncoded())), 64, "\n", true) + "\n"); response.append(END_CERT_REQ + "\n"); result = ResponseHelper.downloadFile("csr.pem", OxTrustConstants.CONTENT_TYPE_TEXT_PLAIN, response.toString().getBytes(), facesContext); } return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE; }
From source file:it.zero11.acme.Acme.java
@SuppressWarnings("serial") protected String getUpdateRegistrationRequest(final KeyPair userKey, final String nonce, final String agreement, final String[] contacts) { return Jwts.builder().setHeaderParam(NONCE_KEY, nonce) .setHeaderParam(JwsHeader.JSON_WEB_KEY, JWKUtils.getWebKey(userKey.getPublic())) .setClaims(new TreeMap<String, Object>() { {//w w w . ja va 2s .c o m put(RESOURCE_KEY, RESOURCE_UPDATE_REGISTRATION); if (contacts != null && contacts.length > 0) { put(CONTACT_KEY, contacts); } put(AGREEMENT_KEY, agreement); } }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact(); }
From source file:test.unit.be.fedict.eid.idp.protocol.openid.OpenIDSSLProtocolServiceTest.java
@Test public void testOpenIDSpike() throws Exception { LOG.debug("OpenID spike"); // setup//from w w w . j a va2s.c o m this.servletTester = new ServletTester(); this.servletTester.addServlet(OpenIDConsumerServlet.class, "/consumer/*"); this.servletTester.addServlet(OpenIDIdentityServlet.class, "/identity/*"); this.servletTester.addServlet(OpenIDProducerServlet.class, "/producer"); Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter); File tmpP12File = File.createTempFile("ssl-", ".p12"); tmpP12File.deleteOnExit(); LOG.debug("p12 file: " + tmpP12File.getAbsolutePath()); persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray()); SslSocketConnector sslSocketConnector = new SslSocketConnector(); sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath()); sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath()); sslSocketConnector.setTruststoreType("pkcs12"); sslSocketConnector.setKeystoreType("pkcs12"); sslSocketConnector.setPassword("secret"); sslSocketConnector.setKeyPassword("secret"); sslSocketConnector.setTrustPassword("secret"); sslSocketConnector.setMaxIdleTime(30000); int sslPort = getFreePort(); sslSocketConnector.setPort(sslPort); this.servletTester.getContext().getServer().addConnector(sslSocketConnector); sslLocation = "https://localhost:" + sslPort; this.servletTester.start(); location = this.servletTester.createSocketConnector(true); LOG.debug("location: " + location); HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter("http.protocol.allow-circular-redirects", Boolean.TRUE); // GetMethod getMethod = new GetMethod(location + "/consumer"); /* * Next is for ConsumerManager to be able to trust the OP. */ // MySSLSocketFactory mySSLSocketFactory = new MySSLSocketFactory( // certificate); // HttpsURLConnection.setDefaultSSLSocketFactory(mySSLSocketFactory); ProtocolSocketFactory protocolSocketFactory = new MyProtocolSocketFactory(certificate); Protocol myProtocol = new Protocol("https", protocolSocketFactory, sslPort); Protocol.registerProtocol("https", myProtocol); GetMethod getMethod = new GetMethod(sslLocation + "/consumer"); // operate int statusCode = httpClient.executeMethod(getMethod); // verify LOG.debug("status code: " + statusCode); assertEquals(HttpServletResponse.SC_OK, statusCode); SessionHandler sessionHandler = this.servletTester.getContext().getSessionHandler(); SessionManager sessionManager = sessionHandler.getSessionManager(); HashSessionManager hashSessionManager = (HashSessionManager) sessionManager; LOG.debug("# sessions: " + hashSessionManager.getSessions()); assertEquals(1, hashSessionManager.getSessions()); Map<String, HttpSession> sessionMap = hashSessionManager.getSessionMap(); LOG.debug("session map: " + sessionMap); Entry<String, HttpSession> sessionEntry = sessionMap.entrySet().iterator().next(); HttpSession httpSession = sessionEntry.getValue(); String userId = (String) httpSession.getAttribute(OpenIDConsumerServlet.USER_ID_SESSION_ATTRIBUTE); LOG.debug("userId session attribute: " + userId); assertEquals(sslLocation + "/identity/idp/123456789", userId); String firstName = (String) httpSession.getAttribute(OpenIDConsumerServlet.FIRST_NAME_SESSION_ATTRIBUTE); assertEquals("sample-first-name", firstName); }