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: AbstractMemoryHttpDataTest.java    From netty-4.1.22 with 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
Source File: DSAParameterGenerator.java    From jdk8u-jdk with 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
Source File: PbmMacCmpCaClient.java    From xipki with 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
Source File: ECKey.java    From gsc-core with 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
Source File: AsyncHttpClientTest.java    From datakernel with 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
Source File: MD5Utils.java    From fun-generator with 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
Source File: ParameterCache.java    From dragonwell8_jdk with 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
Source File: IntentWithGesturesHandler.java    From delion with 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
Source File: sectionZeroAdapter.java    From UltimateRecyclerView with 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
Source File: HttpClientConfig.java    From Pixiv-Illustration-Collection-Backend with 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
Source File: GroupDatabase.java    From mollyim-android with 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
Source File: AESUtil.java    From taoshop with 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
Source File: CryptUtil.java    From PowerFileExplorer with 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
Source File: GF2Matrix.java    From RipplePower with 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
Source File: KerberosClientKeyExchangeImpl.java    From jdk8u60 with 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
Source File: SecureRandomStrengthener.java    From guarda-android-wallets with 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
Source File: DSAKeyPairGenerator.java    From openjdk-jdk9 with 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
Source File: RevocationHashTest.java    From thunder with 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
Source File: Cryptor.java    From secure-preferences with 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
Source File: SupportKeyUril.java    From Android with 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
Source File: GroupCipherTest.java    From libsignal-protocol-java with 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
Source File: MemoryPasswordSafe.java    From consulo with 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
Source File: BaseWrapCipher.java    From RipplePower with 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
Source File: TestProxyUsers.java    From big-c with 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
Source File: AESCrypto.java    From wind-im with 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
Source File: SelfSignedCaCertificate.java    From nomulus with 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
Source File: PasswordHash.java    From xipki with 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
Source File: clientUtil.java    From fido2 with 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
Source File: BCECUtil.java    From gmhelper with 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
Source File: JDKAlgorithmParameterGenerator.java    From TorrentEngine with 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;
     }