List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:io.kodokojo.endpoint.UserSparkEndpoint.java
@Override public void configure() { post(BASE_API + "/user/:id", JSON_CONTENT_TYPE, ((request, response) -> { String identifier = request.params(":id"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Try to create user with id {}", identifier); }/*from www. ja v a 2 s. com*/ if (userStore.identifierExpectedNewUser(identifier)) { JsonParser parser = new JsonParser(); JsonObject json = (JsonObject) parser.parse(request.body()); String email = json.getAsJsonPrimitive("email").getAsString(); String username = email.substring(0, email.lastIndexOf("@")); User userByUsername = userStore.getUserByUsername(username); if (userByUsername != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Trying to create user {} from email '{}' who already exist.", username, email); } halt(409); return ""; } String entityName = email; if (json.has("entity") && StringUtils.isNotBlank(json.getAsJsonPrimitive("entity").getAsString())) { entityName = json.getAsJsonPrimitive("entity").getAsString(); } String password = new BigInteger(130, new SecureRandom()).toString(32); KeyPair keyPair = RSAUtils.generateRsaKeyPair(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); User user = new User(identifier, username, username, email, password, RSAUtils.encodePublicKey((RSAPublicKey) keyPair.getPublic(), email)); String entityId = null; SimpleCredential credential = extractCredential(request); if (credential != null) { User userRequester = userAuthenticator.authenticate(credential); if (userRequester != null) { entityId = entityStore.getEntityIdOfUserId(userRequester.getIdentifier()); } } if (entityId == null) { Entity entity = new Entity(entityName, user); entityId = entityStore.addEntity(entity); } entityStore.addUserToEntity(identifier, entityId); user = new User(identifier, entityId, username, username, email, password, user.getSshPublicKey()); if (userStore.addUser(user)) { response.status(201); StringWriter sw = new StringWriter(); RSAUtils.writeRsaPrivateKey(privateKey, sw); response.header("Location", "/user/" + user.getIdentifier()); UserCreationDto userCreationDto = new UserCreationDto(user, sw.toString()); if (emailSender != null) { List<String> cc = null; if (credential != null) { User userRequester = userAuthenticator.authenticate(credential); if (userRequester != null) { cc = Collections.singletonList(userRequester.getEmail()); } } String content = "<h1>Welcome on Kodo Kojo</h1>\n" + "<p>You will find all information which is bind to your account '" + userCreationDto.getUsername() + "'.</p>\n" + "\n" + "<p>Password : <b>" + userCreationDto.getPassword() + "</b></p>\n" + "<p>Your SSH private key generated:\n" + "<br />\n" + userCreationDto.getPrivateKey() + "\n" + "</p>\n" + "<p>Your SSH public key generated:\n" + "<br />\n" + userCreationDto.getSshPublicKey() + "\n" + "</p>"; emailSender.send(Collections.singletonList(userCreationDto.getEmail()), null, cc, "User creation on Kodo Kojo " + userCreationDto.getName(), content, true); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Mail with user data send to {}.", userCreationDto.getEmail()); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Email to {} content : \n {}", userCreationDto.getEmail(), content); } } } return userCreationDto; } if (LOGGER.isDebugEnabled()) { LOGGER.debug("The UserStore not abel to add following user {}.", user.toString()); } halt(428); return ""; } else { halt(412); return ""; } }), jsonResponseTransformer); post(BASE_API + "/user", JSON_CONTENT_TYPE, (request, response) -> { String res = userStore.generateId(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Generate id : {}", res); } return res; }); get(BASE_API + "/user", JSON_CONTENT_TYPE, (request, response) -> { SimpleCredential credential = extractCredential(request); if (credential != null) { User user = userStore.getUserByUsername(credential.getUsername()); if (user == null) { halt(404); return ""; } return getUserDto(user); } halt(401); return ""; }, jsonResponseTransformer); get(BASE_API + "/user/:id", JSON_CONTENT_TYPE, (request, response) -> { SimpleCredential credential = extractCredential(request); String identifier = request.params(":id"); User requestUser = userStore.getUserByUsername(credential.getUsername()); User user = userStore.getUserByIdentifier(identifier); if (user != null) { if (user.getEntityIdentifier().equals(requestUser.getEntityIdentifier())) { if (!user.getUsername().equals(credential.getUsername())) { user = new User(user.getIdentifier(), user.getName(), user.getUsername(), user.getEmail(), "", user.getSshPublicKey()); } return getUserDto(user); } halt(403, "You aren't in same entity."); return ""; } halt(404); return ""; }, jsonResponseTransformer); }
From source file:org.mitre.jwt.signer.impl.RsaSigner.java
/** * Load the public and private keys from the keystore, identified with the configured alias and accessed with the configured password. * @throws GeneralSecurityException//from w w w . j a va 2 s . c om */ private void loadKeysFromKeystore() { Assert.notNull(keystore, "An keystore must be supplied"); Assert.notNull(alias, "A alias must be supplied"); Assert.notNull(password, "A password must be supplied"); KeyPair keyPair = null; try { keyPair = keystore.getKeyPairForAlias(alias, password); } catch (GeneralSecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.notNull(keyPair, "Either alias and/or password is not correct for keystore"); publicKey = keyPair.getPublic(); privateKey = keyPair.getPrivate(); }
From source file:org.tolven.gatekeeper.CertificateHelper.java
private X509CertificatePrivateKeyPair createX509CertificatePrivateKeyPair(String email, String commonName, String organizationUnitName, String organizationName, String stateOrProvince) { String privateKeyAlgorithm = USER_PRIVATE_KEY_ALGORITHM_PROP; KeyPairGenerator keyPairGenerator; try {/*from w w w .ja v a2 s. c o m*/ keyPairGenerator = KeyPairGenerator.getInstance(privateKeyAlgorithm); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException("Could not get KeyPairGenerator for algorithm: " + privateKeyAlgorithm, ex); } int keySize = Integer.parseInt(USER_PRIVATE_KEY_LENGTH_PROP); keyPairGenerator.initialize(keySize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500Principal x500Principal = getX500Principal(email, commonName, organizationUnitName, organizationName, stateOrProvince); return createSelfSignedCertificate(x500Principal, keyPair.getPublic(), keyPair.getPrivate()); }
From source file:mitm.common.security.ca.handlers.comodo.ApplyCustomClientCertTest.java
@Test public void testApply() throws Exception { KeyPair keyPair = generateKeyPair(); X500PrincipalBuilder principalBuilder = new X500PrincipalBuilder(); principalBuilder.setCommonName("Martijn Brinkers"); principalBuilder.setOrganisation("Djigzo"); principalBuilder.setEmail("martijn@djigzo.com"); PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder( X500PrincipalUtils.toX500Name(principalBuilder.buildPrincipal()), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); PKCS10CertificationRequest pkcs10 = requestBuilder .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate())); String csr = MiscStringUtils.toAsciiString(Base64.encodeBase64(pkcs10.getEncoded())); ComodoConnectionSettings connectionSettings = new ComodoConnectionSettingsImpl(60000, null); ApplyCustomClientCert requestor = new ApplyCustomClientCert(connectionSettings); requestor.setAP("CHANGE"); requestor.setDays(365);//from w ww .j a v a 2s . c o m requestor.setPkcs10(csr); //requestor.setCACertificateID(1); assertFalse(requestor.apply()); assertTrue(requestor.isError()); assertEquals(CustomClientStatusCode.ARGUMENT_IS_INVALID, requestor.getErrorCode()); assertEquals("The value of the 'ap' argument is invalid!", requestor.getErrorMessage()); }
From source file:net.padlocksoftware.padlock.validator.ValidatorTest.java
License:asdf
/** * Test of validate method, of class Validator. *///from ww w.ja v a2 s . co m @Test public void testValidate() throws Exception { KeyPair pair = KeyManager.createKeyPair(); License license = LicenseFactory.createLicense(); license.addProperty("Name", "Jason Nichols"); license.addProperty("Email", "jason@padlocksoftware.net"); license.addProperty("Gibberish", "qwertyasdfg"); LicenseSigner signer = LicenseSigner.createLicenseSigner((DSAPrivateKey) pair.getPrivate()); signer.sign(license); String key = new String(Hex.encodeHex(pair.getPublic().getEncoded())); Validator validator = new Validator(license, key); validator.validate(); }
From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java
private void init(String args[]) { FileInputStream file_inputstream; try {/* w w w .j av a 2 s .com*/ String pwd = args[ARG_KEYSTOREPASSWORD]; String certNameInKeystore = args[ARG_CERTNAMEINKEYSTORE]; file_inputstream = new FileInputStream(args[ARG_KEYSTOREPATH]); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(file_inputstream, pwd.toCharArray()); System.out.println("Keystore size " + keyStore.size()); Enumeration aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { System.out.println(aliases.nextElement()); } Key key = keyStore.getKey(certNameInKeystore, pwd.toCharArray()); getPrintStream().println("Key information " + key.getAlgorithm() + " " + key.getFormat()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); innerSignKey = keyFactory.generatePrivate(keySpec); innerCertificate = keyStore.getCertificate(certNameInKeystore); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } try { KeyPair outerSignKeys = KeyTools.genKeys("1024", "RSA"); outerSignKey = outerSignKeys.getPrivate(); X509Certificate signCert = CertTools.genSelfCert("CN=cmpTest,C=SE", 5000, null, outerSignKeys.getPrivate(), outerSignKeys.getPublic(), PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), true, "BC"); writeCertificate(signCert, "/opt/racerts", "cmpTest.pem"); /* ArrayList<Certificate> certCollection = new ArrayList<Certificate>(); certCollection.add(signCert); byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection); FileOutputStream out = new FileOutputStream(new File("/opt/racerts/cmpStressTest.pem")); out.write(pemRaCert); out.close(); */ } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (NoSuchProviderException e1) { e1.printStackTrace(); } catch (InvalidAlgorithmParameterException e1) { e1.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (CertificateEncodingException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); //} catch (FileNotFoundException e) { // e.printStackTrace(); //} catch (IOException e) { // e.printStackTrace(); //} catch (CertificateException e) { // e.printStackTrace(); } }
From source file:net.padlocksoftware.padlock.validator.ValidatorTest.java
License:asdf
@Test public void testBlacklist() throws Exception { KeyPair pair = KeyManager.createKeyPair(); License license = LicenseFactory.createLicense(); license.addProperty("Name", "Jason Nichols"); license.addProperty("Email", "jason@padlocksoftware.net"); license.addProperty("Gibberish", "qwertyasdfg"); LicenseSigner signer = LicenseSigner.createLicenseSigner((DSAPrivateKey) pair.getPrivate()); signer.sign(license);/* www.j a v a 2s .c om*/ String key = new String(Hex.encodeHex(pair.getPublic().getEncoded())); Validator validator = new Validator(license, key); validator.addBlacklistedLicense(license.getLicenseSignatureString()); boolean ex = false; try { validator.validate(); } catch (ValidatorException e) { ex = true; } assertTrue(ex); }
From source file:org.metaeffekt.dcc.agent.AuthenticationKeyGenerator.java
private X509Certificate generateCertificate(KeyPair key, String certificateCN, Date begin, Date end) throws GeneralSecurityException, IOException, OperatorException { final X500NameBuilder nameBuilder = new X500NameBuilder(); nameBuilder.addRDN(BCStyle.CN, certificateCN); final X500Name name = nameBuilder.build(); final JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(name, new BigInteger(String.valueOf(random.nextInt())), begin, end, name, key.getPublic()); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(key.getPublic())); final X509CertificateHolder certificateHolder = certBuilder .build(new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).build(key.getPrivate())); final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(certificateHolder); return certificate; }
From source file:org.panbox.mobile.android.identitymgmt.IdentityDebugApp.java
/** * Call Create Identity first!/*from www . j ava 2 s. com*/ */ public void addContactTest() { if (null == identity) { Toast.makeText(context, "Create one ID first that we can load afterwards", Toast.LENGTH_LONG).show(); System.err.println("No identity to add contact to, please create one"); return; } PanboxContact c = new PanboxContact(); c.setEmail("contactAdded@bla.de"); c.setName("AddedLastName"); c.setFirstName("Alice"); c.setTrustLevel(2); CloudProviderInfo cpi1 = new CloudProviderInfo("Cloud1", "Alice-Cloud1"); c.addCloudProvider(cpi1); KeyPair cSigKey = CryptCore.generateKeypair(); KeyPair cEncKey = CryptCore.generateKeypair(); c.setCertEnc(CryptCore.createSelfSignedX509Certificate(cEncKey.getPrivate(), cEncKey.getPublic(), c)); c.setCertSign(CryptCore.createSelfSignedX509Certificate(cSigKey.getPrivate(), cSigKey.getPublic(), c)); try { identity.getAddressbook().addContact(c); } catch (ContactExistsException e) { // TODO Auto-generated catch block e.printStackTrace(); } // change cpi of a contact // PanboxContact pbc = identity.getAddressbook().contactExists( // "contact1@test.de"); // CloudProviderInfo cpInfo = pbc.getCloudProvider("Skydrive"); // cpInfo.setUsername("changed-Bobs-Skydriveuser"); // // // remove cpi in contact // cpInfo = pbc.getCloudProvider("Dropbox"); // pbc.removeCloudProvider(cpInfo); // // // add cpi to contact // CloudProviderInfo cpi123 = new CloudProviderInfo("Wuala", "Bobs-Wuala"); // pbc.addCloudProvider(cpi123); // // // change name, email etc of contact // pbc.setEmail("12345@12345.com"); // pbc.setName("12Name"); // pbc.setFirstName("12Firstname"); // // // change mail // identity.setEmail("newMail@testing.org"); // // identity.setName("NewLastName"); // identity.setFirstName("NewFirstName"); // // // del cpi // CloudProviderInfo del = null; // for (CloudProviderInfo cpi : identity.getCloudProviders().values()) { // if (cpi.getProviderName().equals("Dropbox")) { // del = cpi; // } // } // identity.delCloudProvider(del.getProviderName()); // // // add new cpi // CloudProviderInfo newCPI = new CloudProviderInfo("NewCloud", // "myNewuser@bla.com"); // identity.addCloudProvider(newCPI); // // Settings pbSettings = Settings.getInstance(); // pbSettings.setConfDir(context.getFilesDir().getAbsolutePath()); // // pbSettings.setPanboxIdentityDBFile(context.getFilesDir() // // + File.separator + "identity.db"); // // pbSettings.setPanboxKeystore(context.getFilesDir() + File.separator // // + "keystore.jks"); AbstractIdentityManager idm = IdentityManagerAndroid.getInstance(context); idm.storeMyIdentity(identity); }
From source file:com.atlassian.jira.security.auth.trustedapps.TestDefaultCurrentApplicationStore.java
private void assertState(final PublicKey publicKey, final PrivateKey privateKey, final String applicationId, final CurrentApplicationStore applicationStore) { CurrentApplication currentApplication = applicationStore.getCurrentApplication(); assertEquals(applicationId, currentApplication.getID()); assertEquals(publicKey, currentApplication.getPublicKey()); KeyPair keyPair = applicationStore.getKeyPair(); assertEquals(publicKey, keyPair.getPublic()); assertEquals(privateKey, keyPair.getPrivate()); // just make sure we have a key final EncryptedCertificate encoded = currentApplication.encode("this little sentence", null); assertNotNull(encoded.getCertificate()); assertEquals(applicationId, encoded.getID()); assertNotNull(encoded.getSecretKey()); }