Java Code Examples for java.security.SecureRandom#getInstanceStrong()
The following examples show how to use
java.security.SecureRandom#getInstanceStrong() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MTGDeckManager.java From MtgDesktopCompanion with GNU General Public License v3.0 | 6 votes |
public MagicDeck generateRandomDeck() throws IOException { try { Random random= SecureRandom.getInstanceStrong(); List<MTGDeckSniffer> deckServices = MTGControler.getInstance().listEnabled(MTGDeckSniffer.class); MTGDeckSniffer sniffer = deckServices.get(random.nextInt(deckServices.size())); String[] formats = sniffer.listFilter(); sniffer.setProperty("FORMAT", formats[random.nextInt(formats.length)]); List<RetrievableDeck> availableDecks = sniffer.getDeckList(); RetrievableDeck d = availableDecks.get(random.nextInt(availableDecks.size())); return sniffer.getDeck(d); } catch (NoSuchAlgorithmException e) { logger.error(e); return new MagicDeck(); } }
Example 2
Source File: EncryptionPayload.java From strongbox with Apache License 2.0 | 6 votes |
@JsonCreator public EncryptionPayload(@JsonProperty("value") SecretValue value, @JsonProperty("userdata") Optional<UserData> userData, @JsonProperty("created") ZonedDateTime created, Optional<UserAlias> createdBy, @JsonProperty("modified") ZonedDateTime modified, Optional<UserAlias> modifiedBy, @JsonProperty("comment") Optional<Comment> comment) { this.value = value; this.userData = userData; this.created = created; this.modified = modified; this.createdBy = createdBy; this.modifiedBy = modifiedBy; this.comment = comment; try { this.random = SecureRandom.getInstanceStrong(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to instantiate random number generator", e); } }
Example 3
Source File: PrngRandom.java From sfs with Apache License 2.0 | 6 votes |
private SecureRandom getSecureRandom() { // reseed every MAX_INVOCATIONS so that the entropy stream is less predictable if (invocationCount.incrementAndGet() >= MAX_INVOCATIONS) { synchronized (invocationCount) { if (invocationCount.get() >= MAX_INVOCATIONS) { try { secureRandom = SecureRandom.getInstance("NativePRNGNonBlocking"); } catch (Exception e) { try { secureRandom = SecureRandom.getInstanceStrong(); } catch (Exception nE) { throw new RuntimeException(nE); } } invocationCount.set(0); } } } return secureRandom; }
Example 4
Source File: Aes256BitKeysizeTest.java From java-ilp-core with Apache License 2.0 | 5 votes |
@Test public final void test256bitKey() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { SecureRandom sr = SecureRandom.getInstanceStrong(); byte[] nonce = new byte[16]; sr.nextBytes(nonce); KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(256); byte[] key = keygen.generateKey().getEncoded(); byte[] data = new byte[256]; sr.nextBytes(data); Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding"); GCMParameterSpec paramSpec = new GCMParameterSpec(128, nonce); try { cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), paramSpec); cipher.doFinal(data); } catch (InvalidKeyException e) { throw new InterledgerRuntimeException("Error loading 256bit key. " + "Likley cause is missing Unlimited Strength Jurisdiction Policy Files.", e); } }
Example 5
Source File: ProcessApiUnitTest.java From tutorials with MIT License | 5 votes |
private void waistCPU() throws NoSuchAlgorithmException { ArrayList<Integer> randArr = new ArrayList<Integer>(4096); SecureRandom sr = SecureRandom.getInstanceStrong(); Duration somecpu = Duration.ofMillis(4200L); Instant end = Instant.now().plus(somecpu); while (Instant.now().isBefore(end)) { // System.out.println(sr.nextInt()); randArr.add(sr.nextInt()); } }
Example 6
Source File: SecurityFactoryImpl.java From xipki with Apache License 2.0 | 5 votes |
private static SecureRandom getSecureRandom(boolean strong) { if (!strong) { return new SecureRandom(); } try { return SecureRandom.getInstanceStrong(); } catch (NoSuchAlgorithmException ex) { throw new RuntimeCryptoException( "could not get strong SecureRandom: " + ex.getMessage()); } }
Example 7
Source File: Article.java From jinjava with Apache License 2.0 | 5 votes |
public Article(int id, User user) throws NoSuchAlgorithmException { this.id = id; this.href = "/article/" + id; LoremIpsum ipsum = new LoremIpsum(); SecureRandom rnd = SecureRandom.getInstanceStrong(); this.title = ipsum.getWords(10); this.user = user; this.body = ipsum.getParagraphs(); this.pubDate = Date.from(LocalDateTime.now().minusHours(rnd.nextInt(128)).toInstant(ZoneOffset.UTC)); this.published = true; }
Example 8
Source File: ConcurrentRedissonSortedSetTest.java From redisson with Apache License 2.0 | 5 votes |
@Test public void testAddRemove_SingleInstance() throws InterruptedException, NoSuchAlgorithmException { final String name = "testAddNegative_SingleInstance"; RedissonClient r = BaseTest.createInstance(); RSortedSet<Integer> map = r.getSortedSet(name); map.clear(); int length = 1000; for (int i = 0; i < length; i++) { map.add(i); } final AtomicInteger counter = new AtomicInteger(length); final Random rnd = SecureRandom.getInstanceStrong(); testSingleInstanceConcurrency(length, rc -> { RSortedSet<Integer> set = rc.getSortedSet(name); int c = counter.incrementAndGet(); Assert.assertTrue(set.add(c)); set.remove(rnd.nextInt(length)); }); Assert.assertEquals(counter.get(), length*2); Integer prevVal = null; for (Integer val : map) { if (prevVal == null) { prevVal = val; continue; } if (val < prevVal) { Assert.fail(); } } r.shutdown(); }
Example 9
Source File: TLSArtifactsGeneratorTest.java From dcos-commons with Apache License 2.0 | 5 votes |
private X509Certificate createCertificate() throws Exception { BigInteger serial = new BigInteger(100, SecureRandom.getInstanceStrong()); X500Name self = new X500Name("cn=localhost"); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( self, serial, Date.from(Instant.now()), Date.from(Instant.now().plusSeconds(100000)), self, KEYPAIR.getPublic()); X509CertificateHolder certHolder = certificateBuilder .build(new JcaContentSignerBuilder("SHA256WithRSA").build(KEYPAIR.getPrivate())); return new JcaX509CertificateConverter().getCertificate(certHolder); }
Example 10
Source File: LocalKeyFactory.java From aws-athena-query-federation with Apache License 2.0 | 5 votes |
public EncryptionKey create() { try { SecureRandom random = SecureRandom.getInstanceStrong(); KeyGenerator keyGen = KeyGenerator.getInstance(AesGcmBlockCrypto.KEYSPEC); keyGen.init(AesGcmBlockCrypto.KEY_BYTES * 8, random); SecretKey key = keyGen.generateKey(); final byte[] nonce = new byte[AesGcmBlockCrypto.NONCE_BYTES]; random.nextBytes(nonce); return new EncryptionKey(key.getEncoded(), nonce); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }
Example 11
Source File: PskNonceHeader.java From java-ilp-core with Apache License 2.0 | 5 votes |
/** * Constructs an instance of the header with a randomly generated value. * * @return new nonce header */ public static PskNonceHeader seed() { try { SecureRandom sr = SecureRandom.getInstanceStrong(); byte[] nonce = new byte[16]; sr.nextBytes(nonce); return new PskNonceHeader(nonce); } catch (NoSuchAlgorithmException nsa) { throw new InterledgerRuntimeException("Could not generate secure nonce", nsa); } }
Example 12
Source File: PskContext.java From java-ilp-core with Apache License 2.0 | 5 votes |
/** * Generate a strong random 16 byte token using the system provided {@link SecureRandom}. * * @return a random 16 byte token */ static byte[] generateToken() { try { SecureRandom sr = SecureRandom.getInstanceStrong(); byte[] token = new byte[16]; sr.nextBytes(token); return token; } catch (NoSuchAlgorithmException nsa) { throw new InterledgerRuntimeException("Could not generate token", nsa); } }
Example 13
Source File: EntropyHarvester.java From secure-quick-reliable-login with MIT License | 5 votes |
private EntropyHarvester() throws Exception { if(Build.DEVICE != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { sr = SecureRandom.getInstanceStrong(); } else { sr = SecureRandom.getInstance("SHA1PRNG"); } md = MessageDigest.getInstance("SHA-512"); this.numberOfBytesGathered = BigInteger.ZERO; }
Example 14
Source File: Main.java From java-all with MIT License | 5 votes |
public static void main(String[] args) throws Exception, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { // Initialise random and generate key SecureRandom random = SecureRandom.getInstanceStrong(); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128, random); SecretKey key = keyGen.generateKey(); String needToEncyptString = "needToEncString"; // Encrypt Cipher c = Cipher.getInstance("AES/GCM/NoPadding"); byte[] nonce = generateNonce(12); //NEVER REUSE THIS NONCE WITH SAME KEY c.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, nonce)); byte[] encValue = c.doFinal(needToEncyptString.getBytes()); String encrypted = Base64.getUrlEncoder().encodeToString(formatCipherMsg(nonce, encValue)); byte[] decodedMsg = Base64.getUrlDecoder().decode(encrypted); // decrypt ByteBuffer byteBuffer = ByteBuffer.wrap(decodedMsg); int ivLength = byteBuffer.getInt(); if (ivLength != 12) { // check input parameter throw new IllegalArgumentException("invalid iv length"); } byte[] nonce1 = new byte[ivLength]; byteBuffer.get(nonce1); byte[] encValue1 = new byte[byteBuffer.remaining()]; byteBuffer.get(encValue1); c.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, nonce)); byte[] decValue = c.doFinal(encValue); String decryptedString = new String(decValue); System.out.println(needToEncyptString); System.out.println(decryptedString); }
Example 15
Source File: GenerateLowSTests.java From GreenBits with GNU General Public License v3.0 | 4 votes |
public static void main(final String[] argv) throws NoSuchAlgorithmException, IOException { final NetworkParameters params = new MainNetParams(); final LocalTransactionSigner signer = new LocalTransactionSigner(); final SecureRandom secureRandom = SecureRandom.getInstanceStrong(); final ECKey key = new ECKey(secureRandom); final KeyBag bag = new KeyBag() { @Override public ECKey findKeyFromPubHash(byte[] pubkeyHash) { return key; } @Override public ECKey findKeyFromPubKey(byte[] pubkey) { return key; } @Override public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) { return null; } }; // Generate a fictional output transaction we take values from, and // an input transaction for the test case final Transaction outputTransaction = new Transaction(params); final Transaction inputTransaction = new Transaction(params); final TransactionOutput output = new TransactionOutput(params, inputTransaction, Coin.ZERO, key.toAddress(params)); inputTransaction.addOutput(output); outputTransaction.addInput(output); outputTransaction.addOutput(Coin.ZERO, new ECKey(secureRandom).toAddress(params)); addOutputs(outputTransaction, bag); // Sign the transaction final ProposedTransaction proposedTransaction = new ProposedTransaction(outputTransaction); signer.signInputs(proposedTransaction, bag); final TransactionInput input = proposedTransaction.partialTx.getInput(0); input.verify(output); input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(), EnumSet.of(Script.VerifyFlag.DERSIG, Script.VerifyFlag.P2SH)); final Script scriptSig = input.getScriptSig(); final TransactionSignature signature = TransactionSignature.decodeFromBitcoin(scriptSig.getChunks().get(0).data, true, false); // First output a conventional low-S transaction with the LOW_S flag, for the tx_valid.json set System.out.println("[\"A transaction with a low-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getHashAsString() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],"); final BigInteger highS = HIGH_S_DIFFERENCE.subtract(signature.s); final TransactionSignature highSig = new TransactionSignature(signature.r, highS); input.setScriptSig(new ScriptBuilder().data(highSig.encodeToBitcoin()).data(scriptSig.getChunks().get(1).data).build()); input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(), EnumSet.of(Script.VerifyFlag.P2SH)); // A high-S transaction without the LOW_S flag, for the tx_valid.json set System.out.println("[\"A transaction with a high-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getHashAsString() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "\"],"); // Lastly a conventional high-S transaction with the LOW_S flag, for the tx_invalid.json set System.out.println("[\"A transaction with a high-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getHashAsString() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],"); }
Example 16
Source File: GenerateLowSTests.java From green_android with GNU General Public License v3.0 | 4 votes |
public static void main(final String[] argv) throws NoSuchAlgorithmException, IOException { final NetworkParameters params = new MainNetParams(); final LocalTransactionSigner signer = new LocalTransactionSigner(); final SecureRandom secureRandom = SecureRandom.getInstanceStrong(); final ECKey key = new ECKey(secureRandom); final KeyBag bag = new KeyBag() { @Override public ECKey findKeyFromPubHash(byte[] pubkeyHash) { return key; } @Override public ECKey findKeyFromPubKey(byte[] pubkey) { return key; } @Override public RedeemData findRedeemDataFromScriptHash(byte[] scriptHash) { return null; } }; // Generate a fictional output transaction we take values from, and // an input transaction for the test case final Transaction outputTransaction = new Transaction(params); final Transaction inputTransaction = new Transaction(params); final TransactionOutput output = new TransactionOutput(params, inputTransaction, Coin.ZERO, key.toAddress(params)); inputTransaction.addOutput(output); outputTransaction.addInput(output); outputTransaction.addOutput(Coin.ZERO, new ECKey(secureRandom).toAddress(params)); addOutputs(outputTransaction, bag); // Sign the transaction final ProposedTransaction proposedTransaction = new ProposedTransaction(outputTransaction); signer.signInputs(proposedTransaction, bag); final TransactionInput input = proposedTransaction.partialTx.getInput(0); input.verify(output); input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(), EnumSet.of(Script.VerifyFlag.DERSIG, Script.VerifyFlag.P2SH)); final Script scriptSig = input.getScriptSig(); final TransactionSignature signature = TransactionSignature.decodeFromBitcoin(scriptSig.getChunks().get(0).data, true, false); // First output a conventional low-S transaction with the LOW_S flag, for the tx_valid.json set System.out.println("[\"A transaction with a low-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getHashAsString() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],"); final BigInteger highS = HIGH_S_DIFFERENCE.subtract(signature.s); final TransactionSignature highSig = new TransactionSignature(signature.r, highS); input.setScriptSig(new ScriptBuilder().data(highSig.encodeToBitcoin()).data(scriptSig.getChunks().get(1).data).build()); input.getScriptSig().correctlySpends(outputTransaction, 0, output.getScriptPubKey(), EnumSet.of(Script.VerifyFlag.P2SH)); // A high-S transaction without the LOW_S flag, for the tx_valid.json set System.out.println("[\"A transaction with a high-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getHashAsString() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "\"],"); // Lastly a conventional high-S transaction with the LOW_S flag, for the tx_invalid.json set System.out.println("[\"A transaction with a high-S signature.\"],"); System.out.println("[[[\"" + inputTransaction.getHashAsString() + "\", " + output.getIndex() + ", \"" + scriptToString(output.getScriptPubKey()) + "\"]],\n" + "\"" + Utils.HEX.encode(proposedTransaction.partialTx.unsafeBitcoinSerialize()) + "\", \"" + Script.VerifyFlag.P2SH.name() + "," + Script.VerifyFlag.LOW_S.name() + "\"],"); }
Example 17
Source File: AES.java From arcusplatform with Apache License 2.0 | 4 votes |
public AES(String secret, String unsafeIV) throws NoSuchAlgorithmException { this.secret = secret; this.unsafeIV = unsafeIV; this.random = SecureRandom.getInstanceStrong(); }
Example 18
Source File: AES.java From arcusplatform with Apache License 2.0 | 4 votes |
public AES() throws NoSuchAlgorithmException { this.random = SecureRandom.getInstanceStrong(); }