List of usage examples for java.security KeyPairGenerator initialize
public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException
From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java
@Before public void setup() { service = new BCCertificateService(); KeyPairGenerator keyGen; try {// w w w. j a v a2 s . c o m keyGen = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } keyGen.initialize(2048, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); publicKey = keypair.getPublic(); privateKey = keypair.getPrivate(); }
From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * ??/*w ww.j a v a 2 s. c om*/ * * @param pubFile public file * @param priFile private file * @throws IOException IOException */ @SuppressWarnings("PMD.PrematureDeclaration") protected void generater(File pubFile, File priFile) throws IOException { try { KeyPairGenerator keygen = KeyPairGenerator.getInstance(ALGORITHM); SecureRandom secrand = new SecureRandom(); keygen.initialize(KEY_SIZE, secrand); KeyPair keys = keygen.genKeyPair(); PublicKey pubkey = keys.getPublic(); PrivateKey prikey = keys.getPrivate(); byte[] priKey = Base64.encodeBase64(prikey.getEncoded()); byte[] pubKey = Base64.encodeBase64(pubkey.getEncoded()); if (pubFile.exists()) { throw new IOException(pubFile.getPath() + " is exist!"); } if (priFile.exists()) { throw new IOException(priFile.getPath() + " is exist!"); } OutputStream pubOutput = new FileOutputStream(pubFile); try { IOUtils.write(pubKey, pubOutput); } finally { IOUtils.closeQuietly(pubOutput); } OutputStream priOutput = new FileOutputStream(priFile); try { IOUtils.write(priKey, priOutput); } finally { IOUtils.closeQuietly(priOutput); } } catch (NoSuchAlgorithmException e) { log.error("?", e); } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectoryTestCase.java
/** * Method to create a X509 certificate used to test the creation and the update of an entry in the ldap. * * @return A X509 certificate/* w ww .j ava 2 s . co m*/ * @throws CertificateException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException * @throws IllegalStateException * @since 5.9.3 */ protected X509Certificate createCertificate(String dnNameStr) throws NoSuchAlgorithmException, CertificateException, InvalidKeyException, IllegalStateException, SignatureException { X509Certificate cert = null; // Parameters used to define the certificate // yesterday Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); // in 2 years Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000); // Generate the key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Define the content of the certificate X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal dnName = new X500Principal(dnNameStr); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setSubjectDN(dnName); certGen.setIssuerDN(dnName); // use the same certGen.setNotBefore(validityBeginDate); certGen.setNotAfter(validityEndDate); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSA"); cert = certGen.generate(keyPair.getPrivate()); return cert; }
From source file:mitm.common.security.certificate.GenerateSSLCertificate.java
private void generateSSLCertificate() throws Exception { X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder(); KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA"); SecureRandom randomSource = securityFactory.createSecureRandom(); keyPairGenerator.initialize(1024, randomSource); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder(); subjectBuilder.setCommonName("www.example.com"); subjectBuilder.setCountryCode("NL"); subjectBuilder.setLocality("Amsterdam"); subjectBuilder.setState("NH"); X500Principal subject = subjectBuilder.buildPrincipal(); Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>(); extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH); extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION); extendedKeyUsage.add(ExtendedKeyUsageType.SERVERAUTH); SerialNumberGenerator sng = new StandardSerialNumberGenerator(); BigInteger serialNumber = sng.generate(); Date now = new Date(); certificateBuilder.setSubject(subject); certificateBuilder.setIssuer(subject); certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false); certificateBuilder.setNotBefore(DateUtils.addDays(now, -20)); certificateBuilder.setNotAfter(DateUtils.addYears(now, 20)); certificateBuilder.setPublicKey(keyPair.getPublic()); certificateBuilder.setSerialNumber(serialNumber); certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption"); X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null); assertNotNull(certificate);//from w w w .j a va2 s . co m certificates.add(certificate); Certificate[] chain = new Certificate[] { certificate }; keyStore.setKeyEntry("djigzo", keyPair.getPrivate(), null, chain); }
From source file:com.turo.pushy.apns.ApnsClientBenchmark.java
@Setup public void setUp() throws Exception { this.eventLoopGroup = new NioEventLoopGroup(2); final ApnsSigningKey signingKey; {/*from w ww. ja v a 2 s . c om*/ final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); final SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyPairGenerator.initialize(256, random); signingKey = new ApnsSigningKey(KEY_ID, TEAM_ID, (ECPrivateKey) keyPairGenerator.generateKeyPair().getPrivate()); } final ApnsClientBuilder clientBuilder = new ApnsClientBuilder().setApnsServer(HOST, PORT) .setConcurrentConnections(this.concurrentConnections).setSigningKey(signingKey) .setTrustedServerCertificateChain( ApnsClientBenchmark.class.getResourceAsStream(CA_CERTIFICATE_FILENAME)) .setEventLoopGroup(this.eventLoopGroup); this.client = clientBuilder.build(); this.server = new BenchmarkApnsServer( ApnsClientBenchmark.class.getResourceAsStream(SERVER_CERTIFICATES_FILENAME), ApnsClientBenchmark.class.getResourceAsStream(SERVER_KEY_FILENAME), this.eventLoopGroup); final String token = generateRandomToken(); this.pushNotifications = new ArrayList<>(this.notificationCount); final ApnsPayloadBuilder payloadBuilder = new ApnsPayloadBuilder(); for (int i = 0; i < this.notificationCount; i++) { final String payload = payloadBuilder .setAlertBody(RandomStringUtils.randomAlphanumeric(MESSAGE_BODY_LENGTH)) .buildWithDefaultMaximumLength(); this.pushNotifications.add(new SimpleApnsPushNotification(token, TOPIC, payload)); } this.server.start(PORT).await(); }
From source file:ie.peternagy.jcrypto.algo.EllipticCurveWrapper.java
/** * Generate a set of Elliptic Curve keys *//* ww w. j a v a 2 s .c om*/ public void generateKeys() { tryLoadKeys(); if (isInitialized(true) && isInitialized(false)) { return; } try { ECGenParameterSpec ecGenSpec = new ECGenParameterSpec(EC_CURVE); KeyPairGenerator g = KeyPairGenerator.getInstance(ALGORITHM_NAME); g.initialize(ecGenSpec, CryptoSecurityUtil.getSecureRandom()); KeyPair pair = g.generateKeyPair(); privateKey = pair.getPrivate(); publicKey = pair.getPublic(); writeKeys(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException ex) { Logger.getLogger(EllipticCurveWrapper.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testPSS() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC"); byte[] data = "hello world".getBytes(); signature.initSign(privateKey);// w w w.j a v a 2s . co m signature.update(data); byte[] signatureValue = signature.sign(); LOG.debug("signature size: " + signatureValue.length); LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue))); signature.initVerify(publicKey); signature.update(data); boolean result = signature.verify(signatureValue); assertTrue(result); signature.initSign(privateKey); signature.update(data); byte[] signatureValue2 = signature.sign(); LOG.debug("signature size: " + signatureValue2.length); LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2))); assertFalse(Arrays.equals(signatureValue, signatureValue2)); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC"); byte[] digest = messageDigest.digest(data); signature = Signature.getInstance("RAWRSASSA-PSS", "BC"); signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); signature.initVerify(publicKey); signature.update(digest); result = signature.verify(signatureValue); assertTrue(result); }
From source file:com.streamsets.datacollector.publicrestapi.TestCredentialsDeploymentResource.java
private KeyPair generateKeys() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(512, random); return keyGen.generateKeyPair(); }
From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java
private KeyPair generateKeyPair() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); return keyPairGenerator.generateKeyPair(); }
From source file:org.sonatype.sisu.encryptor.RsaAesEncryptor.java
public void generateKeys(OutputStream publicKeyOut, OutputStream privateKeyOut) throws GeneralSecurityException, IOException { KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); generator.initialize(KEY_SIZE * 8, random); KeyPair keyPair = generator.generateKeyPair(); OutputStream privateOut = new Base64OutputStream(privateKeyOut); PrivateKey privateKey = keyPair.getPrivate(); privateOut.write(privateKey.getEncoded()); IOUtil.close(privateOut);/*from www . ja va2s . c o m*/ OutputStream publicOut = new Base64OutputStream(publicKeyOut); PublicKey publicKey = keyPair.getPublic(); publicOut.write(publicKey.getEncoded()); IOUtil.close(publicOut); }