List of usage examples for java.security KeyPairGenerator genKeyPair
public final KeyPair genKeyPair()
From source file:org.owasp.benchmark.testcode.BenchmarkTest02152.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = request.getParameter("vector"); if (param == null) param = ""; String bar = doSomething(param); // Code based on example from: // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/ try {/*from w w w.jav a 2 s .c o m*/ javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE"); // Prepare the cipher to encrypt java.security.KeyPairGenerator keyGen = java.security.KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); java.security.PublicKey publicKey = keyGen.genKeyPair().getPublic(); c.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey); // encrypt and store the results byte[] input = { (byte) '?' }; Object inputParam = bar; if (inputParam instanceof String) input = ((String) inputParam).getBytes(); if (inputParam instanceof java.io.InputStream) { byte[] strInput = new byte[1000]; int i = ((java.io.InputStream) inputParam).read(strInput); if (i == -1) { response.getWriter().println( "This input source requires a POST, not a GET. Incompatible UI for the InputStream source."); return; } input = java.util.Arrays.copyOf(strInput, i); } byte[] result = c.doFinal(input); java.io.File fileTarget = new java.io.File( new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), "passwordFile.txt"); java.io.FileWriter fw = new java.io.FileWriter(fileTarget, true); //the true will append the new data fw.write("secret_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n"); fw.close(); response.getWriter() .println("Sensitive value: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' encrypted and stored<br/>"); } catch (java.security.NoSuchAlgorithmException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (java.security.NoSuchProviderException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.NoSuchPaddingException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.IllegalBlockSizeException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.BadPaddingException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (java.security.InvalidKeyException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } response.getWriter() .println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed"); }
From source file:com.xinferin.licensing.LicenceGenerator.java
/** * Creates a new private and public key and at the same time encodes the public key as XML to be used by the .NET client * @param size//from w w w . j a v a 2 s. com * @param productId * */ private void firstTimeInitialisation(int size) { try { // Get Key Pair Generator for RSA. KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(size); KeyPair keypair = keyGen.genKeyPair(); privateKey = keypair.getPrivate(); publicKey = keypair.getPublic(); // Get the bytes of the public and private keys byte[] privateKeyBytes = privateKey.getEncoded(); byte[] publicKeyBytes = publicKey.getEncoded(); // store temporarily witht he public key for the lifetime of this class. encodedPrivateKey = new Base64().encode(privateKeyBytes); // Generate the Private Key, Public Key and Public Key in XML format. KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes)); RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA") .generatePublic(new X509EncodedKeySpec(publicKeyBytes)); // Store the public key in XML string to make compatible .Net public key file encodedToXMLPublicKey = getRSAPublicKeyAsXMLString(rsaPublicKey); } catch (Exception ex) { System.out.println(ex.getMessage()); } }
From source file:cloud.google.com.windows.example.ExampleCode.java
private KeyPair generateKeys() throws NoSuchAlgorithmException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); // Key moduli for encryption/decryption are 2048 bits long. keyGen.initialize(2048);/*from ww w . ja v a 2 s .c om*/ return keyGen.genKeyPair(); }
From source file:org.owasp.benchmark.testcode.BenchmarkTest01139.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String param = ""; boolean flag = true; java.util.Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements() && flag) { String name = (String) names.nextElement(); java.util.Enumeration<String> values = request.getHeaders(name); if (values != null) { while (values.hasMoreElements() && flag) { String value = (String) values.nextElement(); if (value.equals("vector")) { param = name;/*from w w w . j a v a 2 s . co m*/ flag = false; } } } } String bar = new Test().doSomething(param); // Code based on example from: // http://examples.javacodegeeks.com/core-java/crypto/encrypt-decrypt-file-stream-with-des/ try { javax.crypto.Cipher c = javax.crypto.Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE"); // Prepare the cipher to encrypt java.security.KeyPairGenerator keyGen = java.security.KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024); java.security.PublicKey publicKey = keyGen.genKeyPair().getPublic(); c.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey); // encrypt and store the results byte[] input = { (byte) '?' }; Object inputParam = bar; if (inputParam instanceof String) input = ((String) inputParam).getBytes(); if (inputParam instanceof java.io.InputStream) { byte[] strInput = new byte[1000]; int i = ((java.io.InputStream) inputParam).read(strInput); if (i == -1) { response.getWriter().println( "This input source requires a POST, not a GET. Incompatible UI for the InputStream source."); return; } input = java.util.Arrays.copyOf(strInput, i); } byte[] result = c.doFinal(input); java.io.File fileTarget = new java.io.File( new java.io.File(org.owasp.benchmark.helpers.Utils.testfileDir), "passwordFile.txt"); java.io.FileWriter fw = new java.io.FileWriter(fileTarget, true); //the true will append the new data fw.write("secret_value=" + org.owasp.esapi.ESAPI.encoder().encodeForBase64(result, true) + "\n"); fw.close(); response.getWriter() .println("Sensitive value: '" + org.owasp.esapi.ESAPI.encoder().encodeForHTML(new String(input)) + "' encrypted and stored<br/>"); } catch (java.security.NoSuchAlgorithmException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (java.security.NoSuchProviderException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.NoSuchPaddingException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.IllegalBlockSizeException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (javax.crypto.BadPaddingException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } catch (java.security.InvalidKeyException e) { response.getWriter().println( "Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String,java.security.Provider) Test Case"); e.printStackTrace(response.getWriter()); throw new ServletException(e); } response.getWriter() .println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String,java.lang.String) executed"); }
From source file:com.zxy.commons.codec.rsa.AbstractRSAUtils.java
/** * ??/*w ww. j ava 2 s.com*/ * * @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.platform.signature.core.pki.CertServiceImpl.java
@Override public KeyStore initializeUser(UserInfo userInfo, String suppliedPassword) throws CertException { char[] password = suppliedPassword.toCharArray(); KeyStore ks = null;/*from w w w. j a v a2 s . c o m*/ String userName = userInfo.getUserFields().get(CNField.UserID); AliasWrapper keystoreAlias = new AliasWrapper(userName); try { ks = java.security.KeyStore.getInstance(KEYSTORE_TYPE); ks.load(null, password); KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyGen.initialize(KEY_SIZE); KeyPair keyPair = keyGen.genKeyPair(); java.security.cert.Certificate[] chain = { getRootCertificate() }; ks.setKeyEntry(keystoreAlias.getId(AliasType.KEY), keyPair.getPrivate(), password, chain); X509Certificate cert = getCertificate(keyPair, userInfo); ks.setCertificateEntry(keystoreAlias.getId(AliasType.CERT), cert); } catch (CertificateException e) { throw new CertException(e); } catch (IOException e) { throw new CertException(e); } catch (KeyStoreException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } return ks; }
From source file:com.l2jfree.loginserver.manager.GameServerManager.java
/** * Load RSA keys/* www .j av a 2s . 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: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. *///w w w .ja v a2 s. c om 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.dasein.cloud.test.identity.IdentityResources.java
/** * @link http://stackoverflow.com/a/14582408/211197 * @return Encoded generated public key//from ww w . j a va2 s . co m */ private @Nullable String generateKey() { KeyPairGenerator generator; try { generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048); KeyPair keyPair = generator.genKeyPair(); RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes().length); dos.write("ssh-rsa".getBytes()); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray())); return "ssh-rsa " + publicKeyEncoded + " dasein"; } catch (Throwable e) { return null; } }