Example usage for java.security SecureRandom nextBytes

List of usage examples for java.security SecureRandom nextBytes

Introduction

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

Prototype

@Override
public void nextBytes(byte[] bytes) 

Source Link

Document

Generates a user-specified number of random bytes.

Usage

From source file:com.zimbra.cs.account.TrustedTokenKey.java

TrustedTokenKey(long version, byte[] key) throws ServiceException {
    mVersion = version;// ww  w . j av  a  2 s .  com
    mCreated = System.currentTimeMillis();
    if (key != null) {
        mKey = key;
    } else {
        SecureRandom random = new SecureRandom();
        mKey = new byte[KEY_SIZE_BYTES];
        random.nextBytes(mKey);
    }
}

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//  w  ww  .java2s.  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.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void exportIdPMetadata(Options options, CommandLine cmd, TremoloType tt, KeyStore ks)
        throws Exception, KeyStoreException, CertificateEncodingException, NoSuchAlgorithmException,
        UnrecoverableKeyException, SecurityException, MarshallingException, SignatureException {

    InitializationService.initialize();/*from   www  .  ja v a2s  .  c o m*/

    logger.info("Finding IdP...");
    String idpName = loadOption(cmd, "idpName", options);

    ApplicationType idp = null;

    for (ApplicationType app : tt.getApplications().getApplication()) {
        if (app.getName().equalsIgnoreCase(idpName)) {
            idp = app;
        }
    }

    if (idp == null) {
        throw new Exception("IdP '" + idpName + "' not found");
    }

    logger.info("Loading the base URL");
    String baseURL = loadOption(cmd, "urlBase", options);

    String url = baseURL + idp.getUrls().getUrl().get(0).getUri();

    SecureRandom random = new SecureRandom();
    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    StringBuffer b = new StringBuffer();
    b.append('f').append(Hex.encodeHexString(idBytes));
    String id = b.toString();

    EntityDescriptorBuilder edb = new EntityDescriptorBuilder();
    EntityDescriptor ed = edb.buildObject();
    ed.setID(id);
    ed.setEntityID(url);

    IDPSSODescriptorBuilder idpssdb = new IDPSSODescriptorBuilder();
    IDPSSODescriptor sd = idpssdb.buildObject();//ed.getSPSSODescriptor("urn:oasis:names:tc:SAML:2.0:protocol");
    sd.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol");
    ed.getRoleDescriptors().add(sd);

    HashMap<String, List<String>> params = new HashMap<String, List<String>>();
    for (ParamType pt : idp.getUrls().getUrl().get(0).getIdp().getParams()) {
        List<String> vals = params.get(pt.getName());
        if (vals == null) {
            vals = new ArrayList<String>();
            params.put(pt.getName(), vals);
        }
        vals.add(pt.getValue());
    }

    sd.setWantAuthnRequestsSigned(params.containsKey("requireSignedAuthn")
            && params.get("requireSignedAuthn").get(0).equalsIgnoreCase("true"));

    KeyDescriptorBuilder kdb = new KeyDescriptorBuilder();

    if (params.get("encKey") != null && !params.get("encKey").isEmpty()
            && (ks.getCertificate(params.get("encKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.ENCRYPTION);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("encKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);

    }

    if (params.get("sigKey") != null && !params.get("sigKey").isEmpty()
            && (ks.getCertificate(params.get("sigKey").get(0)) != null)) {
        KeyDescriptor kd = kdb.buildObject();
        kd.setUse(UsageType.SIGNING);
        KeyInfoBuilder kib = new KeyInfoBuilder();
        KeyInfo ki = kib.buildObject();

        X509DataBuilder x509b = new X509DataBuilder();
        X509Data x509 = x509b.buildObject();
        X509CertificateBuilder certb = new X509CertificateBuilder();
        org.opensaml.xmlsec.signature.X509Certificate cert = certb.buildObject();
        cert.setValue(Base64.encode(ks.getCertificate(params.get("sigKey").get(0)).getEncoded()));
        x509.getX509Certificates().add(cert);
        ki.getX509Datas().add(x509);
        kd.setKeyInfo(ki);
        sd.getKeyDescriptors().add(kd);

    }

    HashSet<String> nameids = new HashSet<String>();

    for (TrustType trustType : idp.getUrls().getUrl().get(0).getIdp().getTrusts().getTrust()) {
        for (ParamType pt : trustType.getParam()) {
            if (pt.getName().equalsIgnoreCase("nameIdMap")) {
                String val = pt.getValue().substring(0, pt.getValue().indexOf('='));
                if (!nameids.contains(val)) {
                    nameids.add(val);
                }
            }
        }
    }

    NameIDFormatBuilder nifb = new NameIDFormatBuilder();

    for (String nidf : nameids) {
        NameIDFormat nif = nifb.buildObject();
        nif.setFormat(nidf);
        sd.getNameIDFormats().add(nif);
    }

    SingleSignOnServiceBuilder ssosb = new SingleSignOnServiceBuilder();
    SingleSignOnService sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
    sso.setLocation(url + "/httpPost");
    sd.getSingleSignOnServices().add(sso);

    sso = ssosb.buildObject();
    sso.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect");
    sso.setLocation(url + "/httpRedirect");
    sd.getSingleSignOnServices().add(sso);

    String signingKey = loadOptional(cmd, "signMetadataWithKey", options);

    if (signingKey != null && ks.getCertificate(signingKey) != null) {
        BasicX509Credential signingCredential = new BasicX509Credential(
                (X509Certificate) ks.getCertificate(signingKey),
                (PrivateKey) ks.getKey(signingKey, tt.getKeyStorePassword().toCharArray()));

        Signature signature = OpenSAMLUtils.buildSAMLObject(Signature.class);

        signature.setSigningCredential(signingCredential);
        signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

        ed.setSignature(signature);
        try {
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(ed).marshall(ed);
        } catch (MarshallingException e) {
            throw new RuntimeException(e);
        }
        Signer.signObject(signature);
    }

    // Get the Subject marshaller
    EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();

    // Marshall the Subject
    Element assertionElement = marshaller.marshall(ed);

    logger.info(net.shibboleth.utilities.java.support.xml.SerializeSupport.nodeToString(assertionElement));
}

From source file:com.zimbra.cs.account.ExtAuthTokenKey.java

ExtAuthTokenKey(long version, byte[] key) throws ServiceException {
    this.version = version;
    created = System.currentTimeMillis();
    if (key != null) {
        this.key = key;
    } else {/*w  w w . j a v a 2 s .c  o m*/
        SecureRandom random = new SecureRandom();
        this.key = new byte[KEY_SIZE_BYTES];
        random.nextBytes(this.key);
    }
}

From source file:com.zimbra.cs.account.AuthTokenKey.java

AuthTokenKey(long version, byte[] key) throws ServiceException {
    mVersion = version;/*from   ww  w .  j a v  a  2 s.  c o m*/
    mCreated = System.currentTimeMillis();
    if (key != null) {
        mKey = key;
    } else {
        SecureRandom random = new SecureRandom();
        mKey = new byte[KEY_SIZE_BYTES];
        random.nextBytes(mKey);
    }
}

From source file:de.petendi.commons.crypto.HybridCrypto.java

private synchronized void createSymmetricPassphrase() {
    if (symmetricKey == null) {
        symmetricKey = securityProviderConnector.generateSecretKey();
        SecureRandom randomSecureRandom = new SecureRandom();
        iv = new byte[16];
        randomSecureRandom.nextBytes(iv);
        byte[] encodedKey = symmetricKey.getEncoded();
        concatenated = new byte[iv.length + encodedKey.length];
        System.arraycopy(iv, 0, concatenated, 0, iv.length);
        System.arraycopy(encodedKey, 0, concatenated, iv.length, encodedKey.length);
    }//  w w  w .  ja  v a2 s . c  o  m
}

From source file:org.orcid.core.manager.impl.InternalSSOManagerImpl.java

private String generateAndStoreToken(String orcid) {
    // Generate a random token
    SecureRandom random = new SecureRandom();
    byte[] bytes = new byte[16];
    random.nextBytes(bytes);
    byte[] encoded = Base64.encodeBase64(bytes);
    String token = new String(encoded);

    // Insert it into the DB
    internalSSODao.insert(orcid, token);
    return token;
}

From source file:com.zimbra.cs.account.CsrfTokenKey.java

/**
 * @param version//from w w  w.ja v a  2s.  c o  m
 * @param key
 * @throws ServiceException
 */
CsrfTokenKey(long version, byte[] key) throws ServiceException {
    keyVersion = version;
    keyCreatedAt = System.currentTimeMillis();
    if (key != null) {
        csrfTokenKey = key;
    } else {
        SecureRandom random = new SecureRandom();
        csrfTokenKey = new byte[KEY_SIZE_BYTES];
        random.nextBytes(csrfTokenKey);
    }
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML1ArtifactResolutionTest.java

@SuppressWarnings("unchecked")
protected SAMLArtifactMapEntry stageArtifact(String relyingPartyId) throws Exception {
    SAMLObjectBuilder<Assertion> assetionBuilder = (SAMLObjectBuilder<Assertion>) builderFactory
            .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
    Assertion assertion = assetionBuilder.buildObject();

    SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
    byte[] assertionHandle = new byte[20];
    handleGenerator.nextBytes(assertionHandle);
    SAML1ArtifactType0002 artifact = new SAML1ArtifactType0002(assertionHandle, relyingPartyId);

    SAMLArtifactMap artifactMap = (SAMLArtifactMap) getApplicationContext().getBean("shibboleth.ArtifactMap");
    artifactMap.put(artifact.base64Encode(), relyingPartyId, "urn:example.org:idp1", assertion);
    return artifactMap.get(artifact.base64Encode());
}

From source file:org.brekka.phalanx.core.services.impl.PhalanxSessionServiceImpl.java

@Override
public byte[] allocateAndBind(AuthenticatedPrincipal authenticatedPrincipal) {
    SecureRandom secureRandom = randomCryptoService.getSecureRandom();
    byte[] keyBytes = new byte[SESSION_ID_LENGTH];
    secureRandom.nextBytes(keyBytes);
    CacheKey key = new CacheKey(keyBytes);
    PrincipalSession principalSession = new PrincipalSession(authenticatedPrincipal);
    cache.put(key, principalSession);/*  w  w w.j av a2  s .  com*/
    context.set(principalSession);
    return keyBytes;
}