List of usage examples for java.security SecureRandom getInstance
public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.virtual.VirtualHardwareManager.java
private int getRandom(int max, int min, int current, boolean isSmoothed, int svf) { if (isSmoothed) { int offset = (max - min) * svf / 100; double mx = current + offset; max = (mx > max) ? max : (int) Math.round(mx); double mn = current - offset; min = (mn < min) ? min : (int) Math.round(mn); }/*from w w w . ja v a2s. c om*/ try { SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); return secureRandom.nextInt(max - min) + min; } catch (NoSuchAlgorithmException e) { throw new RuntimeException("SHA1PRNG algorithm could not be found."); } }
From source file:org.vasanti.controller.ImageUploader.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// ww w. j av a2s.c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @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) { status = false; String error = "Listing Id is empty"; files.put("status", status); files.put("error", error); } } 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) { // Update the error status since file name is null status = false; String error = "Image name is empty "; files.put("status", status); files.put("error", error); } 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, Scalr.Method.QUALITY, Scalr.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); InsertImageInterface insert = new InsertImageInterface(); count = insert.InsertImage(images); if (count > 0) { status = true; files.put("status", status); files.put("count", count); } logger.info(files.toString()); } } } catch (FileUploadException ex) { try { logger.error("Got the FileUpload Exception", ex); String error = "Some error has occurred"; files.put("error", error); } catch (JSONException ex1) { logger.error("Got the JsonException", ex1); } } 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:eap.util.EDcodeUtil.java
private static byte[] des(byte[] data, byte[] key, int opMode) { try {/*w w w . j a v a 2 s . c o m*/ DESKeySpec desKey = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES", provider); SecretKey secureKey = keyFactory.generateSecret(desKey); Cipher cipher = Cipher.getInstance("DES", provider); // SecureRandom secureRandom = new SecureRandom(); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); // provider cipher.init(opMode, secureKey, secureRandom); return cipher.doFinal(data); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } }
From source file:com.tremolosecurity.saml.Saml2Assertion.java
public Saml2Assertion(String subject, PrivateKey key, X509Certificate cert, X509Certificate encCert, String issuer, String recepient, String audience, boolean signAssertion, boolean signResponse, boolean encAssertion, String nameIDFormat, String authnContextRef) { this.subject = subject; this.sigKey = key; this.sigCert = cert; this.encCert = encCert; long now = System.currentTimeMillis(); this.notBefore = (new DateTime(now - (5 * 60 * 1000))).withZone(DateTimeZone.UTC); this.notAfter = (new DateTime(now + (5 * 60 * 1000))).withZone(DateTimeZone.UTC); this.attribs = new ArrayList<Attribute>(); this.issueInstant = (new DateTime()).withZone(DateTimeZone.UTC); this.issuer = issuer; this.recepient = recepient; this.audience = audience; this.signAssertion = signAssertion; this.signResponse = signResponse; this.encAssertion = encAssertion; this.nameIDFormat = nameIDFormat; this.authnContextRef = authnContextRef; try {/* w w w . j a va2 s . c om*/ this.random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } }
From source file:org.apache.abdera.ext.oauth.OAuthScheme.java
private String generateNonce() throws AuthenticationException { try {/* w w w. j av a 2 s. co m*/ SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); byte[] temp = new byte[NONCE_LENGTH]; sr.nextBytes(temp); String n = new String(Hex.encodeHex(temp)); return n; } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } }
From source file:com.qut.middleware.spep.authn.bindings.impl.ArtifactProcessorImpl.java
public void afterPropertiesSet() { if (this.entityIdentifier == null || this.sourceID == null) { throw new IllegalArgumentException("ESOE identifier has not been specified correctly."); }//from www . ja va 2s.com if (this.identifierGenerator == null) { throw new IllegalArgumentException("Identifier generator has not been specified correctly."); } if (this.nodeIndex == -1) { throw new IllegalArgumentException("Node index has not been specified correctly."); } try { this.random = SecureRandom.getInstance(this.RNG); this.random.setSeed(System.currentTimeMillis()); String packages = ArtifactResolve.class.getPackage().getName(); String[] schema = new String[] { SchemaConstants.samlProtocol }; this.artifactResponseMarshaller = new MarshallerImpl<ArtifactResponse>(packages, schema, this.keystoreResolver); this.artifactResponseUnmarshaller = new UnmarshallerImpl<ArtifactResponse>(packages, schema, this.metadataProcessor); this.artifactResolveMarshaller = new MarshallerImpl<ArtifactResolve>(packages, schema, this.keystoreResolver); this.artifactResolveUnmarshaller = new UnmarshallerImpl<ArtifactResolve>(packages, schema, this.metadataProcessor); this.artifactMap = new ConcurrentHashMap<String, Artifact>(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException( "No such algorithm exists for the PRNG. Unable to continue. Error: " + e.getMessage(), e); } catch (MarshallerException e) { throw new IllegalArgumentException( "Error initializing marshaller. Unable to continue. Error: " + e.getMessage(), e); } catch (UnmarshallerException e) { throw new IllegalArgumentException( "Error intitializing unmarshaller. Unable to continue. Error: " + e.getMessage(), e); } }
From source file:org.globusonline.nexus.GlobusOnlineRestClient.java
private long generateNonce() { SecureRandom sr = null;//from w w w.ja v a 2s . com try { sr = SecureRandom.getInstance("SHA1PRNG"); byte[] bytes = new byte[1024 / 8]; sr.nextBytes(bytes); int seedByteCount = 10; byte[] seed = sr.generateSeed(seedByteCount); sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sr.nextLong(); }
From source file:com.qut.middleware.esoe.sso.plugins.artifact.impl.ArtifactProcessorImpl.java
public void afterPropertiesSet() { if (this.entityIdentifier == null || this.sourceID == null) { throw new IllegalArgumentException("ESOE identifier has not been specified correctly."); }// w w w. j a v a2 s . com if (this.identifierGenerator == null) { throw new IllegalArgumentException("Identifier generator has not been specified correctly."); } if (this.nodeIndex == -1) { throw new IllegalArgumentException("Node index has not been specified correctly."); } try { this.random = SecureRandom.getInstance(this.RNG); this.random.setSeed(System.currentTimeMillis()); String packages = ArtifactResolve.class.getPackage().getName(); String[] schema = new String[] { SchemaConstants.samlProtocol }; this.artifactResponseMarshaller = new MarshallerImpl<ArtifactResponse>(packages, schema, this.keystoreResolver); this.artifactResponseUnmarshaller = new UnmarshallerImpl<ArtifactResponse>(packages, schema, this.metadataProcessor); this.artifactResolveMarshaller = new MarshallerImpl<ArtifactResolve>(packages, schema, this.keystoreResolver); this.artifactResolveUnmarshaller = new UnmarshallerImpl<ArtifactResolve>(packages, schema, this.metadataProcessor); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException( "No such algorithm exists for the PRNG. Unable to continue. Error: " + e.getMessage(), e); } catch (MarshallerException e) { throw new IllegalArgumentException( "Error initializing marshaller. Unable to continue. Error: " + e.getMessage(), e); } catch (UnmarshallerException e) { throw new IllegalArgumentException( "Error intitializing unmarshaller. Unable to continue. Error: " + e.getMessage(), e); } }
From source file:wssec.TestWSSecurityNewSCT.java
public void testSCTKDKTSign() { try {/*from w w w. ja va2s . c o m*/ 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); String tokenId = sctBuilder.getSctId(); // Derived key signature WSSecDKSign sigBuilder = new WSSecDKSign(); sigBuilder.setExternalKey(tempSecret, tokenId); sigBuilder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1); sigBuilder.build(doc, secHeader); sctBuilder.prependSCTElementToHeader(doc, secHeader); if (LOG.isDebugEnabled()) { 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.globus.gsi.jsse.SSLConfigurator.java
private SecureRandom loadSecureRandom() throws GlobusSSLConfigurationException { try {//ww w.j a va2 s.c om return secureRandomAlgorithm == null ? null : SecureRandom.getInstance(secureRandomAlgorithm); } catch (NoSuchAlgorithmException e) { throw new GlobusSSLConfigurationException(e); } }