Java Code Examples for java.security.SecureRandom#generateSeed()

The following examples show how to use java.security.SecureRandom#generateSeed() . 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: PBECoder.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void test1() throws Exception {

		// 产生盐
		SecureRandom secureRandom = new SecureRandom();
		byte[] salt = secureRandom.generateSeed(8); // 盐长度必须为8字节

		// 产生Key
		String password = "123456";
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
		SecretKey secretKey = keyFactory.generateSecret(keySpec);

		PBEParameterSpec paramSpec = new PBEParameterSpec(salt, ITERATION_COUNT);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);

		byte[] plaintext = "Hello World".getBytes();
		byte[] ciphertext = cipher.doFinal(plaintext);
		new String(ciphertext);
	}
 
Example 2
Source File: LunaConnection.java    From credhub with Apache License 2.0 6 votes vote down vote up
public LunaConnection(final EncryptionConfiguration lunaProviderConfiguration) throws Exception {
  super();
  this.lunaProviderConfiguration = lunaProviderConfiguration;
  provider = (Provider) Class.forName("com.safenetinc.luna.provider.LunaProvider").newInstance();
  Security.addProvider(provider);
  lunaSlotManager = Class.forName("com.safenetinc.luna.LunaSlotManager")
    .getDeclaredMethod("getInstance").invoke(null);

  reconnect();

  // https://www.pivotaltracker.com/story/show/148107855
  // SecureRandom seed is 440 bits in accordance with NIST Special Publication 800-90A Revision 1, section 10.1
  // http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf
  final SecureRandom lunaRandom = SecureRandom.getInstance("LunaRNG");
  secureRandom = SecureRandom.getInstance("SHA1PRNG");
  final byte[] seed = lunaRandom.generateSeed(55);
  secureRandom.setSeed(seed); // 55b * 8 = 440B

  aesKeyGenerator = KeyGenerator.getInstance("AES", provider);
  aesKeyGenerator.init(128);
}
 
Example 3
Source File: RandomServlet.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
  int randomCount = parseParameter(request.getParameter("randomCount"));
  int byteCount = parseParameter(request.getParameter("byteCount"));
  int seedByteCount = parseParameter(request.getParameter("seedByteCount"));

  for (int i = 0; i < randomCount; i++) {
    SecureRandom random = new SecureRandom();
    if (byteCount > 0) {
      random.nextBytes(new byte[byteCount]);
    }
    if (seedByteCount > 0) {
      random.generateSeed(seedByteCount);
    }
  }
}
 
Example 4
Source File: PasswordUtil.java    From jeecg-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节
 * 
 * @return byte[] 盐值
 * */
public static byte[] getSalt() throws Exception {
	// 实例化安全随机数
	SecureRandom random = new SecureRandom();
	// 产出盐
	return random.generateSeed(8);
}
 
Example 5
Source File: StrongSeedReader.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void testSeed(String alg) throws Exception {
    System.out.println("Testing: " + alg);
    SecureRandom sr = SecureRandom.getInstance(alg);
    byte[] ba = sr.generateSeed(20);

    // We should get back a bunch of zeros from the file.
    for (byte b : ba) {
        if (b != 0) {
            throw new Exception("Byte != 0");
        }
    }
}
 
Example 6
Source File: KdbxHeader.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a default KDBX header
 */
public KdbxHeader() {
    SecureRandom random = new SecureRandom();
    cipherUuid = AES_CIPHER;
    compressionFlags = CompressionFlags.GZIP;
    masterSeed = random.generateSeed(32);
    transformSeed = random.generateSeed(32);
    transformRounds = 6000;
    encryptionIv = random.generateSeed(16);
    protectedStreamKey = random.generateSeed(32);
    streamStartBytes = new byte[32];
    protectedStreamAlgorithm = ProtectedStreamAlgorithm.SALSA_20;
}
 
Example 7
Source File: PasswordUtil.java    From teaching with Apache License 2.0 5 votes vote down vote up
/**
 * 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节
 * 
 * @return byte[] 盐值
 * */
public static byte[] getSalt() throws Exception {
	// 实例化安全随机数
	SecureRandom random = new SecureRandom();
	// 产出盐
	return random.generateSeed(8);
}
 
Example 8
Source File: StrongSeedReader.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testSeed(String alg) throws Exception {
    System.out.println("Testing: " + alg);
    SecureRandom sr = SecureRandom.getInstance(alg);
    byte[] ba = sr.generateSeed(20);

    // We should get back a bunch of zeros from the file.
    for (byte b : ba) {
        if (b != 0) {
            throw new Exception("Byte != 0");
        }
    }
}
 
Example 9
Source File: StrongSeedReader.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testSeed(String alg) throws Exception {
    System.out.println("Testing: " + alg);
    SecureRandom sr = SecureRandom.getInstance(alg);
    byte[] ba = sr.generateSeed(20);

    // We should get back a bunch of zeros from the file.
    for (byte b : ba) {
        if (b != 0) {
            throw new Exception("Byte != 0");
        }
    }
}
 
Example 10
Source File: GoogleAuthenticatorUtil.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public static String generateSecretKey() {  
    SecureRandom sr = null;  
    try {  
        sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);  
        sr.setSeed(Base64.decodeBase64(SEED));  
        byte[] buffer = sr.generateSeed(SECRET_SIZE);   
        Base32 codec = new Base32();  
        byte[] bEncodedKey = codec.encode(buffer);  
        String encodedKey = new String(bEncodedKey);  
        return encodedKey;  
    }catch (NoSuchAlgorithmException e) {  
        // should never occur... configuration error  
    }  
    return null;  
}
 
Example 11
Source File: PasswordUtil.java    From jeecg-boot-with-activiti with MIT License 5 votes vote down vote up
/**
 * 获取加密算法中使用的盐值,解密中使用的盐值必须与加密中使用的相同才能完成操作. 盐长度必须为8字节
 * 
 * @return byte[] 盐值
 * */
public static byte[] getSalt() throws Exception {
	// 实例化安全随机数
	SecureRandom random = new SecureRandom();
	// 产出盐
	return random.generateSeed(8);
}
 
Example 12
Source File: StrongSeedReader.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testSeed(String alg) throws Exception {
    System.out.println("Testing: " + alg);
    SecureRandom sr = SecureRandom.getInstance(alg);
    byte[] ba = sr.generateSeed(20);

    // We should get back a bunch of zeros from the file.
    for (byte b : ba) {
        if (b != 0) {
            throw new Exception("Byte != 0");
        }
    }
}
 
Example 13
Source File: SeedGeneratorChoice.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... arguments) throws Exception {
    byte[] bytes;
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    bytes = prng.generateSeed(1);
}
 
Example 14
Source File: SeedGeneratorChoice.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... arguments) throws Exception {
    byte[] bytes;
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    bytes = prng.generateSeed(1);
}
 
Example 15
Source File: ApiTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Test a possible set of SecureRandom API for a SecureRandom instance.
 * @param random SecureRandom instance
 * @param mech Mechanism used to create SecureRandom instance
 */
private static void verifyAPI(SecureRandom random, String mech)
        throws Exception {

    System.out.printf("%nTest SecureRandom mechanism: %s for provider: %s",
            mech, random.getProvider().getName());
    byte[] output = new byte[2];

    // Generate random number.
    random.nextBytes(output);

    // Seed the SecureRandom with a generated seed value of lesser size.
    byte[] seed = random.generateSeed(1);
    random.setSeed(seed);
    random.nextBytes(output);

    // Seed the SecureRandom with a fixed seed value.
    random.setSeed(SEED);
    random.nextBytes(output);

    // Seed the SecureRandom with a larger seed value.
    seed = random.generateSeed(128);
    random.setSeed(seed);
    random.nextBytes(output);

    // Additional operation only supported for DRBG based SecureRandom.
    // Execute the code block and expect to pass for DRBG. If it will fail
    // then it should fail with specified exception type. Else the case
    // will be considered as a test case failure.
    matchExc(() -> {
        random.reseed();
        random.nextBytes(output);
    },
            isDRBG(mech),
            UnsupportedOperationException.class,
            String.format("PASS - Unsupported reseed() method for "
                    + "SecureRandom Algorithm %s ", mech));

    matchExc(() -> {
        random.reseed(DrbgParameters.reseed(false, new byte[]{}));
        random.nextBytes(output);
    },
            isDRBG(mech),
            UnsupportedOperationException.class,
            String.format("PASS - Unsupported reseed(param) method for "
                    + "SecureRandom Algorithm %s ", mech));

    matchExc(() -> {
        random.reseed(DrbgParameters.reseed(true, new byte[]{}));
        random.nextBytes(output);
    },
            isDRBG(mech),
            !isSupportPR(mech, random) ? IllegalArgumentException.class
                    : UnsupportedOperationException.class,
            String.format("PASS - Unsupported or illegal reseed(param) "
                    + "method for SecureRandom Algorithm %s ", mech));

    matchExc(() -> random.nextBytes(output,
            DrbgParameters.nextBytes(-1, false, new byte[]{})),
            isDRBG(mech),
            UnsupportedOperationException.class,
            String.format("PASS - Unsupported nextBytes(out, nextByteParam)"
                    + " method for SecureRandom Algorithm %s ", mech));

    matchExc(() -> random.nextBytes(output,
            DrbgParameters.nextBytes(-1, true, new byte[]{})),
            isDRBG(mech),
            !isSupportPR(mech, random) ? IllegalArgumentException.class
                    : UnsupportedOperationException.class,
            String.format("PASS - Unsupported or illegal "
                    + "nextBytes(out, nextByteParam) method for "
                    + "SecureRandom Algorithm %s ", mech));

    matchExc(() -> {
        random.reseed(null);
        random.nextBytes(output);
    },
            !SHOULD_PASS,
            IllegalArgumentException.class,
            "PASS - Test is expected to fail when parameter for reseed() "
            + "is null");

    matchExc(() -> random.nextBytes(output, null),
            !SHOULD_PASS,
            IllegalArgumentException.class,
            "PASS - Test is expected to fail when parameter for nextBytes()"
            + " is null");

}
 
Example 16
Source File: SeedGeneratorChoice.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... arguments) throws Exception {
    byte[] bytes;
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    bytes = prng.generateSeed(1);
}
 
Example 17
Source File: SeedGeneratorChoice.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... arguments) throws Exception {
    byte[] bytes;
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    bytes = prng.generateSeed(1);
}
 
Example 18
Source File: SeedGeneratorChoice.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... arguments) throws Exception {
    byte[] bytes;
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    bytes = prng.generateSeed(1);
}
 
Example 19
Source File: SeedGeneratorChoice.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String... arguments) throws Exception {
    byte[] bytes;
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    bytes = prng.generateSeed(1);
}
 
Example 20
Source File: EbicsUtils.java    From axelor-open-suite with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Generates a random nonce.
 *
 * <p>EBICS Specification 2.4.2 - 11.6 Generation of the transaction IDs:
 *
 * <p>Transaction IDs are cryptographically-strong random numbers with a length of 128 bits. This
 * means that the likelihood of any two bank systems using the same transaction ID at the same
 * time is sufficiently small.
 *
 * <p>Transaction IDs are generated by cryptographic pseudo-random number generators (PRNG) that
 * have been initialized with a real random number (seed). The entropy of the seed should be at
 * least 100 bits.
 *
 * @return a random nonce.
 * @throws EbicsException nonce generation fails.
 */
public static byte[] generateNonce() throws AxelorException {
  SecureRandom secureRandom;

  try {
    secureRandom = SecureRandom.getInstance("SHA1PRNG");
    return secureRandom.generateSeed(16);
  } catch (NoSuchAlgorithmException e) {
    throw new AxelorException(e.getCause(), TraceBackRepository.TYPE_FUNCTIONNAL, e.getMessage());
  }
}