List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.titilink.common.app.EncryptDecryptUtil.java
public void testRSA() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, SignatureException { ////from w w w .j a v a 2s .co m KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); //? PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); //?? Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey, new SecureRandom()); byte[] cipherData = cipher .doFinal("this is a security text from server".getBytes(Charset.forName("UTF-8"))); // Cipher cipher1 = Cipher.getInstance("RSA"); cipher1.init(Cipher.DECRYPT_MODE, publicKey, new SecureRandom()); byte[] plainData = cipher1.doFinal(cipherData); System.out.println(new String(plainData, Charset.forName("UTF-8"))); //??????? Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey); signature.update(cipherData); byte[] signData = signature.sign(); //????? Signature signature1 = Signature.getInstance("MD5withRSA"); signature1.initVerify(publicKey); signature1.update(cipherData); System.out.println(signature1.verify(signData)); }
From source file:netinf.common.security.impl.CryptographyTest.java
@BeforeClass public static void classSetUp() throws Exception { final Properties properties = Utils.loadProperties(NETINFNODE_PROPERTIES); injector = Guice.createInjector(new LogModule(properties), new DatamodelImplModule(), new CommunicationModule(), new SecurityModule(), new AbstractModule() { @Override/*from w ww . j a v a2 s.c o m*/ protected void configure() { bind(NetInfNodeConnection.class).annotatedWith(SecurityModule.Security.class) .to(RemoteNodeConnection.class).in(Singleton.class); Names.bindProperties(binder(), properties); } }); factory = injector.getInstance(DatamodelFactory.class); identityObject = factory.createIdentityObject(); Identifier id = factory.createIdentifier(); IdentifierLabel label = factory.createIdentifierLabel(); label.setLabelName(DefinedLabelName.UNIQUE_LABEL.getLabelName()); label.setLabelValue("Test-Identity"); id.addIdentifierLabel(label); identityObject.setIdentifier(id); try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair pair = keyPairGenerator.generateKeyPair(); privateKey = pair.getPrivate(); publicKey = pair.getPublic(); String keyName = identityObject.getIdentifier().toString() + "?" + DefinedAttributeIdentification.PUBLIC_KEY.getURI(); publicKeys.put(keyName, publicKey); identityObject.setPublicMasterKey(pair.getPublic()); } catch (Exception e) { throw new NetInfUncheckedException("error creating keys"); } convenienceCommunicator = EasyMock.createMock(RemoteNodeConnection.class); convenienceCommunicator.setHostAndPort("localhost", 5000); EasyMock.expectLastCall().anyTimes(); convenienceCommunicator.setSerializeFormat(SerializeFormat.JAVA); EasyMock.expectLastCall().anyTimes(); EasyMock.expect(convenienceCommunicator.getIO((Identifier) EasyMock.anyObject())).andReturn(identityObject) .anyTimes(); EasyMock.replay(convenienceCommunicator); identityManager = EasyMock.createMock(IdentityManager.class); EasyMock.expect(identityManager.getPrivateKey((String) EasyMock.anyObject())).andReturn(privateKey) .anyTimes(); EasyMock.expect(identityManager.hasPrivateKey((String) EasyMock.anyObject())).andReturn(true).anyTimes(); EasyMock.expect(identityManager.getPrivateKey(((String) EasyMock.anyObject()), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(privateKey).anyTimes(); EasyMock.expect(identityManager.hasPrivateKey(((String) EasyMock.anyObject()), (String) EasyMock.anyObject(), (String) EasyMock.anyObject())).andReturn(true).anyTimes(); EasyMock.replay(identityManager); crypto = new CryptographyImpl(identityManager, algorithm, factory, convenienceCommunicator); }
From source file:org.candlepin.CRLBenchmark.java
@Setup(Level.Trial) public void buildMassiveCRL() throws Exception { X500Name issuer = new X500Name("CN=Test Issuer"); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);/*from www . j av a 2s. c om*/ KeyPair keyPair = generator.generateKeyPair(); Provider bc = new BouncyCastleProvider(); ContentSigner 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.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java
/** * Creates a new instance of RaAddUserCommand * * @param args command line arguments/* ww w .ja va 2s. c o m*/ */ public NestedCrmfRequestTestCommand(String[] args) { super(); if (args.length < NR_OF_MANDATORY_ARGS || args.length > MAX_NR_OF_ARGS) { usage(); System.exit(-1); // NOPMD, this is not a JEE app } hostname = args[ARG_HOSTNAME]; String certFile = args[ARG_CAFILE]; createsCertsPath = args.length > ARG_CREATEDCERTSPATH ? args[ARG_CREATEDCERTSPATH] : null; port = args.length > ARG_PORT ? Integer.parseInt(args[ARG_PORT].trim()) : 8080; urlPath = args.length > ARG_URLPATH && args[ARG_URLPATH].toLowerCase().indexOf("null") < 0 ? args[ARG_URLPATH].trim() : null; try { cacert = (X509Certificate) this.certificateFactory.generateCertificate(new FileInputStream(certFile)); final KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048); popokeys = keygen.generateKeyPair(); } catch (CertificateException e3) { e3.printStackTrace(getPrintStream()); System.exit(-1); } catch (FileNotFoundException e3) { e3.printStackTrace(getPrintStream()); System.exit(-1); } catch (NoSuchAlgorithmException e) { e.printStackTrace(getPrintStream()); System.exit(-1); } init(args); }
From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java
private KeyPairGenerator createKeyGenerator() throws CertificateException { try {// w ww . ja v a2s .com final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); return kpg; } catch (NoSuchAlgorithmException e) { throw new CertificateException("Failed to create RSA key pair generator." + e.getMessage()); } }
From source file:org.apache.abdera2.common.security.DHBase.java
private void init(BigInteger p, BigInteger g, int l, byte[] key) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException { DHParameterSpec spec = new DHParameterSpec(p, g, l); KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH"); keypairgen.initialize(spec);/* w w w .j a va 2 s.c o m*/ keyPair = keypairgen.generateKeyPair(); publicKey = decode(key); }
From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java
/** * Generates a key pair./*from w ww . j a v a 2 s .c o m*/ * * @return key pair * @throws NoSuchAlgorithmException no such algorithm */ public static KeyPair generateKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator clientKeyGen = KeyPairGenerator.getInstance(RSA); clientKeyGen.initialize(2048); return clientKeyGen.genKeyPair(); }
From source file:org.openengsb.core.services.internal.security.FileKeySource.java
private void generateKeysIfRequired(File keyDirectoryFile) { File privateKeyFile = new File(keyDirectoryFile, DEFAULT_PRIVATE_KEY_FILENAME); File publicKeyFile = new File(keyDirectoryFile, DEFAULT_PUBLIC_KEY_FILENAME); if (privateKeyFile.exists() && publicKeyFile.exists()) { LOGGER.info("skipping key-generation, because there already are some"); return;/*from www .ja va 2 s . co m*/ } KeyPairGenerator generator; try { LOGGER.info("generating new keypair"); generator = KeyPairGenerator.getInstance(DEFAULT_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("failed to generate keypair", e); } generator.initialize(DEFAULT_KEY_SIZE); KeyPair generatedKeyPair = generator.generateKeyPair(); try { LOGGER.trace("saving new keypair to files"); FileUtils.writeByteArrayToFile(privateKeyFile, generatedKeyPair.getPrivate().getEncoded()); FileUtils.writeByteArrayToFile(publicKeyFile, generatedKeyPair.getPublic().getEncoded()); } catch (IOException e) { throw new IllegalStateException("failed to write keys to key-directory", e); } }
From source file:org.apache.stratos.keystore.mgt.KeyStoreGenerator.java
/** * This method generates the keypair and stores it in the keystore * * @param keyStore A keystore instance/*from w w w .ja v a 2s. c om*/ * @return Generated public key for the tenant * @throws KeyStoreMgtException Error when generating key pair */ private X509Certificate generateKeyPair(KeyStore keyStore) throws KeyStoreMgtException { try { CryptoUtil.getDefaultCryptoUtil(); //generate key pair KeyPairGenerator keyPairGenerator = null; keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Common Name and alias for the generated certificate String commonName = "CN=" + tenantDomain + ", OU=None, O=None L=None, C=None"; //generate certificates X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt())); v3CertGen.setIssuerDN(new X509Principal(commonName)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); v3CertGen.setSubjectDN(new X509Principal(commonName)); v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate PKCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate()); //add private key to KS keyStore.setKeyEntry(tenantDomain, keyPair.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { PKCertificate }); return PKCertificate; } catch (Exception ex) { String msg = "Error while generating the certificate for tenant :" + tenantDomain + "."; log.error(msg, ex); throw new KeyStoreMgtException(msg, ex); } }
From source file:com.awstrainers.devcourse.sdkdemos.S3Test.java
@Test public void checkUploadEncryptedObject() throws Exception { // Check the next url to read about how to use strong encryption with the jdk. // http://www.oracle.com/technetwork/es/java/javase/downloads/jce-7-download-432124.html KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGenerator.genKeyPair(); // obviously that keypair should be stored somewhere, but this is just a test. EncryptionMaterials encryptionMaterials = new EncryptionMaterials(keyPair); AmazonS3 client = new AmazonS3EncryptionClient(cred, encryptionMaterials); log.info(format("Using {0} bucket to post a new encrypted file.", bucketName)); File file = createTempFile(); Bucket bucket = client.createBucket(bucketName); PutObjectResult result = client.putObject(bucket.getName(), file.getName(), file); }