java.security.SecureRandom Java Examples
The following examples show how to use
java.security.SecureRandom.
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: IntentWithGesturesHandler.java From delion with Apache License 2.0 | 6 votes |
private IntentWithGesturesHandler() { mSecureRandomInitializer = new AsyncTask<Void, Void, SecureRandom>() { // SecureRandomInitializer addresses the bug in SecureRandom that "TrulyRandom" // warns about, so this lint warning can safely be suppressed. @SuppressLint("TrulyRandom") @Override protected SecureRandom doInBackground(Void... params) { SecureRandom secureRandom = null; try { secureRandom = SecureRandom.getInstance("SHA1PRNG"); SecureRandomInitializer.initialize(secureRandom); } catch (NoSuchAlgorithmException e) { Log.e(TAG, "Cannot create SecureRandom", e); } catch (IOException ioe) { Log.e(TAG, "Cannot initialize SecureRandom", ioe); } return secureRandom; } }.execute(); }
Example #2
Source File: ParameterCache.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * Return DH parameters for the given keylength. Uses cache if possible, * generates new parameters and adds them to the cache otherwise. */ public static DHParameterSpec getDHParameterSpec(int keyLength, SecureRandom random) throws NoSuchAlgorithmException, InvalidParameterSpecException { DHParameterSpec spec = getCachedDHParameterSpec(keyLength); if (spec != null) { return spec; } AlgorithmParameterGenerator gen = AlgorithmParameterGenerator.getInstance("DH"); gen.init(keyLength, random); AlgorithmParameters params = gen.generateParameters(); spec = params.getParameterSpec(DHParameterSpec.class); dhCache.put(Integer.valueOf(keyLength), spec); return spec; }
Example #3
Source File: PbmMacCmpCaClient.java From xipki with Apache License 2.0 | 6 votes |
@Override protected ProtectedPKIMessage build(ProtectedPKIMessageBuilder builder) throws Exception { builder.setSenderKID(kid); byte[] salt = new byte[64]; new SecureRandom().nextBytes(salt); PBMParameter pbmParameter = new PBMParameter(salt, requestOwf, requestInterationCount, requestMac); try { PKMACBuilder pkMacBuilder = new PKMACBuilder(new JcePKMACValuesCalculator()); pkMacBuilder.setParameters(pbmParameter); return builder.build(pkMacBuilder.build(password)); } catch (CRMFException ex) { throw new CMPException(ex.getMessage(), ex); } }
Example #4
Source File: ECKey.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
/** * Generate a new keypair using the given Java Security Provider. * * <p>All private key operations will use the provider. */ public ECKey(Provider provider, SecureRandom secureRandom) { this.provider = provider; final KeyPairGenerator keyPairGen = ECKeyPairGenerator.getInstance(provider, secureRandom); final KeyPair keyPair = keyPairGen.generateKeyPair(); this.privKey = keyPair.getPrivate(); final PublicKey pubKey = keyPair.getPublic(); if (pubKey instanceof BCECPublicKey) { pub = ((BCECPublicKey) pubKey).getQ(); } else if (pubKey instanceof ECPublicKey) { pub = extractPublicKey((ECPublicKey) pubKey); } else { throw new AssertionError( "Expected Provider " + provider.getName() + " to produce a subtype of ECPublicKey, found " + pubKey.getClass()); } }
Example #5
Source File: DSAParameterGenerator.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * Initializes this parameter generator for a certain strength * and source of randomness. * * @param strength the strength (size of prime) in bits * @param random the source of randomness */ protected void engineInit(int strength, SecureRandom random) { if ((strength >= 512) && (strength <= 1024) && (strength % 64 == 0)) { this.valueN = 160; } else if (strength == 2048) { this.valueN = 224; // } else if (strength == 3072) { // this.valueN = 256; } else { throw new InvalidParameterException ("Prime size should be 512 - 1024, or 2048"); } this.valueL = strength; this.seedLen = valueN; this.random = random; }
Example #6
Source File: AESUtil.java From taoshop with Apache License 2.0 | 6 votes |
/** * 解密 * @param encryptBytes * @param decryptKey * @return * @throws Exception */ public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); //防止linux下 随机生成key SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" ); secureRandom.setSeed(decryptKey.getBytes()); kgen.init(128, secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); Cipher cipher = Cipher.getInstance("AES");// 创建密码器 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 byte[] result = cipher.doFinal(encryptBytes); return new String(result); }
Example #7
Source File: AbstractMemoryHttpDataTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
/** * Provide content into HTTP data with input stream. * * @throws Exception In case of any exception. */ @Test public void testSetContentFromStream() throws Exception { Random random = new SecureRandom(); for (int i = 0; i < 20; i++) { // Generate input data bytes. int size = random.nextInt(Short.MAX_VALUE); byte[] bytes = new byte[size]; random.nextBytes(bytes); // Generate parsed HTTP data block. TestHttpData data = new TestHttpData("name", UTF_8, 0); data.setContent(new ByteArrayInputStream(bytes)); // Validate stored data. ByteBuf buffer = data.getByteBuf(); assertEquals(0, buffer.readerIndex()); assertEquals(bytes.length, buffer.writerIndex()); assertArrayEquals(bytes, Arrays.copyOf(buffer.array(), bytes.length)); } }
Example #8
Source File: KerberosClientKeyExchangeImpl.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
/** * Creates an instance of KerberosClientKeyExchange consisting of the * Kerberos service ticket, authenticator and encrypted premaster secret. * Called by client handshaker. * * @param serverName name of server with which to do handshake; * this is used to get the Kerberos service ticket * @param protocolVersion Maximum version supported by client (i.e, * version it requested in client hello) * @param rand random number generator to use for generating pre-master * secret */ @Override public void init(String serverName, AccessControlContext acc, ProtocolVersion protocolVersion, SecureRandom rand) throws IOException { // Get service ticket KerberosTicket ticket = getServiceTicket(serverName, acc); encodedTicket = ticket.getEncoded(); // Record the Kerberos principals peerPrincipal = ticket.getServer(); localPrincipal = ticket.getClient(); // Optional authenticator, encrypted using session key, // currently ignored // Generate premaster secret and encrypt it using session key EncryptionKey sessionKey = new EncryptionKey( ticket.getSessionKeyType(), ticket.getSessionKey().getEncoded()); preMaster = new KerberosPreMasterSecret(protocolVersion, rand, sessionKey); }
Example #9
Source File: sectionZeroAdapter.java From UltimateRecyclerView with Apache License 2.0 | 6 votes |
@Override protected void withBindHolder(itemCommonBinder holder, String data, int position) { holder.textViewSample.setText(data + "just the sample data"); holder.item_view.setBackgroundColor(Color.parseColor("#AAffffff")); SecureRandom imgGen = new SecureRandom(); switch (imgGen.nextInt(3)) { case 0: holder.imageViewSample.setImageResource(R.drawable.scn1); break; case 1: holder.imageViewSample.setImageResource(R.drawable.jr13); break; case 2: holder.imageViewSample.setImageResource(R.drawable.jr16); break; } }
Example #10
Source File: MD5Utils.java From fun-generator with MIT License | 6 votes |
/** * 获得加密后的16进制形式口令 * * @param password password * @return String * @throws NoSuchAlgorithmException e */ public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException { byte[] pwd = null; SecureRandom random = new SecureRandom(); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); MessageDigest md = null; md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes(StandardCharsets.UTF_8)); byte[] digest = md.digest(); //因为要在口令的字节数组中存放盐,所以加上盐的字节长度 pwd = new byte[digest.length + SALT_LENGTH]; //将盐的字节拷贝到生成的加密口令字节数组的前12个字节,以便在验证口令时取出盐 System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); //将消息摘要拷贝到加密口令字节数组从第13个字节开始的字节 System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); //将字节数组格式加密后的口令转化为16进制字符串格式的口令 return byteToHexString(pwd); }
Example #11
Source File: HttpClientConfig.java From Pixiv-Illustration-Collection-Backend with Apache License 2.0 | 6 votes |
@Bean @Primary @Autowired public HttpClient httpClientWithOutProxy(TrustManager[] trustAllCertificates, ExecutorService httpclientExecutorService) throws NoSuchAlgorithmException, KeyManagementException { SSLParameters sslParams = new SSLParameters(); sslParams.setEndpointIdentificationAlgorithm(""); SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCertificates, new SecureRandom()); return HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) // .sslParameters(sslParams) // .sslContext(sc) .connectTimeout(Duration.ofSeconds(30)) // .proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 8888))) .executor(httpclientExecutorService) .followRedirects(HttpClient.Redirect.NEVER) .build(); }
Example #12
Source File: GF2Matrix.java From RipplePower with Apache License 2.0 | 6 votes |
/** * Create a nxn random lower triangular matrix. * * @param n number of rows (and columns) * @param sr source of randomness */ private void assignRandomLowerTriangularMatrix(int n, SecureRandom sr) { numRows = n; numColumns = n; length = (n + 31) >>> 5; matrix = new int[numRows][length]; for (int i = 0; i < numRows; i++) { int q = i >>> 5; int r = i & 0x1f; int s = 31 - r; r = 1 << r; for (int j = 0; j < q; j++) { matrix[i][j] = sr.nextInt(); } matrix[i][q] = (sr.nextInt() >>> s) | r; for (int j = q + 1; j < length; j++) { matrix[i][j] = 0; } } }
Example #13
Source File: AsyncHttpClientTest.java From datakernel with Apache License 2.0 | 6 votes |
private static SSLContext createSslContext() { try { SSLContext instance = SSLContext.getInstance("TLSv1.2"); KeyStore keyStore = KeyStore.getInstance("JKS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); try (InputStream input = new FileInputStream(new File(KEYSTORE_PATH))) { keyStore.load(input, KEYSTORE_PASS.toCharArray()); } kmf.init(keyStore, KEY_PASS.toCharArray()); KeyStore trustStore = KeyStore.getInstance("JKS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); try (InputStream input = new FileInputStream(new File(TRUSTSTORE_PATH))) { trustStore.load(input, TRUSTSTORE_PASS.toCharArray()); } tmf.init(trustStore); instance.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); return instance; } catch (Exception e) { throw new AssertionError(e); } }
Example #14
Source File: GroupDatabase.java From mollyim-android with GNU General Public License v3.0 | 6 votes |
public GroupId.Mms getOrCreateMmsGroupForMembers(List<RecipientId> members) { Collections.sort(members); Cursor cursor = databaseHelper.getReadableDatabase().query(TABLE_NAME, new String[] {GROUP_ID}, MEMBERS + " = ? AND " + MMS + " = ?", new String[] {RecipientId.toSerializedList(members), "1"}, null, null, null); try { if (cursor != null && cursor.moveToNext()) { return GroupId.parseOrThrow(cursor.getString(cursor.getColumnIndexOrThrow(GROUP_ID))) .requireMms(); } else { GroupId.Mms groupId = GroupId.createMms(new SecureRandom()); create(groupId, members); return groupId; } } finally { if (cursor != null) cursor.close(); } }
Example #15
Source File: CryptUtil.java From PowerFileExplorer with GNU General Public License v3.0 | 6 votes |
/** * Encrypts AES key and set into preference */ private void setKeyPreference() throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeyException, UnrecoverableEntryException, NoSuchPaddingException, NoSuchProviderException, BadPaddingException, KeyStoreException, IllegalBlockSizeException { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); String encodedAesKey = preferences.getString(PREFERENCE_KEY, null); if (encodedAesKey==null) { // generate encrypted aes key and save to preference byte[] key = new byte[16]; SecureRandom secureRandom = new SecureRandom(); secureRandom.nextBytes(key); byte[] encryptedKey = encryptAESKey(key); encodedAesKey = Base64.encodeToString(encryptedKey, Base64.DEFAULT); preferences.edit().putString(PREFERENCE_KEY, encodedAesKey).apply(); } }
Example #16
Source File: GMSSKeyGenerationParameters.java From RipplePower with Apache License 2.0 | 5 votes |
public GMSSKeyGenerationParameters( SecureRandom random, GMSSParameters params) { // XXX key size? super(random, 1); this.params = params; }
Example #17
Source File: LogstashSchedulerContainer.java From logstash with Apache License 2.0 | 5 votes |
@Override protected CreateContainerCmd dockerCommand() { final String[] cmd = asList( "--mesos.master=" + mesosMasterIpAddress + ":5050", "--mesos.zookeeper.server=" + zookeeperIpAddress + ":2181", mesosRole.map(role -> "--mesos-role=" + role).orElse(null), "--enable.failover=false", elasticsearchHost.map(host -> "--logstash.elasticsearch-host=" + host).orElse(null), "--executor.heap-size=64", "--logstash.heap-size=256", "--enable.docker=" + useDocker, logstashConfig.map(file -> "--logstash.config-file=/config/" + file.getName()).orElse(null), withSyslog ? "--enable.syslog=true" : null ).stream().filter(StringUtils::isNotEmpty).toArray(String[]::new); final CreateContainerCmd containerCmd = dockerClient.createContainerCmd(SCHEDULER_IMAGE); logstashConfig.ifPresent(file -> { try { containerCmd.withBinds(new Bind(file.getParentFile().getCanonicalPath(), new Volume("/config"), AccessMode.ro)); } catch (IOException e) { throw new IllegalStateException("Path error", e); } }); return containerCmd .withName(SCHEDULER_NAME + "_" + new SecureRandom().nextInt()) .withExposedPorts(ExposedPort.tcp(9092)) .withCmd(cmd); }
Example #18
Source File: HttpClientBuilder.java From keycloak with Apache License 2.0 | 5 votes |
private SSLContext createSslContext( final String algorithm, final KeyStore keystore, final String keyPassword, final KeyStore truststore, final SecureRandom random) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { return SSLContexts.custom() .useProtocol(algorithm) .setSecureRandom(random) .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null) .loadTrustMaterial(truststore) .build(); }
Example #19
Source File: MacSameTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
@Override public void doTest(String algo) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException { Mac mac; try { mac = Mac.getInstance(algo, "SunJCE"); } catch (NoSuchAlgorithmException nsae) { // depending on Solaris configuration, // it can support HMAC or not with Mac System.out.println("Expected NoSuchAlgorithmException thrown: " + nsae); return; } byte[] plain = new byte[MESSAGE_SIZE]; for (int i = 0; i < MESSAGE_SIZE; i++) { plain[i] = (byte) (i % 256); } byte[] tail = new byte[plain.length - OFFSET]; System.arraycopy(plain, OFFSET, tail, 0, tail.length); SecureRandom srdm = new SecureRandom(); byte[] keyVal = new byte[KEY_SIZE]; srdm.nextBytes(keyVal); SecretKeySpec keySpec = new SecretKeySpec(keyVal, "HMAC"); mac.init(keySpec); byte[] result1 = mac.doFinal(plain); mac.reset(); mac.update(plain[0]); mac.update(plain, 1, OFFSET - 1); byte[] result2 = mac.doFinal(tail); if (!java.util.Arrays.equals(result1, result2)) { throw new RuntimeException("result1 and result2 are not the same"); } }
Example #20
Source File: DSAKeyPairGenerator.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
private void initialize0(DSAParameterSpec params, SecureRandom random) { int sizeP = params.getP().bitLength(); int sizeQ = params.getQ().bitLength(); checkStrength(sizeP, sizeQ); this.plen = sizeP; this.qlen = sizeQ; this.params = params; this.random = random; this.forceNewParameters = false; }
Example #21
Source File: RandomCompatTest.java From Lightweight-Stream-API with Apache License 2.0 | 5 votes |
@Test public void testRandomConstructor() { assertNotNull(new RandomCompat(1).getRandom()); assertNotNull(new RandomCompat().getRandom()); final RandomCompat secureRandom = new RandomCompat(new SecureRandom()); assertThat(secureRandom.getRandom(), instanceOf(SecureRandom.class)); }
Example #22
Source File: KerberosClientKeyExchange.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
public void init(ProtocolVersion protocolVersion, ProtocolVersion clientVersion, SecureRandom rand, HandshakeInStream input, AccessControlContext acc, Object ServiceCreds) throws IOException { if (impl != null) { impl.init(protocolVersion, clientVersion, rand, input, acc, ServiceCreds); } }
Example #23
Source File: Util.java From smartcard-reader with GNU General Public License v3.0 | 5 votes |
public static byte[] generateRandomBytes(int numBytes) { // TODO: get bytes from a hardware RNG, or set seed byte[] rndBytes = new byte[numBytes]; SecureRandom random = new SecureRandom(); random.nextBytes(rndBytes); return rndBytes; }
Example #24
Source File: TlsWrapper.java From soapbox-race with GNU General Public License v2.0 | 5 votes |
private static SSLContext getSslContext() { SSLContext sslctx = null; try { sslctx = SSLContext.getInstance("TLS"); sslctx.init(null, getTrustAll(), new SecureRandom()); } catch (Exception e) { e.printStackTrace(); } return sslctx; }
Example #25
Source File: NetworkTools.java From MyBox with Apache License 2.0 | 5 votes |
public static boolean download(String address, File targetFile) { try { if (targetFile == null || address == null) { return false; } File tmpFile = FileTools.getTempFile(); URL url = new URL(address); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); SSLContext sc = SSLContext.getInstance(CommonValues.HttpsProtocal); sc.init(null, trustAllManager(), new SecureRandom()); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(trustAllVerifier()); InputStream inStream = conn.getInputStream(); FileOutputStream fs = new FileOutputStream(tmpFile); byte[] buf = new byte[1204]; int len; while ((len = inStream.read(buf)) != -1) { fs.write(buf, 0, len); } if (targetFile.exists()) { targetFile.delete(); } tmpFile.renameTo(targetFile); return targetFile.exists(); } catch (Exception e) { logger.error(e.toString()); return false; } }
Example #26
Source File: BaseKeyGenerator.java From RipplePower with Apache License 2.0 | 5 votes |
protected void engineInit( SecureRandom random) { if (random != null) { engine.init(new KeyGenerationParameters(random, defaultKeySize)); uninitialised = false; } }
Example #27
Source File: ParametersWithRandom.java From BiglyBT with GNU General Public License v2.0 | 5 votes |
public ParametersWithRandom( CipherParameters parameters, SecureRandom random) { this.random = random; this.parameters = parameters; }
Example #28
Source File: TestKGParity.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
public boolean runTest(Provider p, String algo) throws Exception { byte[] keyValue = null; try { // Initialization SecureRandom sRdm = new SecureRandom(); KeyGenerator kg = KeyGenerator.getInstance(algo, p); kg.init(sRdm); // Generate a SecretKey and retrieve its value keyValue = kg.generateKey().getEncoded(); // Verify its parity in the unit of byte for (int i = 0; i < keyValue.length; i++) { if (!checkParity(keyValue[i])) { out.println("Testing: " + p.getName() + "/" + algo + " failed when verify its parity in the unit of byte:" + TestUtility.hexDump(keyValue, i)); return false; } } return true; } catch (Exception ex) { out.println("Testing: " + p.getName() + "/" + algo + " failed with unexpected exception"); ex.printStackTrace(); throw ex; } }
Example #29
Source File: JDKAlgorithmParameterGenerator.java From TorrentEngine with GNU General Public License v3.0 | 5 votes |
protected AlgorithmParameters engineGenerateParameters() { DSAParametersGenerator pGen = new DSAParametersGenerator(); if ( random != null ) { pGen.init(strength, 20, random); } else { pGen.init(strength, 20, new SecureRandom()); } DSAParameters p = pGen.generateParameters(); AlgorithmParameters params; try { params = AlgorithmParameters.getInstance("DSA", BouncyCastleProvider.PROVIDER_NAME); params.init(new DSAParameterSpec(p.getP(), p.getQ(), p.getG())); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; }
Example #30
Source File: BCECUtil.java From gmhelper with Apache License 2.0 | 5 votes |
/** * 生成ECC密钥对 * * @return ECC密钥对 */ public static AsymmetricCipherKeyPair generateKeyPairParameter( ECDomainParameters domainParameters, SecureRandom random) { ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(domainParameters, random); ECKeyPairGenerator keyGen = new ECKeyPairGenerator(); keyGen.init(keyGenerationParams); return keyGen.generateKeyPair(); }