在Java中使用SecureRandom

时间:2019-02-21 19:30:19

标签: java eclipse java-8

我正在尝试用Java导入SecureRamdom,但

import java.security.SecureRandom;

不起作用。我在Eclipse中使用Java SE 8。有人知道如何导入吗?

2 个答案:

答案 0 :(得分:5)

当然可以。 请看下面的代码:

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Momir Sarac
 */
public class SecureRandomExample {

    public static void main(String[] args) {

        try {
            // obtain a strong SecureRandom implementation from securerandom.strongAlgorithms property of java.security.Security
            // class
            SecureRandom secureRandom = SecureRandom.getInstanceStrong();
            // print the provided and algorithm obtained for this secureRandom 
            System.out.println("" + secureRandom.getProvider() + "\n" + secureRandom.getAlgorithm());
            //generate 16-long seed bytes
            //generate a given number of seed bytes (to seed other random number generators, for example):
            byte[] bytes = secureRandom.generateSeed(16);
            //print obtained bytes as string from array 
            System.out.println(Arrays.toString(bytes));
            //to get random bytes, a caller simply passes an array of any length, which is then filled with random bytes:
            secureRandom.nextBytes(bytes);
            //print obtained bytes as string from array 
            System.out.println(Arrays.toString(bytes));

        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(SecureRandomExample.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

答案 1 :(得分:0)

结果证明它确实有效。出于某种原因,eclipse只是将其突出显示为错误,即使它起作用。