List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:netinf.common.security.identity.impl.IdentityManagerImpl.java
/** * @see IdentityManager#createNewMasterIdentity() */// w w w . j a v a 2s . com @Override public IdentityObject createNewMasterIdentity() throws NetInfCheckedException { // as soon as a new Master Identity is created, all Identites known to this IdentityManager will be stored to file. Thus, // ensure that identities are loaded from file before if (this.privateKeys.size() == 0) { try { loadIdentities(); } catch (NetInfCheckedException e) { LOG.warn("Unable to load key file. " + e.getMessage()); } } KeyPairGenerator k; try { k = KeyPairGenerator.getInstance("RSA"); } catch (Exception e) { LOG.warn(e.getMessage()); return null; } k.initialize(1024); KeyPair pair = k.generateKeyPair(); // A new Master Identity implies a new Identity Object. Create it IdentityObject newIdentity = ValidCreator.createValidIdentityObject(pair.getPublic()); // Derive the "Identity-Path" String pathToKey = newIdentity.getIdentifier().toString() + IntegrityImpl.PATH_SEPERATOR + DefinedAttributeIdentification.PUBLIC_KEY.getURI(); this.privateKeys.put(pathToKey, pair.getPrivate()); LOG.info("Private Key: " + Utils.objectToString(pair.getPrivate())); LOG.info("Public Key: " + Utils.objectToString(pair.getPublic())); // save private keys to file writePrivateKeysToFile(this.defaultFilepath, this.defaultKeyAlgorithmName, this.defaultPassword); return newIdentity; }
From source file:com.atlassian.jira.security.auth.trustedapps.TestDefaultCurrentApplicationStore.java
private void assertState(KeyPair pair, String applicationId, CurrentApplicationStore applicationStore) { assertState(pair.getPublic(), pair.getPrivate(), applicationId, applicationStore); }
From source file:it.zero11.acme.Acme.java
@SuppressWarnings("serial") protected String getHTTP01ChallengeRequest(final KeyPair userKey, final String token, final String nonce) { 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 v a2s. co m*/ put(RESOURCE_KEY, RESOURCE_CHALLENGE); put(CHALLENGE_TYPE_KEY, CHALLENGE_TYPE_HTTP_01); put(CHALLENGE_TLS_KEY, true); put(CHALLENGE_KEY_AUTHORIZATION_KEY, getHTTP01ChallengeContent(userKey, token)); put(CHALLENGE_TOKEN_KEY, token); } }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact(); }
From source file:org.springframework.security.oauth.common.signature.TestRSA_SHA1SignatureMethod.java
/** * tests signing and verifying.// www . j av a2s .c om */ public void testSignAndVerify() throws Exception { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(1024); KeyPair keyPair = generator.generateKeyPair(); String baseString = "thisismysignaturebasestringthatshouldbemuchlongerthanthisbutitdoesnthavetobeandherearesomestrangecharacters!@#$%^&*)(*"; byte[] signatureBytes; { Signature signer = Signature.getInstance("SHA1withRSA"); signer.initSign(keyPair.getPrivate()); signer.update(baseString.getBytes("UTF-8")); signatureBytes = signer.sign(); } { Signature signer = Signature.getInstance("SHA1withRSA"); signer.initVerify(keyPair.getPublic()); signer.update(baseString.getBytes("UTF-8")); assertTrue(signer.verify(signatureBytes)); } RSA_SHA1SignatureMethod signatureMethod = new RSA_SHA1SignatureMethod(keyPair.getPrivate(), keyPair.getPublic()); String signature = signatureMethod.sign(baseString); signatureMethod.verify(baseString, signature); }
From source file:it.zero11.acme.Acme.java
@SuppressWarnings("serial") protected String getAuthorizationRequest(final KeyPair userKey, final String nextNonce, final String domain) { return Jwts.builder().setHeaderParam(NONCE_KEY, nextNonce) .setHeaderParam(JwsHeader.JSON_WEB_KEY, JWKUtils.getWebKey(userKey.getPublic())) .setClaims(new TreeMap<String, Object>() { {/*from w w w. j a v a2 s.co m*/ put(RESOURCE_KEY, RESOURCE_NEW_AUTHZ); put(IDENTIFIER_KEY, new TreeMap<String, Object>() { { put(IDENTIFIER_TYPE_KEY, IDENTIFIER_TYPE_DNS); put(IDENTIFIER_VALUE_KEY, domain); } }); } }).signWith(getJWSSignatureAlgorithm(), userKey.getPrivate()).compact(); }
From source file:com.atlassian.jira.security.auth.trustedapps.TestDefaultCurrentApplicationStore.java
@Test public void testCreatesPropertiesIfNotThere() throws Exception { TrustedApplicationProperties properties = new TrustedApplicationProperties(); DefaultCurrentApplicationStore factory = new DefaultCurrentApplicationStore(properties, stubServerId("THIS.ISNT.AREA.LSID"), new MemoryCacheManager(), new SimpleClusterLockService()); factory.start();/*from w w w . j ava2s . com*/ final CurrentApplication currentApplication = factory.getCurrentApplication(); assertNotNull(currentApplication); KeyPair newPair = properties.getPair(); assertNotNull(newPair.getPrivate()); assertNotNull(newPair.getPublic()); assertTrue(isNotBlank(properties.getApplicationId())); assertState(newPair, properties.getApplicationId(), factory); }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * {@code connect} is for forming the secure connection between server and * android, sending and receiving of the data. * //from w w w .ja v a 2s .com * @param arg0 * data which is to be sent to server. * * @return data in string format, received from the server. */ public String connect(String... arg0) { int nrOfDataToSendToServer = arg0.length; nrOfDataToSendToServer = nrOfDataToSendToServer - 1; boolean valid = false; String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig; try { //Creating the server certificate Certificate serverCertificate = getServerCertificate(); KeyStore keyStore = getKeyStore(serverCertificate); TrustManagerFactory tmf = getTrustManager(keyStore); SSLContext sslContext = getSSLContext(tmf); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier); // Converting the data into JSONObject JSONObject obj = new JSONObject(); for (int i = 0; i <= nrOfDataToSendToServer; i++) { obj.put("param" + i, arg0[i]); } // Converting the JSONObject into string String dataToSend = obj.toString(); KeyPairGenerator keyGen = getKeyPairGenerator(); KeyPair keyPair = keyGen.generateKeyPair(); //Public key for verifying the digital signature PublicKey clientPublicKeySig = keyPair.getPublic(); //Private key for signing the data PrivateKey clientPrivateKeySig = keyPair.getPrivate(); // Get signed data String sigData = getDataSig(clientPrivateKeySig, dataToSend); // Creating URL Format String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8"); urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "=" + URLEncoder.encode(dataToSend, "UTF-8"); urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "=" + URLEncoder.encode(sigData, "UTF-8"); // Sending the data to the server OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(urlData); wr.flush(); wr.close(); // Receiving the data from server BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; // Read Server Response while ((line = reader.readLine()) != null) { // Append server response in string sb.append(line + "\n"); // sb.append(line); } String text = sb.toString(); reader.close(); // Extracting the data, public key and signature received from // server Vector<String> storeExtractedValues = new Vector<String>(); storeExtractedValues = extractDataFromJson(text, "data"); dataFromServer = storeExtractedValues.get(0); storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig"); serverPublicKeySigStr = storeExtractedValues.get(0); storeExtractedValues = extractDataFromJson(text, "serverDataSig"); serverDataSig = storeExtractedValues.get(0); // Converting the Server Public key format to Java compatible from PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr); // Verify the received data valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig); // Disconnect the url connection urlConnection.disconnect(); if (dataFromServer.equalsIgnoreCase("unverified")) { CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED; return "-1"; } else if (valid == false) { CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED; return "-1"; } else { return dataFromServer; } } catch (Exception e) { CExceptionHandling.ExceptionMsg = e.getMessage(); if (e.toString().equals("java.net.SocketException: Network unreachable")) { CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION; } else if (e.toString().equals( "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) { CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT; } else { CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS; } return "-1"; } }
From source file:com.vmware.admiral.auth.lightwave.pc.X509CertificateHelper.java
private X509Certificate generateCertificate(KeyPair keyPair, String dn, String sigAlg) throws OperatorCreationException, CertificateException { ContentSigner sigGen = new JcaContentSignerBuilder(sigAlg).build(keyPair.getPrivate()); Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + dn), new BigInteger(64, new SecureRandom()), startDate, endDate, new X500Name("CN=" + dn), keyPair.getPublic()); X509CertificateHolder certHolder = v3CertGen.build(sigGen); X509Certificate x509Certificate = new JcaX509CertificateConverter().getCertificate(certHolder); return x509Certificate; }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
private X509Certificate createSelfSignedCertificate(KeyStore keyStore, String dn, String alias) { try {//from w ww .j a v a 2 s . c o m // create new key pair for the node KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(keySize, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PublicKey publicKey = keypair.getPublic(); PrivateKey privateKey = keypair.getPrivate(); Certificate cert = certificateService.generateCertificate(dn, publicKey, privateKey); keyStore.setKeyEntry(alias, privateKey, getKeyStorePassword().toCharArray(), new Certificate[] { cert }); saveKeyStore(keyStore); return (X509Certificate) cert; } catch (NoSuchAlgorithmException e) { throw new CertificateException("Error setting up node key pair", e); } catch (KeyStoreException e) { throw new CertificateException("Error setting up node key pair", e); } }
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>() { {//from ww w . j av a 2 s. 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(); }