Java Code Examples for java.security.SecureRandom#getInstance()
The following examples show how to use
java.security.SecureRandom#getInstance() .
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: CryptoHelperImpl.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Override public SecureRandom createSecureRandom(final String algorithm) throws NoSuchAlgorithmException { checkNotNull(algorithm); SecureRandom obj; try { obj = SecureRandom.getInstance(algorithm, getProvider()); } catch (NoSuchAlgorithmException e) { logFallback(e); obj = SecureRandom.getInstance(algorithm); } if (log.isTraceEnabled()) { log.trace("Created secure-random: {} ({})", obj.getAlgorithm(), obj.getProvider().getName()); } return obj; }
Example 2
Source File: TestDeserialization.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
public void main(Provider p) throws Exception { // Skip this test for providers not found by java.security.Security if (Security.getProvider(p.getName()) != p) { System.out.println("Skip test for provider " + p.getName()); return; } SecureRandom r; try { r = SecureRandom.getInstance("PKCS11", p); System.out.println("SecureRandom instance " + r); } catch (NoSuchAlgorithmException e) { System.out.println("Provider " + p + " does not support SecureRandom, skipping"); e.printStackTrace(); return; } r.setSeed(System.currentTimeMillis()); byte[] buf = new byte[16]; byte[] ser = toByteArray(r); System.out.println("Serialized Len = " + ser.length); SecureRandom r2 = fromByteArray(ser); System.out.println("Deserialized into " + r2); r2.nextBytes(buf); System.out.println("Done"); }
Example 3
Source File: SecurityUtilities.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
/** * Generate a random array of bytes (1024 bits) using the SHA1PRNG alghoritm. * * @return Byte array filled with random byte */ public byte[] generateRandomChallenge() { byte[] challenge = null; try { SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); // Get 1024 random bits challenge = new byte[1024]; sr.nextBytes(challenge); } catch (NoSuchAlgorithmException e) { SpagoBITracer.major("ENGINES", this.getClass().getName(), "generateRandomChallenge", "Alghoritm SHA1PRNG not found ", e); } return challenge; }
Example 4
Source File: OAuth2AuthorizationServer.java From OAuth-2.0-Cookbook with MIT License | 6 votes |
@Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(1024, random); KeyPair keyPair = keyGen.generateKeyPair(); converter.setKeyPair(keyPair); } catch (Exception e) { throw new RuntimeException(e); } return converter; }
Example 5
Source File: StringRandomUtils.java From openzaly with Apache License 2.0 | 5 votes |
public static String generateRandomString(int length) throws NoSuchAlgorithmException { SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG"); StringBuffer newRandomStr = new StringBuffer(); for (int i = 0; i < length; ++i) { int number = sRandom.nextInt(STR_62_RANDOM.length()); newRandomStr.append(STR_62_RANDOM.charAt(number)); } return newRandomStr.toString(); }
Example 6
Source File: CertificateHelper.java From signer with GNU Lesser General Public License v3.0 | 5 votes |
public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator generator = KeyPairGenerator.getInstance(KEYGEN_ALGORITHM/* , PROVIDER_NAME */); SecureRandom secureRandom = SecureRandom .getInstance(SECURE_RANDOM_ALGORITHM/* , PROVIDER_NAME */); generator.initialize(keySize, secureRandom); return generator.generateKeyPair(); }
Example 7
Source File: AesEncryption.java From AndroidAppCodeFramework with Apache License 2.0 | 5 votes |
private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed); kgen.init(128, sr); // 192 and 256 bits may not be available return kgen.generateKey().getEncoded(); }
Example 8
Source File: SecureRandomStrengthener.java From guarda-android-wallets with GNU General Public License v3.0 | 5 votes |
public SecureRandom generateAndSeedRandomNumberGenerator() { final SecureRandom secureRandom; try { secureRandom = SecureRandom.getInstance(this.algorithm); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException("PRNG is not available", e); } reseed(secureRandom); return secureRandom; }
Example 9
Source File: SecurityUtils.java From Alice-LiveMan with GNU Affero General Public License v3.0 | 5 votes |
public static byte[] getGenerateKey() throws NoSuchAlgorithmException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(liveManSetting.getEncodeKey().getBytes()); kgen.init(128, secureRandom); return kgen.generateKey().getEncoded(); }
Example 10
Source File: KeysManagerImpl.java From cloudstack with Apache License 2.0 | 5 votes |
private static String getBase64EncodedRandomKey(int nBits) { SecureRandom random; try { random = SecureRandom.getInstance("SHA1PRNG"); byte[] keyBytes = new byte[nBits / 8]; random.nextBytes(keyBytes); return Base64.encodeBase64URLSafeString(keyBytes); } catch (NoSuchAlgorithmException e) { s_logger.error("Unhandled exception: ", e); } return null; }
Example 11
Source File: AesCbcWithIntegrity.java From Iron with Apache License 2.0 | 5 votes |
private static byte[] randomBytes(int length) throws GeneralSecurityException { fixPrng(); SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); byte[] b = new byte[length]; random.nextBytes(b); return b; }
Example 12
Source File: DESHelper.java From open-capacity-platform with Apache License 2.0 | 5 votes |
public static String decryptDES(final byte[] data, final String key) { try { final SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); final DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8")); final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); final SecretKey secretKey = keyFactory.generateSecret(desKeySpec); final Cipher cipher = Cipher.getInstance("DES"); cipher.init(2, secretKey, random); return new String(cipher.doFinal(data), "UTF-8"); } catch (Exception e) { e.printStackTrace(); return null; } }
Example 13
Source File: SelfSeed.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) { try { SecureRandom sr1 = SecureRandom.getInstance("SHA1PRNG"); sr1.setSeed(seed); byte randomBytes[] = new byte[NUM_BYTES]; sr1.nextBytes(randomBytes); SecureRandom sr2 = new SecureRandom(seed); if (sr2.getAlgorithm().equals("SHA1PRNG") == false) { System.out.println("Default PRNG is not SHA1PRNG, skipping test"); return; } byte otherRandomBytes[] = new byte[NUM_BYTES]; sr2.nextBytes(otherRandomBytes); // make sure the random bytes generated are the same for (int i = 0; i < NUM_BYTES; i++) { if (randomBytes[i] != otherRandomBytes[i]) throw new SecurityException("FAILURE: " + "Returned bytes not equal"); } // success } catch (Exception e) { throw new SecurityException("FAILURE: " + e.toString()); } }
Example 14
Source File: VMInstanceVO.java From cloudstack with Apache License 2.0 | 5 votes |
public VMInstanceVO(long id, long serviceOfferingId, String name, String instanceName, Type type, Long vmTemplateId, HypervisorType hypervisorType, long guestOSId, long domainId, long accountId, long userId, boolean haEnabled) { this.id = id; hostName = name != null ? name : uuid; if (vmTemplateId != null) { templateId = vmTemplateId; } this.instanceName = instanceName; this.type = type; this.guestOSId = guestOSId; this.haEnabled = haEnabled; state = State.Stopped; this.accountId = accountId; this.domainId = domainId; this.serviceOfferingId = serviceOfferingId; this.hypervisorType = hypervisorType; this.userId = userId; limitCpuUse = false; try { SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] randomBytes = new byte[16]; random.nextBytes(randomBytes); vncPassword = Base64.encodeBase64URLSafeString(randomBytes); } catch (NoSuchAlgorithmException e) { s_logger.error("Unexpected exception in SecureRandom Algorithm selection ", e); } }
Example 15
Source File: NKeyTests.java From nats.java with Apache License 2.0 | 5 votes |
@Test(expected=IllegalArgumentException.class) public void testEncodeSeedSize() throws Exception { byte[] bytes = new byte[48]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); random.nextBytes(bytes); NKey.encodeSeed(NKey.Type.ACCOUNT, bytes); assertFalse(true); }
Example 16
Source File: Comman.java From XERUNG with Apache License 2.0 | 5 votes |
public String random(int size) { StringBuilder generatedToken = new StringBuilder(); try { SecureRandom number = SecureRandom.getInstance("SHA1PRNG"); // Generate 20 integers 0..20 for (int i = 0; i < size; i++) { generatedToken.append(number.nextInt(9)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return generatedToken.toString(); }
Example 17
Source File: SeedGeneratorChoice.java From openjdk-8 with GNU General Public License v2.0 | 4 votes |
public static void main(String... arguments) throws Exception { byte[] bytes; SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); bytes = prng.generateSeed(1); }
Example 18
Source File: CertificateUtils.java From keycloak with Apache License 2.0 | 4 votes |
/** * Generates version 3 {@link java.security.cert.X509Certificate}. * * @param keyPair the key pair * @param caPrivateKey the CA private key * @param caCert the CA certificate * @param subject the subject name * * @return the x509 certificate * * @throws Exception the exception */ public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert, String subject) throws Exception { try { X500Name subjectDN = new X500Name("CN=" + subject); // Serial Number SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt())); // Validity Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3); // SubjectPublicKeyInfo SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic() .getEncoded())); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo); DigestCalculator digCalc = new BcDigestCalculatorProvider() .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc); // Subject Key Identifier certGen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo)); // Authority Key Identifier certGen.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo)); // Key Usage certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); // Extended Key Usage KeyPurposeId[] EKU = new KeyPurposeId[2]; EKU[0] = KeyPurposeId.id_kp_emailProtection; EKU[1] = KeyPurposeId.id_kp_serverAuth; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU)); // Basic Constraints certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); // Content Signer ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC").build(caPrivateKey); // Certificate return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen)); } catch (Exception e) { throw new RuntimeException("Error creating X509v3Certificate.", e); } }
Example 19
Source File: ConnectionIT.java From snowflake-jdbc with Apache License 2.0 | 4 votes |
@Test @ConditionalIgnore(condition = RunningOnGithubAction.class) public void testDifferentKeyLength() throws Exception { Map<String, String> parameters = getConnectionParameters(); String testUser = parameters.get("user"); Integer[] testCases = {2048, 4096, 8192}; KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); for (Integer keyLength : testCases) { keyPairGenerator.initialize(keyLength, random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); Connection connection = getConnection(); Statement statement = connection.createStatement(); statement.execute("use role accountadmin"); String encodePublicKey = Base64.encodeBase64String(publicKey.getEncoded()); statement.execute(String.format( "alter user %s set rsa_public_key='%s'", testUser, encodePublicKey)); connection.close(); String uri = parameters.get("uri"); Properties properties = new Properties(); properties.put("account", parameters.get("account")); properties.put("user", testUser); properties.put("ssl", parameters.get("ssl")); properties.put("port", parameters.get("port")); properties.put("role", "accountadmin"); // test correct private key one properties.put("privateKey", privateKey); connection = DriverManager.getConnection(uri, properties); connection.createStatement().execute( String.format("alter user %s unset rsa_public_key", testUser)); connection.close(); } }
Example 20
Source File: RandomDataImpl.java From astor with GNU General Public License v2.0 | 2 votes |
/** * Sets the PRNG algorithm for the underlying SecureRandom instance using * the Security Provider API. The Security Provider API is defined in <a * href = * "http://java.sun.com/j2se/1.3/docs/guide/security/CryptoSpec.html#AppA"> * Java Cryptography Architecture API Specification & Reference.</a> * <p> * <strong>USAGE NOTE:</strong> This method carries <i>significant</i> * overhead and may take several seconds to execute. * </p> * * @param algorithm * the name of the PRNG algorithm * @param provider * the name of the provider * @throws NoSuchAlgorithmException * if the specified algorithm is not available * @throws NoSuchProviderException * if the specified provider is not installed */ public void setSecureAlgorithm(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { secRand = SecureRandom.getInstance(algorithm, provider); }