Java Code Examples for java.security.SecureRandom

The following examples show how to use java.security.SecureRandom. These examples are extracted from open source projects.
Example 1
Project: netty-4.1.22   File: AbstractMemoryHttpDataTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 2
Project: jdk8u-jdk   File: DSAParameterGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
     * 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 3
Project: xipki   File: PbmMacCmpCaClient.java    License: Apache License 2.0 6 votes vote down vote up
@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
Project: gsc-core   File: ECKey.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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
Project: datakernel   File: AsyncHttpClientTest.java    License: Apache License 2.0 6 votes vote down vote up
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 6
Project: fun-generator   File: MD5Utils.java    License: MIT License 6 votes vote down vote up
/**
 * 获得加密后的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 7
Project: dragonwell8_jdk   File: ParameterCache.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 8
Project: delion   File: IntentWithGesturesHandler.java    License: Apache License 2.0 6 votes vote down vote up
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 9
Project: UltimateRecyclerView   File: sectionZeroAdapter.java    License: Apache License 2.0 6 votes vote down vote up
@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
Project: Pixiv-Illustration-Collection-Backend   File: HttpClientConfig.java    License: Apache License 2.0 6 votes vote down vote up
@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 11
Project: mollyim-android   File: GroupDatabase.java    License: GNU General Public License v3.0 6 votes vote down vote up
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 12
Project: taoshop   File: AESUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 解密
 * @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 13
Project: PowerFileExplorer   File: CryptUtil.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 14
Project: RipplePower   File: GF2Matrix.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 15
Project: jdk8u60   File: KerberosClientKeyExchangeImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 16
Project: guarda-android-wallets   File: SecureRandomStrengthener.java    License: GNU General Public License v3.0 5 votes vote down vote up
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 17
Project: openjdk-jdk9   File: DSAKeyPairGenerator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generate the private key component of the key pair using the
 * provided source of random bits. This method uses the random but
 * source passed to generate a seed and then calls the seed-based
 * generateX method.
 */
private BigInteger generateX(SecureRandom random, BigInteger q) {
    BigInteger x = null;
    byte[] temp = new byte[qlen];
    while (true) {
        random.nextBytes(temp);
        x = new BigInteger(1, temp).mod(q);
        if (x.signum() > 0 && (x.compareTo(q) < 0)) {
            return x;
        }
    }
}
 
Example 18
Project: thunder   File: RevocationHashTest.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void shouldPassBecauseOfNewMaster () throws Exception {
    byte[] secret = new byte[20];
    Random r = new SecureRandom();
    r.nextBytes(secret);

    RevocationHash revocationHash = new RevocationHash(0, 0, secret, secret);
    assertTrue(revocationHash.check());
}
 
Example 19
Project: secure-preferences   File: Cryptor.java    License: Apache License 2.0 5 votes vote down vote up
private Cryptor(SecurityConfig securityConfig){
    this.mSecurityConfig = securityConfig;
    this.mCipherService = CipherServiceImpl.getInstance(mSecurityConfig.getAlgorithm());

    // Generating Session Salt
    mSalt = new byte[mSecurityConfig.getSaltSize()];
    new SecureRandom().nextBytes(mSalt);

    // Generating Session Password
    mPassword = pbkdf2(mSalt);
}
 
Example 20
Project: Android   File: SupportKeyUril.java    License: MIT License 5 votes vote down vote up
/**
 * 16-32 binary random number
 * modify Random
 *
 * @return
 */
public static byte[] createrBinaryRandom() {
    Random random = new Random();
    int n = random.nextInt(17) + 16;
    byte[] byteRandom = SecureRandom.getSeed(n);
    return byteRandom;
}
 
Example 21
Project: libsignal-protocol-java   File: GroupCipherTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
private int randomInt() {
  try {
    return SecureRandom.getInstance("SHA1PRNG").nextInt(Integer.MAX_VALUE);
  } catch (NoSuchAlgorithmException e) {
    throw new AssertionError(e);
  }
}
 
Example 22
Project: consulo   File: MemoryPasswordSafe.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param project the project to use
 * @return the secret key used by provider
 */
@Override
protected byte[] key(Project project) {
  if (key.get() == null) {
    byte[] rnd = new byte[EncryptionUtil.SECRET_KEY_SIZE_BYTES * 16];
    new SecureRandom().nextBytes(rnd);
    key.compareAndSet(null, EncryptionUtil.genKey(EncryptionUtil.hash(rnd)));
  }
  return key.get();
}
 
Example 23
Project: RipplePower   File: BaseWrapCipher.java    License: Apache License 2.0 5 votes vote down vote up
protected void engineInit(
    int                 opmode,
    Key                 key,
    SecureRandom        random)
    throws InvalidKeyException
{
    try
    {
        engineInit(opmode, key, (AlgorithmParameterSpec)null, random);
    }
    catch (InvalidAlgorithmParameterException e)
    {
        throw new IllegalArgumentException(e.getMessage());
    }
}
 
Example 24
Project: big-c   File: TestProxyUsers.java    License: Apache License 2.0 5 votes vote down vote up
public static void loadTest(String ipString, int testRange) {
  Configuration conf = new Configuration();
  conf.set(
      DefaultImpersonationProvider.getTestProvider().
          getProxySuperuserGroupConfKey(REAL_USER_NAME),
      StringUtils.join(",", Arrays.asList(GROUP_NAMES)));

  conf.set(
      DefaultImpersonationProvider.getTestProvider().
          getProxySuperuserIpConfKey(REAL_USER_NAME),
      ipString
      );
  ProxyUsers.refreshSuperUserGroupsConfiguration(conf);


  // First try proxying a group that's allowed
  UserGroupInformation realUserUgi = UserGroupInformation
      .createRemoteUser(REAL_USER_NAME);
  UserGroupInformation proxyUserUgi = UserGroupInformation.createProxyUserForTesting(
      PROXY_USER_NAME, realUserUgi, GROUP_NAMES);

  long startTime = System.nanoTime();
  SecureRandom sr = new SecureRandom();
  for (int i=1; i < 1000000; i++){
    try {
      ProxyUsers.authorize(proxyUserUgi,  "1.2.3."+ sr.nextInt(testRange));
     } catch (AuthorizationException e) {
    }
  }
  long stopTime = System.nanoTime();
  long elapsedTime = stopTime - startTime;
  System.out.println(elapsedTime/1000000 + " ms");
}
 
Example 25
Project: wind-im   File: AESCrypto.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 通过key生成AES加密解密key
 * 
 * @param key
 * @return
 */
public static byte[] generateTSKey(String key) {
	try {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(key.getBytes(CharsetCoding.ISO_8859_1));
		kgen.init(128, secureRandom);
		SecretKey secretKey = kgen.generateKey();
		return secretKey.getEncoded();
	} catch (Exception e) {
		logger.error("generate ts key error by key=" + key, e);
	}
	return null;
}
 
Example 26
Project: nomulus   File: SelfSignedCaCertificate.java    License: Apache License 2.0 5 votes vote down vote up
static KeyPairGenerator createKeyPairGenerator() {
  try {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", PROVIDER);
    keyGen.initialize(2048, new SecureRandom());
    return keyGen;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 27
Project: xipki   File: PasswordHash.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a salted PBKDF2 hash of the password.
 *
 * @param password - the password to hash
 * @param saltSize - the size of salt in bytes
 * @param iterations - the iteration count (slowness factor)
 * @param dkSize - the length of the derived key
 * @return a salted PBKDF2 hash of the password
 */
public static String createHash(byte[] password, int saltSize, int iterations, int dkSize) {
  Args.notNull(password, "password");
  // Generate a random salt
  SecureRandom random = new SecureRandom();
  byte[] salt = new byte[saltSize];
  random.nextBytes(salt);

  // Hash the password
  byte[] hash = pbkdf2(password, salt, iterations, dkSize);
  // format iterations:salt:hash
  return iterations + ":" + toHex(salt) + ":" + toHex(hash);
}
 
Example 28
Project: fido2   File: clientUtil.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public String signObject(String input) throws FileNotFoundException, KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, NoSuchProviderException, InvalidKeyException, SignatureException {

        //Base64 decode input
        byte[] inputbytes = Base64.decodeBase64(input);

        KeyStore attks = KeyStore.getInstance("JCEKS");
        attks.load(getClass().getResourceAsStream(CSConstants.ATTESTATION_KEYSTORE), CSConstants.ATTESTATION_KEYSTORE_TOUCH_PASSWORD.toCharArray());

        //get Key
        PrivateKey prk = (PrivateKey) attks.getKey(CSConstants.ATTESTATION_PRIVATE_KEYALIAS, CSConstants.ATTESTATION_KEYSTORE_TOUCH_PASSWORD.toCharArray());

        //sign
        Signature sig = Signature.getInstance("SHA256withECDSA", "BCFIPS");
        sig.initSign(prk, new SecureRandom());
        sig.update(inputbytes);
        byte[] signedBytes = sig.sign();

        //verify locally
        //get certificate
        Certificate cert = attks.getCertificate(CSConstants.ATTESTATION_PRIVATE_KEYALIAS);
        PublicKey pkey = cert.getPublicKey();
        sig.initVerify(pkey);
        sig.update(inputbytes);
        if (sig.verify(signedBytes)) {
            return Base64.encodeBase64String(signedBytes);
        } else {
            return null;
        }

    }
 
Example 29
Project: gmhelper   File: BCECUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 生成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();
}
 
Example 30
Project: TorrentEngine   File: JDKAlgorithmParameterGenerator.java    License: GNU General Public License v3.0 5 votes vote down vote up
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 31
Project: jdk8u_jdk   File: TestKGParity.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 32
Project: BiglyBT   File: ParametersWithRandom.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ParametersWithRandom(
    CipherParameters    parameters,
    SecureRandom        random)
{
    this.random = random;
    this.parameters = parameters;
}
 
Example 33
Project: RipplePower   File: BaseKeyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
protected void engineInit(
    SecureRandom    random)
{
    if (random != null)
    {
        engine.init(new KeyGenerationParameters(random, defaultKeySize));
        uninitialised = false;
    }
}
 
Example 34
Project: MyBox   File: NetworkTools.java    License: Apache License 2.0 5 votes vote down vote up
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 35
Project: soapbox-race   File: TlsWrapper.java    License: GNU General Public License v2.0 5 votes vote down vote up
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 36
Project: Alpine   File: ApiKeyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates a cryptographically secure API key of the specified length.
 * @param chars the length of the API key to generate
 * @return a String representation of the API key
 */
public static String generate(final int chars) {
    final SecureRandom secureRandom = new SecureRandom();
    final char[] buff = new char[chars];
    for (int i = 0; i < chars; ++i) {
        if (i % 10 == 0) {
            secureRandom.setSeed(secureRandom.nextLong());
        }
        buff[i] = VALID_CHARACTERS[secureRandom.nextInt(VALID_CHARACTERS.length)];
    }
    return new String(buff);
}
 
Example 37
Project: java-n-IDE-for-Android   File: CertCreator.java    License: Apache License 2.0 5 votes vote down vote up
public static KeySet createKey(String keyAlgorithm, int keySize, String keyName,
                               String certSignatureAlgorithm, int certValidityYears, DistinguishedNameValues distinguishedNameValues) {
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlgorithm);
        keyPairGenerator.initialize(keySize);
        KeyPair KPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        X509Principal principal = distinguishedNameValues.getPrincipal();

        // generate a postitive serial number
        BigInteger serialNumber = BigInteger.valueOf(new SecureRandom().nextInt());
        while (serialNumber.compareTo(BigInteger.ZERO) < 0) {
            serialNumber = BigInteger.valueOf(new SecureRandom().nextInt());
        }
        v3CertGen.setSerialNumber(serialNumber);
        v3CertGen.setIssuerDN(principal);
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60L * 60L * 24L * 30L));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60L * 60L * 24L * 366L * (long) certValidityYears)));
        v3CertGen.setSubjectDN(principal);

        v3CertGen.setPublicKey(KPair.getPublic());
        v3CertGen.setSignatureAlgorithm(certSignatureAlgorithm);

        X509Certificate PKCertificate = v3CertGen.generate(KPair.getPrivate(), "BC");

        KeySet keySet = new KeySet();
        keySet.setName(keyName);
        keySet.setPrivateKey(KPair.getPrivate());
        keySet.setPublicKey(PKCertificate);
        return keySet;
    } catch (Exception x) {
        throw new RuntimeException(x.getMessage(), x);
    }
}
 
Example 38
Project: ripple-lib-java   File: BaseKeyGenerator.java    License: ISC License 5 votes vote down vote up
protected void engineInit(
    AlgorithmParameterSpec  params,
    SecureRandom            random)
throws InvalidAlgorithmParameterException
{
    throw new InvalidAlgorithmParameterException("Not Implemented");
}
 
Example 39
Project: hbase   File: HFileBlockDefaultEncodingContext.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param encoding encoding used
 * @param headerBytes dummy header bytes
 * @param fileContext HFile meta data
 */
public HFileBlockDefaultEncodingContext(DataBlockEncoding encoding, byte[] headerBytes,
    HFileContext fileContext) {
  this.encodingAlgo = encoding;
  this.fileContext = fileContext;
  Compression.Algorithm compressionAlgorithm =
      fileContext.getCompression() == null ? NONE : fileContext.getCompression();
  if (compressionAlgorithm != NONE) {
    compressor = compressionAlgorithm.getCompressor();
    compressedByteStream = new ByteArrayOutputStream();
    try {
      compressionStream =
          compressionAlgorithm.createPlainCompressionStream(
              compressedByteStream, compressor);
    } catch (IOException e) {
      throw new RuntimeException(
          "Could not create compression stream for algorithm "
              + compressionAlgorithm, e);
    }
  }

  Encryption.Context cryptoContext = fileContext.getEncryptionContext();
  if (cryptoContext != Encryption.Context.NONE) {
    cryptoByteStream = new ByteArrayOutputStream();
    iv = new byte[cryptoContext.getCipher().getIvLength()];
    new SecureRandom().nextBytes(iv);
  }

  dummyHeader = Preconditions.checkNotNull(headerBytes,
    "Please pass HConstants.HFILEBLOCK_DUMMY_HEADER instead of null for param headerBytes");
}
 
Example 40
Project: AndroidProjects   File: OkHttpClient.java    License: MIT License 5 votes vote down vote up
/**
 * Uses {@code request} to connect a new web socket.
 */
@Override
public WebSocket newWebSocket(Request request, WebSocketListener listener) {
    RealWebSocket webSocket = new RealWebSocket(request, listener, new SecureRandom());
    webSocket.connect(this);
    return webSocket;
}