List of usage examples for java.security SecureRandom nextBytes
@Override public void nextBytes(byte[] bytes)
From source file:com.diversityarrays.dalclient.DalUtil.java
/** * Generate a 64-bit random number./*from w w w.ja v a 2 s. c o m*/ * @return the number as a String */ static public String createRandomNumberString() { SecureRandom random = new SecureRandom(); byte[] sixtyFourBits = new byte[8]; random.nextBytes(sixtyFourBits); // Let's be positive about this :-) sixtyFourBits[0] = (byte) (0x7f & sixtyFourBits[0]); BigInteger bigint = new BigInteger(sixtyFourBits); return bigint.toString(); }
From source file:org.hyperledger.account.BIP39Test.java
@Test public void bip39EncodeDecodeTest() throws IOException, JSONException, HyperLedgerException { JSONObject testData = readObject(TESTS); JSONArray english = testData.getJSONArray("english"); for (int i = 0; i < testData.length(); ++i) { JSONArray test = english.getJSONArray(i); byte[] m = Mnemonic.decode(test.getString(1), "HyperLedger"); assertTrue(test.getString(1).equals(Mnemonic.encode(m, "HyperLedger"))); }/*from www .j av a2s . com*/ SecureRandom random = new SecureRandom(); for (int i = 0; i < 100; ++i) { byte[] secret = new byte[32]; random.nextBytes(secret); String e = Mnemonic.encode(secret, "HyperLedger"); assertTrue(Arrays.equals(Mnemonic.decode(e, "HyperLedger"), secret)); } }
From source file:snow.security.SessionRegistry.java
public String newAccessToken() { SecureRandom ng = Holder.numberGenerator; byte[] randomBytes = new byte[16]; ng.nextBytes(randomBytes); return new String(encodeBase64URLSafeString(randomBytes)); }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
private static void exportSPMetaData(Options options, CommandLine cmd, TremoloType tt, KeyStore ks) throws Exception, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, CertificateEncodingException, MarshallingException { logger.info("Finding mechanism..."); String mechanismName = loadOption(cmd, "mechanismName", options); MechanismType saml2Mech = loadMechanismType(mechanismName, tt); logger.info("...found"); logger.info("Finding chain..."); String chainName = loadOption(cmd, "chainName", options); AuthChainType act = loadChainType(chainName, tt); logger.info("Looking for correct mechanism on the chain..."); AuthMechType currentMechanism = null; for (AuthMechType amt : act.getAuthMech()) { if (amt.getName().equalsIgnoreCase(mechanismName)) { currentMechanism = amt;//from w ww. j av a 2s. c o m break; } } if (currentMechanism == null) { System.err.println("Unknown chain on mechanism"); System.exit(1); } InitializationService.initialize(); logger.info("loading url base"); String urlBase = loadOption(cmd, "urlBase", options); String url = urlBase + saml2Mech.getUri(); SecureRandom random = new SecureRandom(); byte[] idBytes = new byte[20]; random.nextBytes(idBytes); String id = "f" + Hex.encodeHexString(idBytes); EntityDescriptorBuilder edb = new EntityDescriptorBuilder(); EntityDescriptorImpl ed = (EntityDescriptorImpl) edb.buildObject(); ed.setID(id); ed.setEntityID(url); SPSSODescriptorBuilder spb = new SPSSODescriptorBuilder(); SPSSODescriptorImpl sp = (SPSSODescriptorImpl) spb.buildObject(); ed.getRoleDescriptors().add(sp); HashMap<String, ParamType> params = new HashMap<String, ParamType>(); for (ParamType pt : currentMechanism.getParams().getParam()) { params.put(pt.getName(), pt); } boolean assertionsSigned = params.get("assertionsSigned") != null && params.get("assertionsSigned").getValue().equalsIgnoreCase("true"); sp.setWantAssertionsSigned(assertionsSigned); sp.addSupportedProtocol("urn:oasis:names:tc:SAML:2.0:protocol"); SingleLogoutServiceBuilder slsb = new SingleLogoutServiceBuilder(); SingleLogoutService sls = slsb.buildObject(); sls.setLocation(url); sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"); sp.getSingleLogoutServices().add(sls); sls = slsb.buildObject(); sls.setLocation(url); sls.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); sp.getSingleLogoutServices().add(sls); AssertionConsumerServiceBuilder acsb = new AssertionConsumerServiceBuilder(); AssertionConsumerService acs = acsb.buildObject(); acs.setLocation(url); acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); acs.setIndex(0); acs.setIsDefault(true); sp.getAssertionConsumerServices().add(acs); acs = acsb.buildObject(); acs.setLocation(url); acs.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"); acs.setIndex(1); sp.getAssertionConsumerServices().add(acs); if (params.get("spSigKey") != null && !params.get("spSigKey").getValue().isEmpty()) { String alias = params.get("spSigKey").getValue(); X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias); if (certFromKS == null) { throw new Exception("Certificate '" + params.get("spSigKey").getValue() + "' not found"); } PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray()); KeyDescriptorBuilder kdb = new KeyDescriptorBuilder(); 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(new String(Base64.encode(certFromKS.getEncoded()))); x509.getX509Certificates().add(cert); ki.getX509Datas().add(x509); kd.setKeyInfo(ki); sp.getKeyDescriptors().add(kd); } if (params.get("spEncKey") != null && !params.get("spEncKey").getValue().isEmpty()) { String alias = params.get("spEncKey").getValue(); X509Certificate certFromKS = (X509Certificate) ks.getCertificate(alias); if (certFromKS == null) { throw new Exception("Certificate '" + params.get("spEncKey").getValue() + "' not found"); } PrivateKey keyFromKS = (PrivateKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray()); KeyDescriptorBuilder kdb = new KeyDescriptorBuilder(); 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(new String(Base64.encode(certFromKS.getEncoded()))); x509.getX509Certificates().add(cert); ki.getX509Datas().add(x509); kd.setKeyInfo(ki); sp.getKeyDescriptors().add(kd); } EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller(); // Marshall the Subject Element assertionElement = marshaller.marshall(ed); String xml = net.shibboleth.utilities.java.support.xml.SerializeSupport.prettyPrintXML(assertionElement); logger.info(xml); }
From source file:dk.netarkivet.harvester.harvesting.metadata.MetadataFileWriterTester.java
@Test public void testMetadataFileWriterArc() throws IOException { File metafile = getOutputArcFile("metadata.arc"); MetadataFileWriter mdfw = MetadataFileWriterArc.createWriter(metafile); String uri = "http://www.netarkivet.dk/"; long ctm = System.currentTimeMillis(); SecureRandom random = new SecureRandom(); byte[] payload = new byte[8192]; random.nextBytes(payload); mdfw.write(uri, "application/binary", "127.0.0.1", ctm, payload); mdfw.close();/*from w w w . j a va 2 s. c om*/ metafile.deleteOnExit(); File metadataArcFile = getOutputArcFile("42-metadata-1.arc"); MetadataFileWriter mfwa = MetadataFileWriterArc.createWriter(metadataArcFile); for (File f : logsDir.listFiles()) { mfwa.writeFileTo(f, "metadata://netarkivet.dk/crawl/logs/" + f.getName(), "text/plain"); } }
From source file:dk.netarkivet.harvester.harvesting.MetadataFileWriterTester.java
public void testMetadataFileWriterArc() { File metafile = new File("metadata.arc"); MetadataFileWriter mdfw = MetadataFileWriterArc.createWriter(metafile); String uri = "http://www.netarkivet.dk/"; long ctm = System.currentTimeMillis(); SecureRandom random = new SecureRandom(); byte[] payload = new byte[8192]; random.nextBytes(payload); try {// www.j av a 2 s . c om mdfw.write(uri, "application/binary", "127.0.0.1", ctm, payload); mdfw.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail("Unexpected exception!"); } metafile.deleteOnExit(); File metadataArcFile = new File(TestInfo.WORKING_DIR, "42-metadata-1.arc"); MetadataFileWriter mfwa = MetadataFileWriterArc.createWriter(metadataArcFile); for (File f : logsDir.listFiles()) { mfwa.writeFileTo(f, "metadata://netarkivet.dk/crawl/logs/" + f.getName(), "text/plain"); } }
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 . j av 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:org.zuinnote.hadoop.office.format.common.writer.msexcel.internal.EncryptedTempData.java
public EncryptedTempData(CipherAlgorithm ca, ChainingMode cm) throws IOException { // generate random key for temnporary files if (ca != null) { SecureRandom sr = new SecureRandom(); byte[] iv = new byte[ca.blockSize]; byte[] key = new byte[ca.defaultKeySize / 8]; sr.nextBytes(iv); sr.nextBytes(key);/*from w w w . j a v a 2s . co m*/ SecretKeySpec skeySpec = new SecretKeySpec(key, ca.jceId); this.ca = ca; this.cm = cm; if (this.cm.jceId.equals(ChainingMode.ecb.jceId)) { // does not work with Crpyto Functions since it does not require IV this.cm = ChainingMode.cbc; } this.ciEncrypt = CryptoFunctions.getCipher(skeySpec, ca, cm, iv, Cipher.ENCRYPT_MODE, "PKCS5Padding"); this.ciDecrypt = CryptoFunctions.getCipher(skeySpec, ca, cm, iv, Cipher.DECRYPT_MODE, "PKCS5Padding"); } this.tempFile = TempFile.createTempFile("hadooffice-poi-temp-data", ".tmp"); }
From source file:dk.netarkivet.harvester.harvesting.metadata.MetadataFileWriterTester.java
@Test public void testMetadataFileWriterWarc() throws IOException { File metafile = getOutputArcFile("metadata.warc"); MetadataFileWriter mdfw = MetadataFileWriterWarc.createWriter(metafile); String uri = "http://www.netarkivet.dk/"; long ctm = System.currentTimeMillis(); SecureRandom random = new SecureRandom(); byte[] payload = new byte[8192]; random.nextBytes(payload); mdfw.write(uri, "application/binary", "127.0.0.1", ctm, payload); mdfw.close();/*from w w w.j a va2s .co m*/ metafile.deleteOnExit(); File metadataArcFile = getOutputArcFile("42-metadata-1.warc"); MetadataFileWriter mfwa = MetadataFileWriterWarc.createWriter(metadataArcFile); ((MetadataFileWriterWarc) mfwa).insertInfoRecord(new ANVLRecord()); for (File f : logsDir.listFiles()) { mfwa.writeFileTo(f, "metadata://netarkivet.dk/crawl/logs/" + f.getName(), "text/plain"); } }
From source file:dk.netarkivet.harvester.harvesting.MetadataFileWriterTester.java
public void testMetadataFileWriterWarc() { File metafile = new File("metadata.warc"); MetadataFileWriter mdfw = MetadataFileWriterWarc.createWriter(metafile); String uri = "http://www.netarkivet.dk/"; long ctm = System.currentTimeMillis(); SecureRandom random = new SecureRandom(); byte[] payload = new byte[8192]; random.nextBytes(payload); try {/* w ww .j a v a 2 s . co m*/ mdfw.write(uri, "application/binary", "127.0.0.1", ctm, payload); mdfw.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail("Unexpected exception!"); } metafile.deleteOnExit(); File metadataArcFile = new File(TestInfo.WORKING_DIR, "42-metadata-1.warc"); MetadataFileWriter mfwa = MetadataFileWriterWarc.createWriter(metadataArcFile); ((MetadataFileWriterWarc) mfwa).insertInfoRecord(new ANVLRecord()); for (File f : logsDir.listFiles()) { mfwa.writeFileTo(f, "metadata://netarkivet.dk/crawl/logs/" + f.getName(), "text/plain"); } }