List of usage examples for java.security KeyPair getPrivate
public PrivateKey getPrivate()
From source file:com.POLIS.licensing.frontend.AnnotationEnabledFrontendTest.java
@Before public void setUp() throws NoSuchAlgorithmException, NoSuchProviderException, SystemStateException, OperationException { frontend = new AnnotationEnabledFrontend<>(new TestFactory(), new TestConnector(), new TestDecorator()); SecureRandom random = new SecureRandom(); KeyPairGenerator rsagenerator = KeyPairGenerator.getInstance("RSA", "BC"); rsagenerator.initialize(1024, random); KeyPair pair = rsagenerator.generateKeyPair(); serverPubKey = pair.getPublic();//from www . ja va 2s. c om serverPrivKey = pair.getPrivate(); frontend.initialize(serverPubKey); }
From source file:org.dataone.proto.trove.net.SocketFactoryManager.java
/** * Load PEM file contents into in-memory keystore NOTE: this implementation uses Bouncy Castle security provider * * @return the keystore that will provide the material * @throws KeyStoreException// w w w. j av a 2s . c om * @throws CertificateException * @throws NoSuchAlgorithmException * @throws IOException */ private KeyStore getKeyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { // if the location has been set, use it KeyStore keyStore = null; Object pemObject = null; keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, keyStorePassword.toCharArray()); // get the private key and certificate from the PEM // TODO: find a way to do this with default Java provider (not Bouncy Castle)? Security.addProvider(new BouncyCastleProvider()); PEMParser pemReader = new PEMParser(new FileReader(clientCertificateLocation)); X509Certificate certificate = null; PrivateKey privateKey = null; KeyPair keyPair = null; while ((pemObject = pemReader.readObject()) != null) { if (pemObject instanceof PrivateKey) { privateKey = (PrivateKey) pemObject; } else if (pemObject instanceof KeyPair) { keyPair = (KeyPair) pemObject; privateKey = keyPair.getPrivate(); } else if (pemObject instanceof X509Certificate) { certificate = (X509Certificate) pemObject; } } if (certificate == null) { log.warn("Certificate is null"); } else { if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253) .equals(certificate.getIssuerX500Principal().getName(X500Principal.RFC2253))) { log.warn("Certificate is Self Signed"); } } Certificate[] chain = new Certificate[] { certificate }; // set the entry keyStore.setKeyEntry("cilogon", privateKey, keyStorePassword.toCharArray(), chain); return keyStore; }
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 . c om @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: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);// w ww . j ava2s. c o m 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:jp.primecloud.auto.service.impl.IaasDescribeServiceImpl.java
protected PrivateKey toPrivateKey(String privateKey) { StringReader reader = new StringReader(privateKey); // ??/*from www . j a v a2s. c om*/ PEMReader pemReader = new PEMReader(reader); try { Object pemObject = pemReader.readObject(); KeyPair keyPair = KeyPair.class.cast(pemObject); return keyPair.getPrivate(); } catch (Exception e) { // ??????? throw new AutoApplicationException("ESERVICE-000705", e); } finally { try { pemReader.close(); } catch (IOException ignore) { } } }
From source file:io.vertx.config.vault.utils.Certificates.java
/** * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder * * @param keyPair The RSA keypair with which to generate the certificate * @param issuer The issuer (and subject) to use for the certificate * @return An X509 certificate// w w w .j a v a 2 s .c om * @throws IOException * @throws OperatorCreationException * @throws CertificateException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException */ private static X509Certificate generateCert(final KeyPair keyPair, final String issuer) throws IOException, OperatorCreationException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { final String subject = issuer; final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(new X500Name(issuer), BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(subject), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded())); final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false, subjectAltNames); final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("SHA1WithRSAEncryption"); final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); final ContentSigner signer = signerBuilder.build(keyp); final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer); final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder); certificate.checkValidity(new Date()); certificate.verify(keyPair.getPublic()); return certificate; }
From source file:org.aon.esolutions.appconfig.web.controller.EnvironmentController.java
private Map<String, String> updateKeys(Environment env) throws Exception { Map<String, String> answer = new HashMap<String, String>(); if (env != null) { // First, get private key - Performs ACL Checking PrivateKeyHolder holder = null;//www.j a va2 s. co m if (env.getPrivateKeyHolder() != null) holder = privateKeyRepository.findOne(env.getPrivateKeyHolder().getId()); if (holder != null) { Key key = RSAEncryptUtil.getPrivateKeyFromString(holder.getPrivateKey()); for (String encryptedVariable : env.getEncryptedVariables()) { String encryptedValue = env.get(encryptedVariable); if (encryptedValue != null) { String decryptedValue = RSAEncryptUtil.decrypt(encryptedValue, key); env.put(encryptedVariable, decryptedValue); } } } else { holder = new PrivateKeyHolder(); env.setPrivateKeyHolder(holder); holder.setEnvironment(env); } // Generate the new keys KeyPair keyPair = RSAEncryptUtil.generateKey(); env.setPublicKey(RSAEncryptUtil.getKeyAsString(keyPair.getPublic())); holder.setPrivateKey(RSAEncryptUtil.getKeyAsString(keyPair.getPrivate())); // Re-encrypt with the new values for (String encryptedVariable : env.getEncryptedVariables()) { String decryptedValue = env.get(encryptedVariable); if (decryptedValue != null) { String encryptedValue = RSAEncryptUtil.encrypt(decryptedValue, keyPair.getPublic()); env.put(encryptedVariable, encryptedValue); } } updateUtility.savePrivateKeyHolder(holder); answer.put("publicKey", env.getPublicKey()); answer.put("privateKey", holder.getPrivateKey()); } return answer; }
From source file:com.vmware.demo.SamlUtils.java
/** * Generate a public x509 cert, based on a key. * * @param key KeyPair used to generate public Cert, private key in KeyPair not exposed. * @param issuer If generating an SSL Cert, issuer needs to match hostname * @return/*ww w. j a v a 2 s . c o m*/ * @throws SamlException */ public static X509Certificate generateCert(KeyPair key, String issuer) throws SamlException { X509Certificate binCert; try { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); // create the certificate - version 3 v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(new X509Principal(issuer)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis())); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); //10 years v3CertGen.setSubjectDN(new X509Principal(issuer)); v3CertGen.setPublicKey(key.getPublic()); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // add the extensions v3CertGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, false, new BasicConstraints(true)); // generate the actual cert binCert = v3CertGen.generate(key.getPrivate()); // check the cert binCert.checkValidity(new Date()); binCert.verify(key.getPublic()); } catch (Exception e) { throw new SamlException("Failed to generate certificate.", e); } return binCert; }
From source file:com.google.u2f.key.impl.U2FKeyReferenceImpl.java
@Override public AuthenticateResponse authenticate(AuthenticateRequest authenticateRequest) throws U2FException { Log.info(">> authenticate"); byte control = authenticateRequest.getControl(); byte[] applicationSha256 = authenticateRequest.getApplicationSha256(); byte[] challengeSha256 = authenticateRequest.getChallengeSha256(); byte[] keyHandle = authenticateRequest.getKeyHandle(); Log.info(" -- Inputs --"); Log.info(" control: " + control); Log.info(" applicationSha256: " + Hex.encodeHexString(applicationSha256)); Log.info(" challengeSha256: " + Hex.encodeHexString(challengeSha256)); Log.info(" keyHandle: " + Hex.encodeHexString(keyHandle)); KeyPair keyPair = dataStore.getKeyPair(keyHandle); int counter = dataStore.incrementCounter(); byte userPresence = userPresenceVerifier.verifyUserPresence(); byte[] signedData = RawMessageCodec.encodeAuthenticateSignedBytes(applicationSha256, userPresence, counter, challengeSha256);/*www .ja v a 2s. c o m*/ Log.info("Signing bytes " + Hex.encodeHexString(signedData)); byte[] signature = crypto.sign(signedData, keyPair.getPrivate()); Log.info(" -- Outputs --"); Log.info(" userPresence: " + userPresence); Log.info(" counter: " + counter); Log.info(" signature: " + Hex.encodeHexString(signature)); Log.info("<< authenticate"); return new AuthenticateResponse(userPresence, counter, signature); }
From source file:edu.vt.middleware.crypt.asymmetric.AsymmetricCli.java
/** * Generate a new encryption public/private key pair using CLI arguments. * * @param line Parsed command line arguments container. * * @throws Exception On encryption errors. *///from w w w.ja v a 2s.c o m protected void genKeyPair(final CommandLine line) throws Exception { validateOptions(line); final AsymmetricAlgorithm alg = newAlgorithm(line); final int size = Integer.parseInt(line.getOptionValue(OPT_GENKEYPAIR)); System.err.println("Generating " + alg + " key pair of " + size + " bits"); final KeyPair keyPair = PublicKeyUtils.generate(alg.getAlgorithm(), size); final File pubKeyFile = new File(line.getOptionValue(OPT_OUTFILE)); final File privKeyFile = new File(line.getOptionValue(OPT_PRIVKEYPATH)); CryptWriter.writeEncodedKey(keyPair.getPublic(), pubKeyFile); System.err.println("Wrote X.509 DER-encoded public key to " + pubKeyFile); CryptWriter.writeEncodedKey(keyPair.getPrivate(), privKeyFile); System.err.println("Wrote PKCS#8 DER-encoded private key to " + privKeyFile); }