List of usage examples for java.security SecureRandom nextBytes
@Override public void nextBytes(byte[] bytes)
From source file:org.apache.hadoop.gateway.openid.filter.OIDCFilter.java
private boolean processAuthorizationCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuffer buf = req.getRequestURL(); String personGuid = null;/*w w w.ja va2s .c o m*/ if (req.getQueryString() != null) { buf.append('?').append(req.getQueryString()); } AuthorizationCodeResponseUrl responseUrl; try { responseUrl = new AuthorizationCodeResponseUrl(buf.toString()); } catch (Exception e) { return false; } String code = responseUrl.getCode(); String state = responseUrl.getState(); if (responseUrl.getError() != null) { //error String error = responseUrl.getError(); String errorDescription = responseUrl.getErrorDescription(); req.setAttribute(ATTRIBUTE_LOGGED_IN, false); req.setAttribute(ATTRIBUTE_ERROR, error); req.setAttribute(ATTRIBUTE_ERROR_DESCRIPTION, errorDescription); return true; } else if (code == null) { return false; } else { lock.lock(); try { if (flow == null) { flow = initializeFlow(); } HttpSession session = req.getSession(); String storedState = (String) session.getAttribute(SESSION_OIDC_STATE); if (state != null && state.equals(storedState)) { String redirectUri = getRedirectUri(req); SecureRandom random = new SecureRandom(); byte[] bytes = new byte[16]; random.nextBytes(bytes); Base64 b64 = Base64.encode(bytes); String nonce = b64.toString(); nonce = nonce == null ? "" : nonce; String returnedNonce = null; TokenRequest tokenRequest = flow.newTokenRequest(code).setRedirectUri(redirectUri); tokenRequest.set(NONCE, nonce); TokenResponse response = tokenRequest.execute(); String idToken = (String) response.get(ID_TOKEN); System.out.println("id token: " + idToken); String[] str = idToken.split("\\."); if (str.length == 3) { String json = new Base64URL(str[1]).decodeToString(); String[] outer = json.split("[\\{\\}]"); for (String s : outer) { String[] pairs = s.split(","); for (String p : pairs) { String[] kv = p.split(":"); if (kv.length == 2) { String key = null; if (kv[0].startsWith("\"")) { key = kv[0].substring(1, kv[0].length() - 1); } else { key = kv[0]; } if (SUB.equals((key))) { if (kv[1].startsWith("\"")) { personGuid = kv[1].substring(1, kv[1].length() - 1); } else { personGuid = kv[1]; } } else if (NONCE.equals((key))) { if (kv[1].startsWith("\"")) { returnedNonce = kv[1].substring(1, kv[1].length() - 1); } else { returnedNonce = kv[1]; } } } if (personGuid != null && returnedNonce != null) { break; } } if (personGuid != null && returnedNonce != null) { break; } } } if (!nonce.equals(returnedNonce)) { personGuid = null; } System.out.println("personguid: " + personGuid); String userId = getUserId(req); // Credential credential = flow.createAndStoreCredential(response, userId); req.setAttribute(ATTRIBUTE_LOGGED_IN, personGuid != null); req.setAttribute(ATTRIBUTE_SUB_ID, personGuid); return personGuid != null; } else { req.setAttribute(ATTRIBUTE_LOGGED_IN, false); req.setAttribute(ATTRIBUTE_ERROR, ERROR_STATE_MISMATCH); return true; } // } catch(ParseException e) { // e.printStackTrace(); // } catch(JOSEException e) { // e.printStackTrace(); } finally { lock.unlock(); } } }
From source file:org.secuso.privacyfriendlydicegame.MainActivity.java
public int[] rollDice(int poolSize) { for (int j = 0; j < 5; j++) { backResults[j] = oldResults[j];//from w ww . j a v a 2 s . c om } int[] dice = new int[poolSize]; for (int i = 0; i < dice.length; i++) { if (isLocked[i]) { dice[i] = oldResults[i]; } else { SecureRandom random = new SecureRandom(); byte bytes[] = new byte[6]; random.nextBytes(bytes); dice[i] = random.nextInt(6) + 1; oldResults[i] = dice[i]; } } return dice; }
From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java
private String encrypt(final byte[] plainText, final byte[] encryptionKeyBytes, final SecureRandom random) throws GeneralSecurityException { // Generate 16 random IV bytes final byte[] ivBytes = new byte[AESIV_LENGTH]; random.nextBytes(ivBytes); final IvParameterSpec ivSpec = new IvParameterSpec(ivBytes); // Setup cypher final Cipher cipher = Cipher.getInstance(ENCRYPTION_CIPHER); cipher.init(Cipher.ENCRYPT_MODE, buildSecretKey(encryptionKeyBytes), ivSpec); // Generate encrypted data final byte[] encryptedBytes = cipher.doFinal(plainText); // Prepend the IV final byte[] encryptedBytesPlusIV = new byte[ivBytes.length + encryptedBytes.length]; System.arraycopy(ivBytes, 0, encryptedBytesPlusIV, 0, ivBytes.length); System.arraycopy(encryptedBytes, 0, encryptedBytesPlusIV, ivBytes.length, encryptedBytes.length); return convert(encryptedBytesPlusIV); }
From source file:test.be.fedict.eid.applet.SecurePinPadReaderTest.java
/** * Only applicable for 2048 bit keys./* w ww . j a va 2 s . c o m*/ * * @throws Exception */ @Test @QualityAssurance(firmware = Firmware.V015Z, approved = true) public void testLargePlainTextMessage() throws Exception { CardChannel cardChannel = this.pcscEid.getCardChannel(); List<X509Certificate> signCertChain = this.pcscEid.getSignCertificateChain(); CommandAPDU setApdu = new CommandAPDU(0x00, 0x22, 0x41, 0xB6, new byte[] { 0x04, // length of following data (byte) 0x80, // algo ref 0x01, // rsa pkcs#1 (byte) 0x84, // tag for private key ref (byte) 0x83 }); // non-rep key ResponseAPDU responseApdu = cardChannel.transmit(setApdu); assertEquals(0x9000, responseApdu.getSW()); this.pcscEid.verifyPin(); byte[] data = new byte[115]; /* * If the length of the plain text message is >= 115, the message is not * visualized by the secure pinpad reader. */ SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(data); AlgorithmIdentifier algoId = new AlgorithmIdentifier("2.16.56.1.2.1.3.1"); DigestInfo digestInfo = new DigestInfo(algoId, data); CommandAPDU computeDigitalSignatureApdu = new CommandAPDU(0x00, 0x2A, 0x9E, 0x9A, digestInfo.getDEREncoded()); responseApdu = cardChannel.transmit(computeDigitalSignatureApdu); assertEquals(0x9000, responseApdu.getSW()); byte[] signatureValue = responseApdu.getData(); LOG.debug("signature value size: " + signatureValue.length); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, signCertChain.get(0)); byte[] signatureDigestInfoValue = cipher.doFinal(signatureValue); ASN1InputStream aIn = new ASN1InputStream(signatureDigestInfoValue); DigestInfo signatureDigestInfo = new DigestInfo((ASN1Sequence) aIn.readObject()); LOG.debug("result algo Id: " + signatureDigestInfo.getAlgorithmId().getObjectId().getId()); assertEquals("2.16.56.1.2.1.3.1", signatureDigestInfo.getAlgorithmId().getObjectId().getId()); assertArrayEquals(data, signatureDigestInfo.getDigest()); }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
private byte[] genIV() { SecureRandom r = new SecureRandom(); byte[] iv = new byte[16]; r.nextBytes(iv); return iv;// w w w. java2 s . c o m }
From source file:com.diona.fileReader.CipherUtil.java
/** * Generates the initialization vector to be used for encryption. * /*from ww w . ja va 2s .c o m*/ * @return the initialization vector. */ private byte[] getIV(final Context context) { // final SocialWorkerSharedPreferences sharedPreferences = SocialWorkerSharedPreferences.getInstance(); // if (sharedPreferences.getIV() == null) { try { final SecureRandom random = new SecureRandom(); final byte[] iv = new byte[IV_LENGTH]; random.nextBytes(iv); // sharedPreferences.setIV(iv); return iv; } catch (final Exception e) { Log.e(TAG, "" + e.getMessage(), e); return null; } // } else { // return sharedPreferences.getIV(); // } }
From source file:org.n2.app.beans.RegisterBean.java
/** * Creates a fixed length small fingerprint (digest / hash) * See: https://www.owasp.org/index.php/Hashing_Java */// www . jav a2s. c o m private void securePassword() { try { // Uses a secure Random not a simple Random SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); // Salt generation 64 bits long byte[] salt = new byte[8]; random.nextBytes(salt); // Digest computation byte[] digest = getHash(ITERATION_NUMBER, password, salt); setPassword(byteToBase64(digest)); setSalt(byteToBase64(salt)); } catch (Exception e) { LOG.error("Error while creating password hash", e); throw new RuntimeException("Error while creating user."); } }
From source file:org.alfresco.encryption.KeyStoreTests.java
public byte[] generateKeyData() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(System.currentTimeMillis()); byte bytes[] = new byte[DESedeKeySpec.DES_EDE_KEY_LEN]; random.nextBytes(bytes); return bytes; }
From source file:test.unit.be.agiv.security.handler.WSSecurityHandlerTest.java
@Test public void testSignature() throws Exception { // setup/*w w w .j a va 2 s .c o m*/ SOAPMessageContext mockContext = EasyMock.createMock(SOAPMessageContext.class); EasyMock.expect(mockContext.get("javax.xml.ws.handler.message.outbound")).andStubReturn(Boolean.TRUE); byte[] secret = new byte[256 / 8]; SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(secret); String tokenIdentifier = "#saml-token-test"; this.testedInstance.setKey(secret, tokenIdentifier, null, false); InputStream requestInputStream = WSSecurityHandlerTest.class .getResourceAsStream("/r-sts-request-before-signing.xml"); SOAPMessage soapMessage = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage(null, requestInputStream); EasyMock.expect(mockContext.getMessage()).andStubReturn(soapMessage); // prepare EasyMock.replay(mockContext); // operate boolean result = this.testedInstance.handleMessage(mockContext); // verify EasyMock.verify(mockContext); assertTrue(result); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); soapMessage.writeTo(outputStream); LOG.debug("SOAP message: " + new String(outputStream.toByteArray())); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray()); Document resultDocument = documentBuilder.parse(byteArrayInputStream); TestUtils.markAllIdAttributesAsId(resultDocument); NodeList signatureNodeList = resultDocument.getElementsByTagNameNS(Constants.SignatureSpecNS, "Signature"); assertEquals(1, signatureNodeList.getLength()); Element signatureElement = (Element) signatureNodeList.item(0); XMLSignature xmlSignature = new XMLSignature(signatureElement, null); Key key = WSSecurityUtil.prepareSecretKey(SignatureMethod.HMAC_SHA1, secret); boolean signatureResult = xmlSignature.checkSignatureValue(key); assertTrue(signatureResult); LOG.debug("signed SOAP: " + toString(resultDocument)); }
From source file:org.opensafety.hishare.util.implementation.EncryptionImpl.java
public byte[] createSalt() throws CryptographyException { SecureRandom random; try {/* w ww .ja v a2 s. com*/ random = SecureRandom.getInstance(randomAlgorithm); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e.getMessage()); } byte[] salt = new byte[saltLength]; random.nextBytes(salt); return salt; }