List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:models.logic.CipherDecipher.java
public static KeyPair publicPrivateKeyGenerator() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { //Generation// ww w. j a v a2 s. co m KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); return kpg.genKeyPair(); }
From source file:org.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java
public ProtocolStackLoopbackLoadStress(boolean nio, boolean ssl) throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException, UnrecoverableKeyException, KeyManagementException, OperatorCreationException { KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(2048); // maximum supported by JVM with export restrictions keyPair = gen.generateKeyPair();/*from w ww . j a va 2 s.c o m*/ Date now = new Date(); Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10)); Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10)); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo .getInstance(keyPair.getPublic().getEncoded()); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US") .build(); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate, lastDate, subject, subjectPublicKeyInfo); JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils(); certGen.addExtension(X509Extension.subjectKeyIdentifier, false, instance.createSubjectKeyIdentifier(subjectPublicKeyInfo)); ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER) .build(keyPair.getPrivate()); certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER) .getCertificate(certGen.build(signer)); char[] password = "password".toCharArray(); KeyStore store = KeyStore.getInstance("jks"); store.load(null, password); store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate }); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(store, password); context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), new TrustManager[] { new PublicKeyMatchingX509ExtendedTrustManager(keyPair.getPublic()) }, null); hub = IOHub.create(executorService); serverSocketChannel = ServerSocketChannel.open(); acceptor = new Acceptor(serverSocketChannel, nio, ssl); }
From source file:org.umit.icm.mobile.utils.RSACrypto.java
public static KeyPair generateKey() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(Constants.RSA_KEY_SIZE); return keyPairGen.generateKeyPair(); }
From source file:org.kaaproject.kaa.server.transports.http.transport.HttpTestClient.java
/** * Initialization of request keys and encoder/decoder * * @param serverPublicKey - server public key * @throws Exception - if key generation failed. */// ww w . java 2 s .c o m private void init(PublicKey serverPublicKey) throws Exception { KeyPairGenerator clientKeyGen; try { clientKeyGen = KeyPairGenerator.getInstance("RSA"); clientKeyGen.initialize(2048); KeyPair clientKeyPair = clientKeyGen.genKeyPair(); clientPrivateKey = clientKeyPair.getPrivate(); clientPublicKey = clientKeyPair.getPublic(); } catch (NoSuchAlgorithmException e) { throw new Exception(e.toString()); } crypt = new MessageEncoderDecoder(clientPrivateKey, clientPublicKey, serverPublicKey); try { key = crypt.getEncodedSessionKey(); } catch (GeneralSecurityException e) { throw new Exception(e.toString()); } ByteBuffer publicKeyBuffer = ByteBuffer .wrap(EndpointObjectHash.fromSha1(clientPublicKey.getEncoded()).getData()); clientPublicKeyHash = EndpointObjectHash.fromBytes(publicKeyBuffer.array()); }
From source file:org.candlepin.CRLWriteBenchmark.java
@Setup(Level.Trial) public void buildMassiveCRL() throws Exception { issuer = new X500Name("CN=Test Issuer"); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);//from w ww . j a v a 2s .co m KeyPair keyPair = generator.generateKeyPair(); bc = new BouncyCastleProvider(); signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc).build(keyPair.getPrivate()); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date()); crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(keyPair.getPublic())); /* With a CRL number of 127, incrementing it should cause the number of bytes in the length * portion of the TLV to increase by one.*/ crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127"))); for (int i = 0; i < 2000000; i++) { crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified); } X509CRLHolder holder = crlBuilder.build(signer); X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder); crlFile = File.createTempFile("crl", ".der"); System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath()); FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded()); }
From source file:org.candlepin.sync.ExporterTest.java
private KeyPair createKeyPair() { KeyPair cpKeyPair = null;// w w w . j ava 2s.c o m try { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); java.security.KeyPair newPair = generator.generateKeyPair(); cpKeyPair = new KeyPair(newPair.getPrivate(), newPair.getPublic()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return cpKeyPair; }
From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java
/** * Default constructor./*from ww w . ja v a 2s. c om*/ * * @throws Exception */ protected X509CertificateBuilderAcceptanceTest() throws GeneralSecurityException, InvalidNameException, URISyntaxException, UnknownHostException, IOException { certUtil = new X509CertificateUtilImpl(); TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // create key pairs. this is for testing so we use 512-bit keys for // speed. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(512); keyPair = keyPairGen.generateKeyPair(); issuerKeyPair = keyPairGen.generateKeyPair(); grandfatherKeyPair = keyPairGen.generateKeyPair(); notBefore = Calendar.getInstance(); notBefore.set(Calendar.MINUTE, 0); notBefore.set(Calendar.SECOND, 0); notBefore.set(Calendar.MILLISECOND, 0); notAfter = Calendar.getInstance(); notAfter.setTime(notBefore.getTime()); notAfter.add(Calendar.YEAR, 1); expectedGeneralNameUri1 = new com.otterca.common.crypto.GeneralName.URI("http://example.com"); expectedGeneralNameUri2 = new com.otterca.common.crypto.GeneralName.URI("ldap://example.net"); expectedGeneralNameDir = new com.otterca.common.crypto.GeneralName.Directory("C=US,ST=AK,C=Anchorage"); expectedGeneralNameEmail = new com.otterca.common.crypto.GeneralName.Email("bob@example.com"); expectedGeneralNameDns = new com.otterca.common.crypto.GeneralName.DNS("example.com"); expectedGeneralNameIpAddress = new com.otterca.common.crypto.GeneralName.IpAddress("127.0.0.1"); }
From source file:netinf.common.security.identity.impl.IdentityManagerImpl.java
/** * @see IdentityManager#createNewMasterIdentity() */// w w w . ja va 2s . c om @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:hudson.cli.Connection.java
public KeyAgreement diffieHellman(boolean side, int keySize) throws IOException, GeneralSecurityException { KeyPair keyPair;/*from ww w . j a v a2s . c o m*/ PublicKey otherHalf; if (side) { AlgorithmParameterGenerator paramGen = AlgorithmParameterGenerator.getInstance("DH"); paramGen.init(keySize); KeyPairGenerator dh = KeyPairGenerator.getInstance("DH"); dh.initialize(paramGen.generateParameters().getParameterSpec(DHParameterSpec.class)); keyPair = dh.generateKeyPair(); // send a half and get a half writeKey(keyPair.getPublic()); otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey()); } else { otherHalf = KeyFactory.getInstance("DH").generatePublic(readKey()); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DH"); keyPairGen.initialize(((DHPublicKey) otherHalf).getParams()); keyPair = keyPairGen.generateKeyPair(); // send a half and get a half writeKey(keyPair.getPublic()); } KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(keyPair.getPrivate()); ka.doPhase(otherHalf, true); return ka; }
From source file:com.microsoft.azure.keyvault.extensions.RsaKey.java
public RsaKey(String kid, int keySize) throws NoSuchAlgorithmException { if (Strings.isNullOrWhiteSpace(kid)) { throw new IllegalArgumentException("kid"); }//from w w w .j av a 2 s . c om final KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(keySize); _keyPair = generator.generateKeyPair(); _kid = kid; }