List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:org.ejbca.core.model.ca.catoken.BaseCAToken.java
private void testKey(KeyPair pair) throws Exception { if (log.isDebugEnabled()) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream ps = new PrintStream(baos); KeyTools.printPublicKeyInfo(pair.getPublic(), ps); ps.flush();/*from w w w . j a va2s. co m*/ log.debug("Using of " + baos.toString()); } if (!doPermitExtractablePrivateKey() && KeyTools.isPrivateKeyExtractable(pair.getPrivate())) { String msg = intres.getLocalizedMessage("catoken.extractablekey", EjbcaConfiguration.doPermitExtractablePrivateKeys()); if (!EjbcaConfiguration.doPermitExtractablePrivateKeys()) { throw new InvalidKeyException(msg); } log.info(msg); } KeyTools.testKey(pair.getPrivate(), pair.getPublic(), getProvider()); }
From source file:it.zero11.acme.Acme.java
@SuppressWarnings("serial") protected String getRegistrationRequest(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>() { {//from www . j a v a 2 s . c om put(RESOURCE_KEY, RESOURCE_NEW_REG); if (contacts != null && contacts.length > 0) { put(CONTACT_KEY, contacts); } if (agreement != null) { put(AGREEMENT_KEY, agreement); } } }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact(); }
From source file:it.zero11.acme.Acme.java
@SuppressWarnings("serial") protected String getNewCertificateRequest(final KeyPair userKey, final String nonce, final PKCS10CertificationRequest csr) throws IOException { return Jwts.builder().setHeaderParam(NONCE_KEY, nonce) .setHeaderParam(JwsHeader.JSON_WEB_KEY, JWKUtils.getWebKey(userKey.getPublic())) .setClaims(new TreeMap<String, Object>() { {// w w w . j av a 2 s . c o m put(RESOURCE_KEY, RESOURCE_NEW_CERT); put(CSR_KEY, TextCodec.BASE64URL.encode(csr.getEncoded())); } }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact(); }
From source file:kr.ac.cau.mecs.cass.processor.SignupProcessor.java
@Override public Signal process(Signal signal) { Signal resignal = new Signal(); resignal.setReceiver(signal.getSender()); resignal.setSender("CASS"); resignal.setAction(new Action(Action.ACT_SIGNUP)); if (signal.getPayload() != null && (signal.getPayload().getPayload() instanceof JSONObjectPayload)) { JSONObject jobj = (JSONObject) signal.getPayload().getPayload().getData(); if (jobj.has("userid") && jobj.has("userpw")) { String userid = jobj.optString("userid"); String userpw = jobj.optString("userpw"); //valid payload DBUserEntity _user = UserEntityDAO.getByUserID(session, userid); if (_user != null) { //user exists setGenericMessage(resignal, "user exists"); } else { if (userid.length() > 4) { if (userpw.length() > 4) { //create here _user = new DBUserEntity(); _user.setName(userid); _user.setPassword(userpw); if (_user.getAccessToken() == null) { _user.setAccessToken(new DBAccessTokenEntity()); _user.getAccessToken().setUser(_user); }//w w w .j a v a2 s. c o m KeyPair keypair = AccessTokenUtil.generateKeyPair(System.currentTimeMillis()); String usertoken = BCrypt.hashpw(userid, BCrypt.gensalt(12)); String authtoken = AccessTokenUtil.signData(usertoken, keypair.getPrivate()); _user.getAccessToken() .setPrivateKey(AccessTokenUtil.encodePrivateKey(keypair.getPrivate())); _user.getAccessToken() .setPublicKey(AccessTokenUtil.encodePublicKey(keypair.getPublic())); _user.getAccessToken().setAccessToken(authtoken); _user.getAccessToken().setUserToken(usertoken); session.save(_user); session.saveOrUpdate(_user.getAccessToken()); JSONObject jres = new JSONObject(); jres.putOpt("authToken", authtoken); jres.putOpt("userToken", usertoken); resignal.setPayload(new Payload(new JSONObjectPayload(jres))); } else { setGenericMessage(resignal, "pw too short(min 5)"); } } else { setGenericMessage(resignal, "id too short(min 5)"); } } } else { setGenericMessage(resignal, "invalid payload type"); } } else { //inform user invalid payload type setGenericMessage(resignal, "invalid payload type"); } return resignal; }
From source file:cybervillains.ca.KeyStoreManager.java
private synchronized void rememberKeyPair(final KeyPair kp) { _rememberedPrivateKeys.put(kp.getPublic(), kp.getPrivate()); if (persistImmediately) { persistKeyPairMap();/*from ww w.jav a 2s.c o m*/ } }
From source file:org.bedework.util.security.pki.PKITools.java
/** * @return RSAKeys//from w ww . ja v a 2s.c o m * @throws PKIException */ public RSAKeys genRSAKeys() throws PKIException { RSAKeys keys = new RSAKeys(); try { SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(new byte[1]); KeyPairGenerator rsaKeyGen; if (curSchema.pName == null) { rsaKeyGen = KeyPairGenerator.getInstance(curSchema.keyFactory); } else { rsaKeyGen = KeyPairGenerator.getInstance(curSchema.keyFactory, curSchema.pName); } rsaKeyGen.initialize(1024, secureRandom); if (trace()) { trace("Generating keys..."); } KeyPair rsaKeyPair = rsaKeyGen.generateKeyPair(); if (trace()) { trace("Saving Public Key..."); } keys.privateKey = rsaKeyPair.getPrivate().getEncoded(); keys.publicKey = rsaKeyPair.getPublic().getEncoded(); if (trace()) { trace("Done..."); } return keys; } catch (Throwable t) { throw new PKIException(t); } }
From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java
public X509Certificate generateV1Certificate(String subject, char[] ksPass, KeyStore keyStore) throws OperatorCreationException, IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException { KeyPair pair = generateKeyPair(); BigInteger certSerial = BigInteger.valueOf(System.currentTimeMillis()); X500Name issuerDN = new X500Name("CN=" + subject); X500Name subjectDN = new X500Name("CN=" + subject); Date notBefore = new Date(System.currentTimeMillis() - 10000); Date notAfter = new Date(System.currentTimeMillis() + 10000); PublicKey pubKey = (pair.getPublic()); X509v1CertificateBuilder certGen = new JcaX509v1CertificateBuilder(issuerDN, certSerial, notBefore, notAfter, subjectDN, pubKey); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(pair.getPrivate()); byte[] encoded = certGen.build(signer).getEncoded(); CertificateFactory fact = CertificateFactory.getInstance("X.509"); InputStream is = new ByteArrayInputStream(encoded); X509Certificate generateCertificate = (X509Certificate) fact.generateCertificate(is); is.close();/*from w w w . j a v a 2 s . co m*/ // set the CA cert as trusted root X509Certificate[] chain = new X509Certificate[] { generateCertificate }; addToKeyStore(pair, chain, K_NAME, keyStore, ksPass); String certStr = generateCertificate.toString(); return generateCertificate; }
From source file:org.openbase.bco.authentication.core.AuthenticatorController.java
@Override public void activate() throws CouldNotPerformException, InterruptedException { if (!credentialStore.hasEntry(CredentialStore.SERVICE_SERVER_ID) || JPService.testMode()) { // Generate private/public key pair for service servers. final KeyPair keyPair = EncryptionHelper.generateKeyPair(); credentialStore.addCredentials(CredentialStore.SERVICE_SERVER_ID, keyPair.getPublic().getEncoded(), false, false);/* www. ja va 2 s . c o m*/ try { final LoginCredentials loginCredentials = credentialStore .getEntry(CredentialStore.SERVICE_SERVER_ID).toBuilder() .setCredentials(ByteString.copyFrom(keyPair.getPrivate().getEncoded())).build(); File privateKeyFile = new File(JPService.getProperty(JPCredentialsDirectory.class).getValue(), AuthenticatedServerManager.SERVICE_SERVER_PRIVATE_KEY_FILENAME); try (FileOutputStream outputStream = new FileOutputStream(privateKeyFile)) { outputStream.write(loginCredentials.toByteArray()); outputStream.flush(); } AbstractProtectedStore.protectFile(privateKeyFile); } catch (JPNotAvailableException ex) { throw new CouldNotPerformException("Could not load property.", ex); } catch (IOException ex) { throw new CouldNotPerformException("Could not write private key.", ex); } } if (initialPasswordRequired() || JPService.testMode()) { // Generate initial password. initialPassword = RandomStringUtils.randomAlphanumeric(15); } serverWatchDog.activate(); }
From source file:com.atlassian.jira.security.auth.trustedapps.DefaultCurrentApplicationStore.java
private Pair<KeyPair, CurrentApplication> getOrCreateCurrentApplication() { accessLock.lock();/*ww w . ja v a 2 s . com*/ final KeyPair keyPair; String uid; try { final String privateKeyData = applicationProperties.getText(Keys.PRIVATE_KEY_DATA); final String publicKeyData = applicationProperties.getText(Keys.PUBLIC_KEY_DATA); if (isBlank(privateKeyData)) { keyPair = generateNewKeyPair(); applicationProperties.setText(Keys.PRIVATE_KEY_DATA, KeyFactory.encode(keyPair.getPrivate())); applicationProperties.setText(Keys.PUBLIC_KEY_DATA, KeyFactory.encode(keyPair.getPublic())); } else { PrivateKey privateKey = KeyFactory.getPrivateKey(privateKeyData); PublicKey publicKey = KeyFactory.getPublicKey(publicKeyData); keyPair = new KeyPair(publicKey, privateKey); } uid = applicationProperties.getString(Keys.UID); if (isBlank(uid)) { uid = new UIDGenerator().generateUID(licenseService); applicationProperties.setString(Keys.UID, uid); } } finally { accessLock.unlock(); } CurrentApplication application = new DefaultCurrentApplication(keyPair.getPublic(), keyPair.getPrivate(), uid); return Pair.of(keyPair, application); }
From source file:org.apache.sshd.common.config.keys.loader.pem.PKCS8PEMResourceKeyPairParserTest.java
@Test // see SSHD-760 public void testPkcs8() throws IOException, GeneralSecurityException { KeyPairGenerator generator = SecurityUtils.getKeyPairGenerator(algorithm); if (keySize > 0) { generator.initialize(keySize);/* w w w . java 2s. c o m*/ } KeyPair kp = generator.generateKeyPair(); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { Collection<Object> items = new ArrayList<>(); PrivateKey prv1 = kp.getPrivate(); items.add(new PEMItem(prv1.getEncoded(), "PRIVATE KEY")); byte[] bytes = PEMUtil.encode(items); os.write(bytes); os.close(); try (ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray())) { KeyPair kp2 = SecurityUtils.loadKeyPairIdentity(getCurrentTestName(), bais, null); assertEquals("Mismatched public key", kp.getPublic(), kp2.getPublic()); assertEquals("Mismatched private key", prv1, kp2.getPrivate()); } } }