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:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testTokenKeyDoesNotMatch() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey);
    LOG.debug("SignResponse: " + signResponse);

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            "foobar-token-key".getBytes(), null);
    session.setDestination("destination-foobar");
    session.setInResponseTo("in-response-to");
    try {//from   ww w  . j  ava  2 s. c o m
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (SecurityException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
        assertFalse(session.isSignResponseVerified());
    }
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testUserCancel() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey, DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR,
            DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR, null);
    LOG.debug("SignResponse: " + signResponse);

    LOG.debug("decoded sign response: " + new String(Base64.decode(signResponse.getBytes())));

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);//from   ww  w  .  j av  a 2  s.com
    session.setDestination("destination");
    session.setInResponseTo("in-response-to");
    try {
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (UserCancelException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
    }
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testAuthorization() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey, DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR,
            DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR, null);
    LOG.debug("SignResponse: " + signResponse);

    LOG.debug("decoded sign response: " + new String(Base64.decode(signResponse.getBytes())));

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);//  w  w  w .j av  a  2  s  . c om
    session.setDestination("destination");
    session.setInResponseTo("in-response-to");
    try {
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (SubjectNotAuthorizedException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
    }
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testClientRuntime() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey, DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR,
            DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR, null);
    LOG.debug("SignResponse: " + signResponse);

    LOG.debug("decoded sign response: " + new String(Base64.decode(signResponse.getBytes())));

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);//from ww  w  .  j a  v a  2  s.  c o  m
    session.setDestination("destination");
    session.setInResponseTo("in-response-to");
    try {
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (ClientRuntimeException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
    }
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testAuthorizationWithSignerIdentity() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey, DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR,
            DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR, "signer-identity");
    LOG.debug("SignResponse: " + signResponse);

    LOG.debug("decoded sign response: " + new String(Base64.decode(signResponse.getBytes())));

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);/*  w  w w  .j  ava2s .co m*/
    session.setDestination("destination");
    session.setInResponseTo("in-response-to");
    try {
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (SubjectNotAuthorizedException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
        assertEquals("signer-identity", e.getSignerIdentity());
    }
}

From source file:Networking.Client.java

public void PRF() {
    try {/*from  w ww  .  j a v  a  2  s. c o  m*/
        SecretKeySpec myKey = new SecretKeySpec(this.node.getHashed_key_128(), "AES");
        byte[] plainText = new byte[128];
        byte[] ones = new byte[16];
        Arrays.fill(ones, (byte) 1);

        SecureRandom random = new SecureRandom();
        byte IV[] = new byte[16];
        random.nextBytes(IV);
        IvParameterSpec iv = new IvParameterSpec(IV);
        Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
        c.init(Cipher.ENCRYPT_MODE, myKey, iv);
        byte[] macKey = new byte[c.getOutputSize(plainText.length)];
        c.doFinal(plainText, 0, plainText.length, macKey);
        this.node.setMacKey(macKey);
        Cipher c1 = Cipher.getInstance("AES/CTR/NoPadding");
        c1.init(Cipher.ENCRYPT_MODE, myKey, iv);
        byte[] sessionKey = new byte[c1.getOutputSize(ones.length)];
        c1.doFinal(ones, 0, ones.length, sessionKey);
        this.node.setSessionKey(sessionKey);

    } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchPaddingException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ShortBufferException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:test.unit.be.e_contract.dssp.client.SignResponseVerifierTest.java

@Test
public void testMissingSignature() throws Exception {
    byte[] tokenKey = new byte[256 / 8];
    SecureRandom secureRandom = new SecureRandom();
    secureRandom.nextBytes(tokenKey);
    String signResponse = SignResponseFactory.createSignResponse("response-id", "destination", "in-response-to",
            "token-id", tokenKey);
    LOG.debug("SignResponse: " + signResponse);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(new ByteArrayInputStream(Base64.decode(signResponse)));
    Node signatureNode = document.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature")
            .item(0);//from w ww .  j a v a2 s .co  m
    signatureNode.getParentNode().removeChild(signatureNode);

    signResponse = Base64.encode(toString(document).getBytes());

    DigitalSignatureServiceSession session = new DigitalSignatureServiceSession("response-id", "token-id",
            tokenKey, null);
    session.setDestination("destination");
    session.setInResponseTo("in-response-to");
    try {
        SignResponseVerifier.checkSignResponse(signResponse, session);
        fail();
    } catch (SecurityException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // expected
        assertFalse(session.isSignResponseVerified());
    }
}

From source file:com.cloud.consoleproxy.AgentHookBase.java

@Override
public void startAgentHttpHandlerInVM(StartupProxyCommand startupCmd) {
    StartConsoleProxyAgentHttpHandlerCommand cmd = null;

    try {/*from ww  w . ja v a2  s  .co  m*/
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

        byte[] randomBytes = new byte[16];
        random.nextBytes(randomBytes);
        String storePassword = Base64.encodeBase64String(randomBytes);

        byte[] ksBits = null;
        String consoleProxyUrlDomain = _configDao.getValue(Config.ConsoleProxyUrlDomain.key());
        if (consoleProxyUrlDomain == null || consoleProxyUrlDomain.isEmpty()) {
            s_logger.debug(
                    "SSL is disabled for console proxy based on global config, skip loading certificates");
        } else {
            ksBits = _ksMgr.getKeystoreBits(ConsoleProxyManager.CERTIFICATE_NAME,
                    ConsoleProxyManager.CERTIFICATE_NAME, storePassword);
            //ks manager raises exception if ksBits are null, hence no need to explicltly handle the condition
        }

        cmd = new StartConsoleProxyAgentHttpHandlerCommand(ksBits, storePassword);
        cmd.setEncryptorPassword(getEncryptorPassword());

        HostVO consoleProxyHost = findConsoleProxyHost(startupCmd);

        assert (consoleProxyHost != null);
        if (consoleProxyHost != null) {
            Answer answer = _agentMgr.send(consoleProxyHost.getId(), cmd);
            if (answer == null || !answer.getResult()) {
                s_logger.error(
                        "Console proxy agent reported that it failed to execute http handling startup command");
            } else {
                s_logger.info("Successfully sent out command to start HTTP handling in console proxy agent");
            }
        }
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("Unexpected exception in SecureRandom Algorithm selection ", e);
    } catch (AgentUnavailableException e) {
        s_logger.error("Unable to send http handling startup command to the console proxy resource for proxy:"
                + startupCmd.getProxyVmId(), e);
    } catch (OperationTimedoutException e) {
        s_logger.error(
                "Unable to send http handling startup command(time out) to the console proxy resource for proxy:"
                        + startupCmd.getProxyVmId(),
                e);
    } catch (OutOfMemoryError e) {
        s_logger.error("Unrecoverable OutOfMemory Error, exit and let it be re-launched");
        System.exit(1);
    } catch (Exception e) {
        s_logger.error(
                "Unexpected exception when sending http handling startup command(time out) to the console proxy resource for proxy:"
                        + startupCmd.getProxyVmId(),
                e);
    }
}

From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java

/**
 * CryptoWrapper constructor creates a Cipher instance with the given
 * parameters.//from w ww  .  j a va  2s.  co m
 * 
 */
private CryptoWrapper(CryptoWrapperBuilder builder) throws IOException, GeneralSecurityException {

    readBufferSize = builder.readBufferSize;
    cipher = Cipher.getInstance(builder.transformationString);
    saltSize = builder.saltSize;
    keyDerivationIterationCount = builder.keyDerivationIterationCount;

    // Salt to prevent rainbow-table assisted dictionary attacks.
    // Used to derive a key from the password with PBKDF2WithHmacSHA1.
    if (builder.salt == null) {
        salt = new byte[saltSize];
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(salt);
    } else {
        salt = builder.salt;
    }

    if (builder.cipherKey == null) {
        cipherKey = new SecretKeySpec(getHashedPassword(builder), builder.cipherName);
    } else {
        cipherKey = builder.cipherKey;
    }

    /* If no IV given then generate a new one */
    if (builder.initializationVector == null) {
        initializationVector = getInitializationVector(builder);
    } else {
        initializationVector = builder.initializationVector;
    }
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML2ArtifactResolutionTest.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();

    SAMLObjectBuilder<Response> responseBuilder = (SAMLObjectBuilder<Response>) builderFactory
            .getBuilder(Response.DEFAULT_ELEMENT_NAME);
    Response response = responseBuilder.buildObject();
    response.getAssertions().add(assertion);

    SecureRandom handleGenerator = SecureRandom.getInstance("SHA1PRNG");
    byte[] endpointIndex = { 0, 1 };
    MessageDigest sha1Digester = MessageDigest.getInstance("SHA-1");
    byte[] source = sha1Digester.digest(relyingPartyId.getBytes());
    byte[] assertionHandle = new byte[20];
    handleGenerator.nextBytes(assertionHandle);
    SAML2ArtifactType0004 artifact = new SAML2ArtifactType0004(endpointIndex, source, assertionHandle);

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