Example usage for java.security SecureRandom getInstance

List of usage examples for java.security SecureRandom getInstance

Introduction

In this page you can find the example usage for java.security SecureRandom getInstance.

Prototype

public static SecureRandom getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.

Usage

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Instantiates a new jar delta jar patcher test.
 *//*w w w  .  jav  a2 s.c  om*/
public JarDeltaJarPatcherTest() {
    try {
        random = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
}

From source file:com.haulmont.cuba.core.sys.encryption.Sha1EncryptionModule.java

protected String generateSalt() throws NoSuchAlgorithmException {
    SecureRandom random = SecureRandom.getInstance(RANDOMIZE_ALGORITHM);
    byte[] salt = new byte[SALT_LENGTH_BYTES];
    random.nextBytes(salt);/* w  ww.  j  a  va2s .c o  m*/
    return new String(Hex.encodeHex(salt));
}

From source file:com.romeikat.datamessie.core.base.service.AuthenticationService.java

public byte[] createSalt() {
    SecureRandom sr;/* w  w w  . jav  a 2s.com*/
    try {
        sr = SecureRandom.getInstance("SHA1PRNG");
        final byte[] salt = new byte[512 / 8];
        sr.nextBytes(salt);
        return salt;
    } catch (final NoSuchAlgorithmException e) {
        LOG.error("Could not create salt", e);
        return null;
    }
}

From source file:ch.cern.security.saml2.utils.UrlUtils.java

/**
 * Generates the URL response (IdP)//w ww  . java  2 s  .  c  om
 * 
 * @param request
 * @param isDebugEnabled
 * @return The logout URL:
 *         https://login.cern.ch/adfs/ls/?SAMLResponse=value&
 *         SigAlg=value&Signature=value
 * @throws DataFormatException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws UnrecoverableKeyException
 * @throws InvalidKeyException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws SignatureException
 * @throws XMLStreamException
 */
public static String generateSamlResponse(HttpServletRequest request, boolean isDebugEnabled)
        throws DataFormatException, ParserConfigurationException, SAXException, IOException,
        UnrecoverableKeyException, InvalidKeyException, KeyStoreException, NoSuchProviderException,
        NoSuchAlgorithmException, CertificateException, SignatureException, XMLStreamException {

    // Get the request as an XML
    String xmlLogoutRequest = XMLUtils.xmlDecodeAndInflate(request.getParameter(Constants.SAML_REQUEST),
            isDebugEnabled);

    // Parse the xml request. Encapsulate the data in a SamlVO object
    SamlVO samlVO = XMLUtils.parseXMLmessage(xmlLogoutRequest, isDebugEnabled);

    // Add the destination: context-param in web.xml. This info is not in the logoutRequest
    samlVO.setDestination(
            (String) request.getSession().getServletContext().getAttribute(Constants.IDP_ENDPOINT));

    // Generates the ID
    byte[] buf = new byte[16];
    SecureRandom.getInstance(RANDOM_ALGORITHM).nextBytes(buf);
    samlVO.setId("_".concat(new String(Hex.encode(buf))));

    // Set the issueInstant
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
    samlVO.setIssueInstant(simpleDateFormat.format(new Date()));

    // Get the entityID!!!
    samlVO.setIssuer((String) request.getSession().getServletContext().getAttribute(Constants.ENTITY_ID));

    // Generate the LogoutResponse
    String samlResponse = XMLUtils.createXMLresponse(samlVO, isDebugEnabled);

    // Deflate and encode the LogoutResponse
    String base64response = XMLUtils.xmlDeflateAndEncode(samlResponse, isDebugEnabled);

    // URL-encode the deflatedResponse
    String urlEncodedresponse = URLEncoder.encode(base64response, Constants.CHARACTER_ENCODING);

    if (isDebugEnabled)
        nc.notice("Data to sign: " + Constants.SAML_RESPONSE + EQUAL + urlEncodedresponse + AMPERSAND
                + Constants.SIG_ALG + EQUAL
                + URLEncoder.encode(
                        (String) request.getSession().getServletContext().getAttribute(Constants.SIG_ALG),
                        Constants.CHARACTER_ENCODING));

    // Sign the SAMLResponse=value&SigAlg=value
    String signature = SignatureUtils.sign(
            Constants.SAML_RESPONSE + EQUAL + urlEncodedresponse + AMPERSAND + Constants.SIG_ALG + EQUAL
                    + URLEncoder.encode(
                            (String) request.getSession().getServletContext().getAttribute(Constants.SIG_ALG),
                            Constants.CHARACTER_ENCODING),
            (PrivateKey) request.getSession().getServletContext().getAttribute(Constants.SP_PRIVATE_KEY),
            (String) request.getSession().getServletContext().getAttribute(Constants.ALGORITHM),
            isDebugEnabled);

    // URL-encode the signature
    String urlEncodedSignature = URLEncoder.encode(signature, Constants.CHARACTER_ENCODING);

    if (isDebugEnabled)
        nc.notice("Final URL: "
                + (String) request.getSession().getServletContext().getAttribute(Constants.IDP_ENDPOINT)
                + QUESTION_MARK + Constants.SAML_RESPONSE + EQUAL + urlEncodedresponse + AMPERSAND
                + Constants.SIG_ALG + EQUAL
                + URLEncoder.encode(
                        (String) request.getSession().getServletContext().getAttribute(Constants.SIG_ALG),
                        Constants.CHARACTER_ENCODING)
                + AMPERSAND + SIGNATURE + EQUAL + urlEncodedSignature);

    // Constructs the final URL
    // https://endpoint/?SAMLResponse=value&SigAlg=value&Signature=value
    return (String) request.getSession().getServletContext().getAttribute(Constants.IDP_ENDPOINT)
            + QUESTION_MARK + Constants.SAML_RESPONSE + EQUAL + urlEncodedresponse + AMPERSAND
            + Constants.SIG_ALG + EQUAL
            + URLEncoder.encode(
                    (String) request.getSession().getServletContext().getAttribute(Constants.SIG_ALG),
                    Constants.CHARACTER_ENCODING)
            + AMPERSAND + SIGNATURE + EQUAL + urlEncodedSignature;
}

From source file:edu.cmu.sei.ams.cloudlet.impl.AESEncrypter.java

/**
 * Encrypts data and returns the encrypted string.
 * @param clear A byte array to encrypt.
 * @return An encrypted string.//from  w w  w .  jav a 2 s . c o  m
 * @throws EncryptionException
 */
public String encrypt(byte[] clear) throws EncryptionException {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        byte[] b = new byte[16];
        random.nextBytes(b);
        byte[] iv = b;
        //log.info("IV: " + String.valueOf(Hex.encodeHex(iv)));

        // TODO: change to CBC method with padding.
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, this.skeySpec, new IvParameterSpec(iv));

        byte[] encrypted = cipher.doFinal(clear);
        //log.info("Cipher Text: " + String.valueOf(Hex.encodeHex(encrypted)));
        String encryptedString = new String(Base64.encodeBase64(ivCipherConcat(iv, encrypted)));
        return encryptedString;
    } catch (Exception e) {
        throw new EncryptionException("Error encrypting information", e);
    }
}

From source file:com.sonicle.webtop.core.util.IdentifierUtils.java

/**
 * @deprecated use com.sonicle.commons.IdentifierUtils.getCRSFToken instead
 * @return/*from   w  w  w.ja v  a 2 s .c  o  m*/
 */
@Deprecated
public static synchronized String getCRSFToken() {
    try {
        byte[] buffer = new byte[80 / 8];
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.nextBytes(buffer);
        byte[] secretKey = Arrays.copyOf(buffer, 80 / 8);
        byte[] encodedKey = new Base32().encode(secretKey);
        return new String(encodedKey).toLowerCase();
    } catch (NoSuchAlgorithmException ex) {
        return null;
    }
}

From source file:org.noroomattheinn.utils.PWUtils.java

public byte[] generateSalt() {
    // VERY important to use SecureRandom instead of just Random
    try {/*  w ww .j  a  va2s  .  c  o  m*/
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        // Generate a 8 byte (64 bit) salt as recommended by RSA PKCS5
        byte[] salt = new byte[8];
        random.nextBytes(salt);

        return salt;

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(PWUtils.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }

}

From source file:org.wso2.carbon.identity.sso.saml.builders.SAMLArtifactBuilder.java

/**
 * Build the SAML V2.0 Artifact type of Type Code 0x0004
 * Artifact length : 44 bytes/*from  w  ww  . jav  a  2 s  . c o  m*/
 *
 * SAML V2.0 defines an artifact type of type code 0x0004
 * Identification:urn:oasis:names:tc:SAML:2.0:artifact-04
 *
 * SAML_artifact := B64(TypeCode EndpointIndex RemainingArtifact)
 * TypeCode := Byte1Byte2
 * EndpointIndex := Byte1Byte2
 *
 * TypeCode := 0x0004
 * RemainingArtifact := SourceID MessageHandle
 * SourceID := 20-byte_sequence
 * MessageHandle := 20-byte_sequence
 *
 * @return SAML V2.0 Artifact type of Type Code 0x0004
 */
private String buildSAML2Artifact() throws IdentityException, NoSuchAlgorithmException {

    if (log.isDebugEnabled()) {
        log.debug("Building Artifact");
    }
    //Endpoint Index
    byte[] endpointIndex = { 0, 0 };

    //Source ID
    MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1");
    String issuerID = SAMLSSOUtil.getIssuer().getValue();
    byte[] sourceID = sha1Digester.digest(issuerID.getBytes());

    //MessageHandle
    SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
    byte[] messageHandle;
    messageHandle = new byte[20];
    handleGenerator.nextBytes(messageHandle);

    byte[] artifactByteArray = new byte[44];
    System.arraycopy(SAMLSSOConstants.SAML2_ARTIFACT_TYPE_CODE, 0, artifactByteArray, 0, 2);
    System.arraycopy(endpointIndex, 0, artifactByteArray, 2, 2);
    System.arraycopy(sourceID, 0, artifactByteArray, 4, 20);
    System.arraycopy(messageHandle, 0, artifactByteArray, 24, 20);
    return new String(Base64.encode(artifactByteArray));
}

From source file:com.networknt.light.util.HashUtil.java

private static String getSalt() throws NoSuchAlgorithmException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    byte[] salt = new byte[16];
    sr.nextBytes(salt);/*from w  w w.  j  ava2s .  c  o  m*/
    return salt.toString();
}

From source file:com.github.mrstampy.gameboot.security.SecurityConfiguration.java

/**
 * Secure random./*from   w  w  w.j  a  va 2  s  .  c o m*/
 *
 * @return the secure random
 * @throws Exception
 *           the exception
 */
@Bean(name = GAME_BOOT_SECURE_RANDOM)
public SecureRandom secureRandom() throws Exception {
    SecureRandom random = isEmpty(algorithm) ? SecureRandom.getInstanceStrong()
            : SecureRandom.getInstance(algorithm);

    byte[] seed = new byte[seedSize];
    random.nextBytes(seed);

    return random;
}