List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.l2jfree.loginserver.manager.GameServerManager.java
/** * Load RSA keys/*ww w .j a va2 s .c o m*/ * @throws NoSuchAlgorithmException * @throws InvalidAlgorithmParameterException */ private void loadRSAKeys() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4); keyGen.initialize(spec); _keyPairs = new KeyPair[KEYS_SIZE]; for (int i = 0; i < KEYS_SIZE; i++) { _keyPairs[i] = keyGen.genKeyPair(); } _log.info("GameServerManager: Cached " + _keyPairs.length + " RSA keys for Game Server communication."); }
From source file:com.owncloud.android.utils.PushUtils.java
private static int generateRsa2048KeyPair() { String keyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder() + File.separator + KEYPAIR_FOLDER;//from w ww . j a v a2 s . c om String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION; String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION; File keyPathFile = new File(keyPath); if (!new File(privateKeyPath).exists() && !new File(publicKeyPath).exists()) { try { if (!keyPathFile.exists()) { keyPathFile.mkdir(); } KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair pair = keyGen.generateKeyPair(); int statusPrivate = saveKeyToFile(pair.getPrivate(), privateKeyPath); int statusPublic = saveKeyToFile(pair.getPublic(), publicKeyPath); if (statusPrivate == 0 && statusPublic == 0) { // all went well return 0; } else { return -2; } } catch (NoSuchAlgorithmException e) { Log_OC.d(TAG, "RSA algorithm not supported"); } } else { // we already have the key return -1; } // we failed to generate the key return -2; }
From source file:cherry.goods.crypto.VersionedSignatureTest.java
private RSASignature createRSASignature() throws Exception { KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA"); keygen.initialize(2048);/*from w w w . java 2 s . c om*/ KeyPair key = keygen.generateKeyPair(); RSASignature impl = new RSASignature(); impl.setAlgorithm("SHA256withRSA"); impl.setPublicKeyBytes(key.getPublic().getEncoded()); impl.setPrivateKeyBytes(key.getPrivate().getEncoded()); return impl; }
From source file:net.nicholaswilliams.java.licensing.TestLicenseManager.java
@BeforeClass public static void setUpClass() throws Exception { TestLicenseManager.control = EasyMock.createStrictControl(); TestLicenseManager.licenseProvider = TestLicenseManager.control.createMock(LicenseProvider.class); TestLicenseManager.publicKeyPasswordProvider = TestLicenseManager.control .createMock(PasswordProvider.class); TestLicenseManager.licensePasswordProvider = TestLicenseManager.control.createMock(PasswordProvider.class); TestLicenseManager.keyDataProvider = TestLicenseManager.control.createMock(PublicKeyDataProvider.class); TestLicenseManager.licenseValidator = TestLicenseManager.control.createMock(LicenseValidator.class); try {//from w w w . j ava2 s .co m LicenseManager.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseManagerProperties.setLicenseProvider(TestLicenseManager.licenseProvider); try { LicenseManager.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseManagerProperties.setPublicKeyDataProvider(TestLicenseManager.keyDataProvider); try { LicenseManager.getInstance(); fail("Expected java.lang.IllegalArgumentException, got no exception."); } catch (IllegalArgumentException ignore) { } LicenseManagerProperties.setPublicKeyPasswordProvider(TestLicenseManager.publicKeyPasswordProvider); LicenseManagerProperties.setLicensePasswordProvider(TestLicenseManager.licensePasswordProvider); LicenseManagerProperties.setLicenseValidator(TestLicenseManager.licenseValidator); LicenseManagerProperties.setCacheTimeInMinutes(0); LicenseManager.getInstance(); KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair(); TestLicenseManager.privateKey = keyPair.getPrivate(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded()); IOUtils.write(Encryptor.encryptRaw(x509EncodedKeySpec.getEncoded(), TestLicenseManager.keyPassword), outputStream); TestLicenseManager.encryptedPublicKey = outputStream.toByteArray(); }
From source file:org.apache.xml.security.test.signature.XmlSecTest.java
private void checkXmlSignatureSoftwareStack(boolean cert) throws Exception { Init.init();/*from w w w . j av a 2 s.co m*/ DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document testDocument = documentBuilder.newDocument(); Element rootElement = testDocument.createElementNS("urn:namespace", "tns:document"); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:namespace"); testDocument.appendChild(rootElement); Element childElement = testDocument.createElementNS("urn:childnamespace", "t:child"); childElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:t", "urn:childnamespace"); childElement.appendChild(testDocument.createTextNode("hello world")); rootElement.appendChild(childElement); PrivateKey privateKey = null; PublicKey publicKey = null; X509Certificate signingCert = null; if (cert) { // get key & self-signed certificate from keystore String fs = System.getProperty("file.separator"); FileInputStream fis = new FileInputStream(BASEDIR + fs + "data" + fs + "test.jks"); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(fis, "changeit".toCharArray()); signingCert = (X509Certificate) ks.getCertificate("mullan"); publicKey = signingCert.getPublicKey(); privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray()); } else { KeyPair keyPair = KeyPairGenerator.getInstance("DSA").generateKeyPair(); publicKey = keyPair.getPublic(); privateKey = keyPair.getPrivate(); } XMLSignature signature = new XMLSignature(testDocument, "", XMLSignature.ALGO_ID_SIGNATURE_DSA, Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS); Element signatureElement = signature.getElement(); rootElement.appendChild(signatureElement); Transforms transforms = new Transforms(testDocument); XPathContainer xpath = new XPathContainer(testDocument); xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS); xpath.setXPath("not(ancestor-or-self::ds:Signature)"); transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns()); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1); if (cert) { signature.addKeyInfo(signingCert); } else { signature.addKeyInfo(publicKey); } Element nsElement = testDocument.createElementNS(null, "nsElement"); nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", Constants.SignatureSpecNS); signature.sign(privateKey); // TransformerFactory tf = TransformerFactory.newInstance(); // Transformer t = tf.newTransformer(); // t.transform(new DOMSource(testDocument), new StreamResult(System.out)); NodeList signatureElems = XPathAPI.selectNodeList(testDocument, "//ds:Signature", nsElement); signatureElement = (Element) signatureElems.item(0); XMLSignature signatureToVerify = new XMLSignature(signatureElement, ""); boolean signResult = signatureToVerify.checkSignatureValue(publicKey); assertTrue(signResult); }
From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java
@Test public void signCertificate() throws Exception { X509Certificate cert = service.generateCertificate(TEST_DN, publicKey, privateKey); String csr = service.generatePKCS10CertificateRequestString(cert, privateKey); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048, new SecureRandom()); KeyPair caKeypair = keyGen.generateKeyPair(); X509Certificate caCert = service.generateCertificationAuthorityCertificate(TEST_CA_DN, caKeypair.getPublic(), caKeypair.getPrivate()); X509Certificate signed = service.signCertificate(csr, caCert, caKeypair.getPrivate()); assertEquals("Issuer", caCert.getSubjectX500Principal(), signed.getIssuerX500Principal()); assertEquals("Subject", cert.getSubjectX500Principal(), signed.getSubjectX500Principal()); }
From source file:pepperim.util.IMCrypt.java
/** * Generates a new 2048 bit RSA keypair. * @return String array containing: [Base64-encoded public key, Base64-encoded private key] *//* ww w . j a v a2 s . c o m*/ public static String[] RSA_genKeypair() { try { KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(2048, random); KeyPair keyPair = pairgen.generateKeyPair(); String[] keypair = new String[2]; keypair[0] = B64_Enc(keyPair.getPublic().getEncoded()); keypair[1] = B64_Enc(keyPair.getPrivate().getEncoded()); return keypair; } catch (GeneralSecurityException e) { Main.log(e.getMessage()); return null; } }
From source file:com.joyent.manta.config.TestConfigContext.java
/** * Some test cases need a direct reference to a KeyPair along with it's associated config. Manually calling * KeyPairFactory with a half-baked config can get cumbersome, so let's build a ConfigContext which has * everything ready and supplies the relevant KeyPair. * * @return the generated keypair and a config which uses a serialized version of that keypair *//* www . j av a2 s . c o m*/ public static ImmutablePair<KeyPair, BaseChainedConfigContext> generateKeyPairBackedConfig( final String passphrase) { final KeyPair keyPair; try { keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair(); } catch (final NoSuchAlgorithmException impossible) { throw new Error(impossible); // "RSA" is always provided } final Object keySerializer; if (passphrase != null) { try { keySerializer = new JcaMiscPEMGenerator(keyPair.getPrivate(), new JcePEMEncryptorBuilder("AES-128-CBC").build(passphrase.toCharArray())); } catch (IOException e) { throw new RuntimeException(e); } } else { keySerializer = keyPair.getPrivate(); } final String keyContent; try (final StringWriter content = new StringWriter(); final JcaPEMWriter writer = new JcaPEMWriter(content)) { writer.writeObject(keySerializer); writer.flush(); keyContent = content.toString(); } catch (IOException e) { throw new RuntimeException(e); } final BaseChainedConfigContext config = new ChainedConfigContext(DEFAULT_CONFIG) // we need to unset the key path in case one exists at ~/.ssh/id_rsa // see the static initializer in DefaultsConfigContext .setMantaKeyPath(null).setPrivateKeyContent(keyContent) .setMantaKeyId(KeyFingerprinter.md5Fingerprint(keyPair)); if (passphrase != null) { config.setPassword(passphrase); } return new ImmutablePair<>(keyPair, config); }
From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java
/** * Generate a 2048 bit RSA KeyPair./*ww w . jav a2 s . c o m*/ * * @param algorithm the algorithm to use * @param bits the length of the key (modulus) in bits * * @return the KeyPair * * @exception NoSuchAlgorithmException if no KeyPairGenerator is available * for the requested algorithm */ private static KeyPair generateKeyPair() throws NoSuchAlgorithmException { KeyPair kp = null; KeyPairGenerator generator; generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); kp = generator.generateKeyPair(); return kp; }
From source file:cybervillains.ca.KeyStoreManager.java
@SuppressWarnings("unchecked") public KeyStoreManager(File root) { this.root = root; Security.insertProviderAt(new BouncyCastleProvider(), 2); _sr = new SecureRandom(); try {//from ww w. j av a 2s.co m _rsaKpg = KeyPairGenerator.getInstance(RSA_KEYGEN_ALGO); _dsaKpg = KeyPairGenerator.getInstance(DSA_KEYGEN_ALGO); } catch (Throwable t) { throw new Error(t); } try { File privKeys = new File(root, KEYMAP_SER_FILE); if (!privKeys.exists()) { _rememberedPrivateKeys = new HashMap<PublicKey, PrivateKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(privKeys)); // Deserialize the object _rememberedPrivateKeys = (HashMap<PublicKey, PrivateKey>) in.readObject(); in.close(); } File pubKeys = new File(root, PUB_KEYMAP_SER_FILE); if (!pubKeys.exists()) { _mappedPublicKeys = new HashMap<PublicKey, PublicKey>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(pubKeys)); // Deserialize the object _mappedPublicKeys = (HashMap<PublicKey, PublicKey>) in.readObject(); in.close(); } } catch (FileNotFoundException e) { // check for file exists, won't happen. e.printStackTrace(); } catch (IOException e) { // we could correct, but this probably indicates a corruption // of the serialized file that we want to know about; likely // synchronization problems during serialization. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // serious problem. e.printStackTrace(); throw new Error(e); } _rsaKpg.initialize(1024, _sr); _dsaKpg.initialize(1024, _sr); try { _ks = KeyStore.getInstance("JKS"); reloadKeystore(); } catch (FileNotFoundException fnfe) { try { createKeystore(); } catch (Exception e) { throw new Error(e); } } catch (Exception e) { throw new Error(e); } try { File file = new File(root, CERTMAP_SER_FILE); if (!file.exists()) { _certMap = new HashMap<String, String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _certMap = (HashMap<String, String>) in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } try { File file = new File(root, SUBJMAP_SER_FILE); if (!file.exists()) { _subjectMap = new HashMap<String, String>(); } else { ObjectInputStream in = new ObjectInputStream(new FileInputStream(file)); // Deserialize the object _subjectMap = (HashMap<String, String>) in.readObject(); in.close(); } } catch (FileNotFoundException e) { // won't happen, check file.exists() e.printStackTrace(); } catch (IOException e) { // corrupted file, we want to know. e.printStackTrace(); throw new Error(e); } catch (ClassNotFoundException e) { // something very wrong, exit e.printStackTrace(); throw new Error(e); } }