📌  相关文章
📜  Java中的 SecureRandom getInstance() 方法及示例

📅  最后修改于: 2022-05-13 01:54:31.592000             🧑  作者: Mango

Java中的 SecureRandom getInstance() 方法及示例

getInstance(字符串算法)

Java.security.SecureRandom类的getInstance()方法用于返回实现指定随机数生成器 (RNG) 算法的 SecureRandom 对象。

此方法遍历已注册的安全提供者列表,从最喜欢的提供者开始。返回一个新的 SecureRandom 对象,该对象封装来自支持指定算法的第一个 Provider 的 SecureRandomSpi 实现。

句法:

public static SecureRandom 
getInstance( String algorithm ) 
throws NoSuchAlgorithmException

参数:该方法以标准的RNG算法为参数。

返回值:此方法返回新的SecureRandom对象。

异常:此方法抛出NoSuchAlgorithmException - 如果没有提供程序支持指定算法的 SecureRandomSpi 实现。

笔记:

  1. 这些程序不会在在线 IDE 上运行。
  2. 每次 Secure Random 类都会产生随机输出。

下面是说明getInstance()方法的示例:

示例 1:

// Java program to demonstrate
// nextBytes() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
        try {
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出:

Byte array before operation : [84, 97, 106, 109, 97, 104, 97, 108]
Byte array after operation : [124, -66, -62, -5, -71, -4, 30, 16]

示例 2:

// Java program to demonstrate
// getInstance() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
        try {
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
            System.out.println("Trying to get the instance of TAJMAHAL");
            SecureRandom sr = SecureRandom.getInstance("TAJMAHAL");
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}

输出:

Trying to get the instance of TAJMAHAL
Exception thrown : java.security.NoSuchAlgorithmException: TAJMAHAL SecureRandom not available

getInstance(字符串算法,Provider提供者)

Java.security.SecureRandom类的getInstance()方法用于返回实现指定随机数生成器 (RNG) 算法的 SecureRandom 对象。
返回一个封装来自指定 Provider 对象的 SecureRandomSpi 实现的新 SecureRandom 对象。请注意,指定的提供者对象不必在提供者列表中注册。

返回的 SecureRandom 对象尚未播种。要播种返回的对象,请调用 setSeed 方法。如果未调用 setSeed,则第一次调用 nextBytes 将强制 SecureRandom 对象自行播种。如果之前调用了 setSeed,则不会发生这种自播。

句法:

public static SecureRandom 
getInstance( String algorithm, Provider provider )
throws NoSuchAlgorithmException

参数:此方法将以下参数作为参数

  • algorithm – RNG 算法的名称。
  • 提供者——提供者。

返回值:此方法返回新的 SecureRandom 对象

异常:此方法抛出以下异常

  • NoSuchAlgorithmException –如果指定算法的 SecureRandomSpi 实现不能从指定的 Provider 对象获得。
  • IllegalArgumentException –如果指定的提供者为空。

    笔记:

    1. 这些程序不会在在线 IDE 上运行。
    2. 每次 Secure Random 类都会产生随机输出。

    下面是说明getInstance()方法的示例:

    示例 1:

    // Java program to demonstrate
    // getInstance() method
      
    import java.security.*;
    import java.util.*;
      
    public class GFG1 {
        public static void main(String[] argv)
        {
            try {
                // creating SecureRandom object
                SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
      
                // creating Provider object
                Provider pd = sr1.getProvider();
      
                // creating the object of SecureRandom and getting instance
                // By using getInstance() method
      
                SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", pd);
      
                // Declaring the string variable
                String str = "Tajmahal";
      
                // Declaring the byte Array
                // converting string into byte
                byte[] b = str.getBytes();
      
                // printing the byte array
                System.out.println("Byte array before operation : "
                                   + Arrays.toString(b));
      
                // generating user-specified number of random bytes
                // using nextBytes() method
                sr.nextBytes(b);
      
                // printing the new byte array
                System.out.println("Byte array after operation : "
                                   + Arrays.toString(b));
            }
      
            catch (NoSuchAlgorithmException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (ProviderException e) {
      
                System.out.println("Exception thrown : " + e);
            }
        }
    }
    

    输出:

    Byte array before operation : [84, 97, 106, 109, 97, 104, 97, 108]
    Byte array after operation : [109, 55, 116, -15, -83, 126, -128, 88]

    注意:以下程序在在线IDE中产生以下异常
    抛出异常: Java.security.ProviderException:初始化失败

    示例 2:

    // Java program to demonstrate
    // getInstance() method
      
    import java.security.*;
    import java.util.*;
      
    public class GFG1 {
        public static void main(String[] argv)
        {
            try {
                // creating SecureRandom object
                SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
      
                // creating Provider object
                Provider pd = sr1.getProvider();
      
                // creating the object of SecureRandom and getting instance
                // By using getInstance() method
                System.out.println("Trying to getting the instance of TAJMAHAL ");
                SecureRandom sr = SecureRandom.getInstance("TAJMAHAL", pd);
      
                // Declaring the string variable
                String str = "Tajmahal";
      
                // Declaring the byte Array
                // converting string into byte
                byte[] b = str.getBytes();
      
                // printing the byte array
                System.out.println("Byte array before operation : "
                                   + Arrays.toString(b));
      
                // generating user-specified number of random bytes
                // using nextBytes() method
                sr.nextBytes(b);
      
                // printing the new byte array
                System.out.println("Byte array after operation : "
                                   + Arrays.toString(b));
            }
      
            catch (NoSuchAlgorithmException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (ProviderException e) {
      
                System.out.println("Exception thrown : " + e);
            }
        }
    }
    

    输出:

    Trying to getting the instance of TAJMAHAL
    Exception thrown : java.security.NoSuchAlgorithmException: no such algorithm: TAJMAHAL for provider SUN

    getInstance(字符串算法,字符串提供者)

    Java.security.SecureRandom类的getInstance()方法用于返回实现指定随机数生成器 (RNG) 算法的 SecureRandom 对象。

    返回一个封装来自指定提供者的 SecureRandomSpi 实现的新 SecureRandom 对象。指定的提供者必须在安全提供者列表中注册。

    句法:

    public static SecureRandom 
    getInstance( String algorithm, String provider )
    throws NoSuchAlgorithmException, NoSuchProviderException

    参数:此方法将以下参数作为参数

    • algorithm – RNG 算法的名称。有关标准 RNG 算法名称的信息,请参阅Java Cryptography Architecture Standard Algorithm Name Documentation 中的 SecureRandom 部分。
    • 提供者——提供者的名称。

    返回值:此方法返回新的 SecureRandom 对象

    异常:此方法抛出以下异常

    • NoSuchAlgorithmException – 如果指定算法的 SecureRandomSpi 实现不能从指定的提供者处获得。
    • NoSuchProviderException – 如果指定的提供者未在安全提供者列表中注册。
    • IllegalArgumentException – 如果提供者名称为 null 或为空。

    笔记:

    1. 这些程序不会在在线 IDE 上运行。
    2. 每次 Secure Random 类都会产生随机输出。

    下面是说明getInstance()方法的示例:

    示例 1:

    // Java program to demonstrate
    // getInstance() method
      
    import java.security.*;
    import java.util.*;
      
    public class GFG1 {
        public static void
            main(String[] argv)
                throws NoSuchAlgorithmException,
                       NoSuchProviderException
        {
            try {
                // creating SecureRandom object
                SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
      
                // creating Provider object
                Provider pd = sr1.getProvider();
      
                // getting provider name
                // by using method getname()
                String provider = pd.getName();
      
                // getting algorithm name
                // by using     getAlgorithm() mathod
                String algo = sr1.getAlgorithm();
      
                // creating the object of SecureRandom and getting instance
                // By using getInstance() method
                SecureRandom sr = SecureRandom.getInstance(algo, provider);
      
                // Declaring the string variable
                String str = "Tajmahal";
      
                // Declaring the byte Array
                // converting string into byte
                byte[] b = str.getBytes();
      
                // printing the byte array
                System.out.println("Byte array before operation : "
                                   + Arrays.toString(b));
      
                // generating user-specified number of random bytes
                // using nextBytes() method
                sr.nextBytes(b);
      
                // printing the new byte array
                System.out.println("Byte array after operation : "
                                   + Arrays.toString(b));
            }
      
            catch (NoSuchAlgorithmException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (ProviderException e) {
      
                System.out.println("Exception thrown : " + e);
            }
        }
    }
    

    输出:

    Byte array before operation : [84, 97, 106, 109, 97, 104, 97, 108]
    Byte array after operation : [-11, 81, 39, 67, -95, -51, 115, -18]

    示例 2:

    // Java program to demonstrate
    // getInstance() method
      
    import java.security.*;
    import java.util.*;
      
    public class GFG1 {
        public static void
            main(String[] argv)
                throws NoSuchAlgorithmException,
                       NoSuchProviderException
        {
            try {
                // creating SecureRandom object
                SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
      
                // creating Provider object
                Provider pd = sr1.getProvider();
      
                // getting provider name
                // by using method getname()
                String provider = pd.getName();
      
                // creating the object of SecureRandom and getting instance
                // By using getInstance() method
                System.out.println("Trying to take TAJMAHAL as a algorithm");
                SecureRandom sr = SecureRandom.getInstance("TAJMAHAL", provider);
      
                // Declaring the string variable
                String str = "Tajmahal";
      
                // Declaring the byte Array
                // converting string into byte
                byte[] b = str.getBytes();
      
                // printing the byte array
                System.out.println("Byte array before operation : "
                                   + Arrays.toString(b));
      
                // generating user-specified number of random bytes
                // using nextBytes() method
                sr.nextBytes(b);
      
                // printing the new byte array
                System.out.println("Byte array after operation : "
                                   + Arrays.toString(b));
            }
      
            catch (NoSuchAlgorithmException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (ProviderException e) {
      
                System.out.println("Exception thrown : " + e);
            }
        }
    }
    

    输出:

    Trying to take TAJMAHAL as a algorithm
    Exception thrown : java.security.NoSuchAlgorithmException: no such algorithm: TAJMAHAL for provider SUN

    示例 3:

    // Java program to demonstrate
    // getInstance() method
      
    import java.security.*;
    import java.util.*;
      
    public class GFG1 {
        public static void
            main(String[] argv)
                throws NoSuchAlgorithmException,
                       NoSuchProviderException
        {
            try {
                // creating SecureRandom object
                SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
      
                // getting algorithm name
                // by using     getAlgorithm() mathod
                String algo = sr1.getAlgorithm();
      
                // creating the object of SecureRandom and getting instance
                // By using getInstance() method
                System.out.println("Trying to taking MOON as a provider");
                SecureRandom sr = SecureRandom.getInstance(algo, "MOON");
      
                // Declaring the string variable
                String str = "Tajmahal";
      
                // Declaring the byte Array
                // converting string into byte
                byte[] b = str.getBytes();
      
                // printing the byte array
                System.out.println("Byte array before operation : "
                                   + Arrays.toString(b));
      
                // generating user-specified number of random bytes
                // using nextBytes() method
                sr.nextBytes(b);
      
                // printing the new byte array
                System.out.println("Byte array after operation : "
                                   + Arrays.toString(b));
            }
      
            catch (NoSuchAlgorithmException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (NoSuchProviderException e) {
      
                System.out.println("Exception thrown : " + e);
            }
        }
    }
    

    输出:

    Trying to taking MOON as a provider
    Exception thrown : java.security.NoSuchProviderException: no such provider: MOON