Prefer SecureRandom over Random

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: java-security/avoid-random

Language: Java

Severity: Notice

Category: Security

Description

Functions as Math.random() and objects like java.util.Random() do not provide strong enough randomness. Consider using java.security.SecureRandom() instead.

Non-Compliant Code Examples

@RestController
public class ImageServlet {

  public static final int PINCODE = new java.util.Random().nextInt(10000);

  @RequestMapping(
      method = {GET, POST},
      value = "/challenge/logo",
      produces = MediaType.IMAGE_PNG_VALUE)
  @ResponseBody
  public byte[] logo() throws IOException {
    byte[] in = getBytes();

    String pincode = String.format("%04d", PINCODE);

    in[81216] = (byte) pincode.charAt(0);
    in[81217] = (byte) pincode.charAt(1);
    in[81218] = (byte) pincode.charAt(2);
    in[81219] = (byte) pincode.charAt(3);

    return in;
  }
}
@RestController
public class ImageServlet {

  public static final int PINCODE = new Random().nextInt(10000);

  @RequestMapping(
      method = {GET, POST},
      value = "/challenge/logo",
      produces = MediaType.IMAGE_PNG_VALUE)
  @ResponseBody
  public byte[] logo() throws IOException {
    byte[] in = getBytes();

    String pincode = String.format("%04d", PINCODE);

    in[81216] = (byte) pincode.charAt(0);
    in[81217] = (byte) pincode.charAt(1);
    in[81218] = (byte) pincode.charAt(2);
    in[81219] = (byte) pincode.charAt(3);

    return in;
  }
}
@RestController
public class ImageServlet {

  public static final int PINCODE = new Random().nextInt(10000);

  @RequestMapping(
      method = {GET, POST},
      value = "/challenge/logo",
      produces = MediaType.IMAGE_PNG_VALUE)
  @ResponseBody
  public byte[] logo() throws IOException {
    var v = Math.random();
  }
}

Compliant Code Examples

import org.apache.commons.codec.binary.Hex;

class Class {
    String generateSecretToken() {
        SecureRandom secRandom = new SecureRandom();

        byte[] result = new byte[32];
        secRandom.nextBytes(result);
        return Hex.encodeHexString(result);
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis