List of usage examples for java.security SecureRandom getInstance
public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:eap.util.EDcodeUtil.java
private static byte[] aes(byte[] data, byte[] key, int keyLen, int opMode) { try {/*from ww w . j ava 2s .c o m*/ KeyGenerator kgen = KeyGenerator.getInstance("AES", provider); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); // provider secureRandom.setSeed(key); kgen.init(keyLen, secureRandom); SecretKey secretKey = kgen.generateKey(); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES"); /* mode: ECB/CBC/PCBC/CTR/CTS/CFB/CFB8 to CFB128/OFB/OBF8 to OFB128<br/> * padding: Nopadding/PKCS5Padding/ISO10126Padding */ Cipher cipher = Cipher.getInstance("AES", provider); // ECB/PKCS5Padding cipher.init(opMode, keySpec); return cipher.doFinal(data); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } // // we're using Bouncy Castle // Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()) // // // create our key specification // val secretKeySpec = new SecretKeySpec(hexStringToByteArray(hexEncodedKey), "AES") // // // create an AES engine in CTR mode (no padding) // val aes = Cipher.getInstance("AES/CTR/NoPadding", BouncyCastleProvider.PROVIDER_NAME) // // // initialize the AES engine in encrypt mode with the key and IV // aes.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(hexStringToByteArray(hexEncodedIv))) // // // encrypt the message and return the encrypted byte array // aes.doFinal(hexStringToByteArray(hexEncodedMessage)) }
From source file:net.lightbody.bmp.proxy.jetty.http.SunJsseListener.java
protected SSLServerSocketFactory createFactory() throws Exception { _keystore = System.getProperty(KEYSTORE_PROPERTY, _keystore); log.info(KEYSTORE_PROPERTY + "=" + _keystore); if (_password == null) _password = Password.getPassword(PASSWORD_PROPERTY, null, null); log.info(PASSWORD_PROPERTY + "=" + _password.toStarString()); if (_keypassword == null) _keypassword = Password.getPassword(KEYPASSWORD_PROPERTY, null, _password.toString()); log.info(KEYPASSWORD_PROPERTY + "=" + _keypassword.toStarString()); KeyStore ks = null;/*from w ww.ja v a 2 s. c o m*/ log.info(KEYSTORE_TYPE_PROPERTY + "=" + _keystore_type); if (_keystore_provider_class != null) { // find provider. // avoid creating another instance if already installed in Security. java.security.Provider[] installed_providers = Security.getProviders(); java.security.Provider myprovider = null; for (int i = 0; i < installed_providers.length; i++) { if (installed_providers[i].getClass().getName().equals(_keystore_provider_class)) { myprovider = installed_providers[i]; break; } } if (myprovider == null) { // not installed yet, create instance and add it myprovider = (java.security.Provider) Class.forName(_keystore_provider_class).newInstance(); Security.addProvider(myprovider); } log.info(KEYSTORE_PROVIDER_CLASS_PROPERTY + "=" + _keystore_provider_class); ks = KeyStore.getInstance(_keystore_type, myprovider.getName()); } else if (_keystore_provider_name != null) { log.info(KEYSTORE_PROVIDER_NAME_PROPERTY + "=" + _keystore_provider_name); ks = KeyStore.getInstance(_keystore_type, _keystore_provider_name); } else { ks = KeyStore.getInstance(_keystore_type); log.info(KEYSTORE_PROVIDER_NAME_PROPERTY + "=[DEFAULT]"); } ks.load(new FileInputStream(new File(_keystore)), _password.toString().toCharArray()); KeyManagerFactory km = KeyManagerFactory.getInstance("SunX509", "SunJSSE"); km.init(ks, _keypassword.toString().toCharArray()); KeyManager[] kma = km.getKeyManagers(); TrustManagerFactory tm = TrustManagerFactory.getInstance("SunX509", "SunJSSE"); if (_useDefaultTrustStore) { tm.init((KeyStore) null); } else { tm.init(ks); } TrustManager[] tma = tm.getTrustManagers(); SSLContext sslc = SSLContext.getInstance("SSL"); sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG")); SSLServerSocketFactory ssfc = sslc.getServerSocketFactory(); log.info("SSLServerSocketFactory=" + ssfc); return ssfc; }
From source file:wssec.TestWSSecurityNewSCT.java
/** * Test for WSS-217:/*from w w w .java 2s . c om*/ * "Add ability to specify a reference to an absolute URI in the derived key functionality". */ public void testSCTKDKTSignAbsolute() { try { SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope(); Document doc = unsignedEnvelope.getAsDocument(); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); WSSecSecurityContextToken sctBuilder = new WSSecSecurityContextToken(); sctBuilder.prepare(doc, crypto); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] tempSecret = new byte[16]; random.nextBytes(tempSecret); // Store the secret this.secrets.put(sctBuilder.getIdentifier(), tempSecret); // Derived key signature WSSecDKSign sigBuilder = new WSSecDKSign(); sigBuilder.setExternalKey(tempSecret, sctBuilder.getIdentifier()); sigBuilder.setTokenIdDirectId(true); sigBuilder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1); sigBuilder.build(doc, secHeader); sctBuilder.prependSCTElementToHeader(doc, secHeader); if (LOG.isDebugEnabled()) { LOG.debug("DKT Absolute"); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc); LOG.debug(outputString); } verify(doc); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:org.vasanti.controller.DropZoneFileUpload.java
/** * @param request// ww w .j av a 2 s.co m * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) * */ @SuppressWarnings("unchecked") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); String path = ""; if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } bnimagesbn images = new bnimagesbn(); ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); response.setContentType("application/json"); JSONObject files = new JSONObject(); try { List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { FileItem colpostid = (FileItem) items.get(0); String COLPOSTID = colpostid.getString(); if (COLPOSTID != null) { images.setCOLPOSTID(COLPOSTID); logger.info("COLPOSTID from View is = " + COLPOSTID); } else if (COLPOSTID == null) { RequestDispatcher rd = request .getRequestDispatcher("/WEB-INF/views/services/error-page.jsp"); rd.forward(request, response); } } else if (!item.isFormField()) { String ImageName = ""; String name = item.getName(); String contentType = item.getContentType(); logger.info("Content Type of file is " + contentType); long size = item.getSize(); logger.info("Size of file is " + size); String filetype = name.substring(name.lastIndexOf(".")); SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); String randomNum = Integer.toString(prng.nextInt()); MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] result = sha.digest(randomNum.getBytes()); ImageName = hexEncode(result) + filetype; logger.info(" ImageName1 is " + ImageName); if (name != null) { if ((size < 9048576) && (("image/jpeg".equals(contentType)) || ("image/jpg".equals(contentType)) || ("image/gif".equals(contentType)) || ("image/png".equals(contentType)) || ("image/bmp".equals(contentType)))) { images.setCOLIMAGENAME(ImageName); } } else if (name == null) { RequestDispatcher rd = request .getRequestDispatcher("/WEB-INF/views/adultservices/error-page.jsp"); rd.forward(request, response); } File file = new File(ImagefileUploadPath, ImageName); item.write(file); path = file.getCanonicalPath(); logger.info(" ImageName1 CanonicalPath is " + path); BufferedImage img = null; try { img = ImageIO.read((new File(path))); } catch (IOException ex) { logger.error("Logging IO Exception while creating thumbnail", ex); } BufferedImage thumbImg = Scalr.resize(img, Method.QUALITY, Mode.AUTOMATIC, 150, 150, Scalr.OP_ANTIALIAS); File thumbnailfile = new File(ThumbnailFileUploadPath, ImageName); images.setCOLTHUMBNAILNAME(ImageName); ImageIO.write(thumbImg, "jpg", thumbnailfile); files.put("name", ImageName); // jsono.put("size", item.getSize()); // jsono.put("url", "UploadServlet?getfile=" + ImageName); // jsono.put("thumbnail_url", "UploadServlet?getthumb=" + ImageName); // jsono.put("delete_url", "UploadServlet?delfile=" + ImageName); // jsono.put("delete_type", "GET"); InsertImageInterface insert = new InsertImageInterface(); count = insert.InsertImage(images); files.put("status", status); logger.info(files.toString()); } } } catch (FileUploadException ex) { logger.error("Got the FileUpload Exception", ex); } catch (Exception ex) { logger.error("Got the Exception", ex); } finally { try { files.put("status", status); writer.write(files.toString()); writer.close(); } catch (JSONException ex) { logger.error("Got the JSONException", ex); } } }
From source file:com.google.gerrit.httpd.auth.oauth.OAuthSession.java
private static SecureRandom newRandomGenerator() { try {/* w w w .ja va 2 s . c om*/ return SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("No SecureRandom available for GitHub authentication", e); } }
From source file:com.autentia.tnt.manager.security.AuthenticationManager.java
/** * Generate a new random password/* www . j a v a2 s . com*/ * * @return a new random password */ private String generateRandomPassword(String[] rnd0, String[] rnd1, String[] rnd2, String[] rnd3, String[] rnd4) { StringBuilder ret = new StringBuilder(); // Get lists of random words. We could cache these, but this method is // rarely called and caching would // depend on user locale, so we prefer to waste CPU better than memory. // Get a true random number generator SecureRandom rnd; try { rnd = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException ex) { rnd = new SecureRandom(); } // Generate random numbers int i0 = rnd.nextInt(rnd0.length); int i1 = rnd.nextInt(rnd1.length); int i2 = rnd.nextInt(rnd2.length); int i3 = rnd.nextInt(rnd3.length); int i4 = rnd.nextInt(rnd4.length); // Compose password ret.append(rnd0[i0]); ret.append(rnd1[i1]); ret.append(rnd2[i2]); ret.append(rnd3[i3]); ret.append(rnd4[i4]); return ret.toString(); }
From source file:org.apache.rahas.impl.util.SAMLUtilsTest.java
private static byte[] generateEphemeralKey(int keySize) throws TrustException { try {//from w w w . ja v a2s . c o m SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] temp = new byte[keySize / 8]; random.nextBytes(temp); return temp; } catch (Exception e) { throw new TrustException("errorCreatingSymmKey", e); } }
From source file:org.vasanti.controller.UploadServlet.java
/** * @param request//from w ww.ja v a2s . c o m * @param response * @throws javax.servlet.ServletException * @throws java.io.IOException * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) * */ @SuppressWarnings("unchecked") @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); String path = ""; if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } bnimagesbn images = new bnimagesbn(); ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); response.setContentType("application/json"); JSONArray json = new JSONArray(); JSONObject files = new JSONObject(); try { List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { FileItem colpostid = (FileItem) items.get(0); String COLPOSTID = colpostid.getString(); if (COLPOSTID != null) { images.setCOLPOSTID(COLPOSTID); logger.info("COLPOSTID from View is = " + COLPOSTID); } else if (COLPOSTID == null) { RequestDispatcher rd = request .getRequestDispatcher("/WEB-INF/views/services/error-page.jsp"); rd.forward(request, response); } } else if (!item.isFormField()) { String ImageName = ""; String name = item.getName(); String contentType = item.getContentType(); logger.info("Content Type of file is", contentType); long size = item.getSize(); logger.info("Size of file is", size); String filetype = name.substring(name.lastIndexOf(".")); SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); String randomNum = Integer.toString(prng.nextInt()); MessageDigest sha = MessageDigest.getInstance("SHA-1"); byte[] result = sha.digest(randomNum.getBytes()); ImageName = hexEncode(result) + filetype; logger.info(" ImageName1 is " + ImageName); if (name != null) { if ((size < 9048576) && (("image/jpeg".equals(contentType)) || ("image/jpg".equals(contentType)) || ("image/gif".equals(contentType)) || ("image/png".equals(contentType)) || ("image/bmp".equals(contentType)))) { images.setCOLIMAGENAME(ImageName); } } else if (name == null) { RequestDispatcher rd = request .getRequestDispatcher("/WEB-INF/views/adultservices/error-page.jsp"); rd.forward(request, response); } File file = new File(ImagefileUploadPath, ImageName); item.write(file); path = file.getCanonicalPath(); logger.info(" ImageName1 CanonicalPath is " + path); BufferedImage img = null; try { img = ImageIO.read((new File(path))); } catch (IOException ex) { logger.error("Logging IO Exception while creating thumbnail", ex); } BufferedImage thumbImg = Scalr.resize(img, Method.QUALITY, Mode.AUTOMATIC, 150, 150, Scalr.OP_ANTIALIAS); File thumbnailfile = new File(ThumbnailFileUploadPath, ImageName); images.setCOLTHUMBNAILNAME(ImageName); ImageIO.write(thumbImg, "jpg", thumbnailfile); JSONObject jsono = new JSONObject(); jsono.put("name", ImageName); jsono.put("size", item.getSize()); jsono.put("url", "UploadServlet?getfile=" + ImageName); jsono.put("thumbnail_url", "UploadServlet?getthumb=" + ImageName); jsono.put("delete_url", "UploadServlet?delfile=" + ImageName); jsono.put("delete_type", "GET"); json.put(jsono); InsertImageInterface insert = new InsertImageInterface(); insert.InsertImage(images); files.put("files", json); logger.info(json.toString()); } } } catch (FileUploadException ex) { logger.error("Got the FileUpload Exception", ex); } catch (Exception ex) { logger.error("Got the Exception", ex); } finally { writer.write(json.toString()); writer.close(); } }
From source file:com.erudika.para.utils.Utils.java
/** * Generates an authentication token - a random string encoded in Base64. * @param length the length of the generated token * @param urlSafe switches to a URL safe encoding * @return a random string//w w w . j a v a 2 s . co m */ public static String generateSecurityToken(int length, boolean urlSafe) { final byte[] bytes = new byte[length]; SecureRandom rand; try { rand = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException ex) { logger.error(null, ex); rand = new SecureRandom(); } rand.nextBytes(bytes); return urlSafe ? base64encURL(bytes) : base64enc(bytes); }
From source file:org.wso2.carbon.identity.core.util.IdentityUtil.java
public static int getRandomInteger() throws IdentityException { try {//from ww w . j a v a2 s. c o m SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); int number = prng.nextInt(); while (number < 0) { number = prng.nextInt(); } return number; } catch (NoSuchAlgorithmException e) { log.error("Error when generating a random number.", e); throw new IdentityException("Error when generating a random number.", e); } }