How to generate a secure random number in a variety of programming languages

Source: Internet
Author: User
Tags cryptographically secure sodium

What does it mean to generate secure random data? Why generate secure random data? In some previous literature this was not a good indication of how to generate "safe" random numbers. So, here's how to safely generate random numbers in the programming language below.

    C + +    Java    . NET    node. js    PHP    Python    Ruby

General conditions that need to be included

All scenarios for this article must be read only from the kernel's csprng (cryptographically secure pseudo-random number Generator, password-safe pseudo-random numbers generator) and shut down immediately after the failure. The rng of the user space and fallback to an unsafe rng are not allowed. So, depending on the platform, use the following entropy source:

  Windows:        rtlgenrandom
Linux: getrandom (how available) its method is correct, will block before sowing, and then no longer sow. /dev/urandom (old Linux kernel) for software running at Linux startup, query /dev/random until it is available. This means that at that time/dev/urandom has sown, you can safely read the content from the/dev/urandom, you can use your password. Do notread from the/dev/random. OpenBSD: getentropy () arc4random_buf () Use CHACHA20 encryption Algorithm (not RC4) other Unix-like systems (including OS X) :/ Dev/urandom

Solutions that rely on programs such as HAVEGED,EGD are not considered here.

Password-safe random in C + +

The simplest and safest way to do this is to add the Libsodium library to the project's dependent library, using the RANDOMBYTES_BUF () function.

Here you see how libsodium implements these functions. The PHP team adopted a similar approach in its internal random_bytes function implementation.

#include"sodium.h"intfoo () {Charmystring[ +]; intmyInt; Randombytes_buf (myString, +); /*myString'll be a string of random bytes*/myInt= Randombytes_uniform (Ten); /*myInt'll be a random number between 0 and 9*/}

Use Libsodium if you can, as is the case in the other languages below.

Password-safe random in Java

In addition to using Libsodium (recommended), you can also use the Java SecureRandom class directly:

New securerandom (); byte New byte [];csprng.nextbytes (randombytes);

Note: Do not use Securerandom.getinstancestrong () on Linux, do not be misled by the name, it is equivalent to reading/dev/random, this is not safe. Java8 in New SecureRandom () reads/dev/urandom by default, which is what you need.

Password security randomization in. NET (C #)

The common approach is to use System.Security.Cryptography.RNGCryptoServiceProvider, such as:

New RNGCryptoServiceProvider (); byte New byte [];csprng.getbytes (rawbytearray);

If you need to generate a secure integer on the password, look at the implementation of the Cryptorandom class in Inferno (A. NET password vault written by Stan Drapkin).

Password security randomization in node. js

Do not use Crypto.randombytes ()

var csprng = require ("sodium"). Random; var bytes = Csprng.randombytes_buf (32);

Password-safe random in PHP

If you are running PHP 7, there is a built-in function:

$string = random_bytes (+); $integer = random_int (0, Php_int_max);

How do you use PHP 5, get Random_compat, and then use the same API as PHP 7.

Composer require paragonie/random_compat:^2

Please use version 2. Version 1 will fall back to OpenSSL, which can cause security problems if there are no other entropy sources available. However, some people will explicitly use version 1 for compatibility.

If you are writing a PHP 5 library for others to use in their projects, set your Composer.json condition string to ^1|^2. Conversely, if you are writing an application, set the condition string to ^2.

Password-safe random in Python

If you are not using Libsodium: If you need random bytes, use Os.urandom ().

If you need random data in other formats, you need to use random. Systemrandom (), not random.

Import SYS Import Random # Random bytes  = os.urandom (= random). Systemrandom ()#  Random (probably large) integer= csprng.randint (0, Sys.maxint )

Password-safe random in Ruby

Do not use Ruby's securerandom!

It is not the best csprng, regardless of the name. Fortunately, Tony Arcieri (a cryptographic expert, Cryptosphere's designer, and a comprehensive password application engineer) provides Ruby community with a secure option to port Libsodium's Sysrandom interface to the Ruby Gem.

Recommendation: Use Sysrandom proxy securerandom.

Install Sysrandom:

Gem Install Sysrandom

Sysrandom is compatible with the SecureRandom API. You can replace securerandom by patching.

How to generate a secure random number in a variety of programming languages

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.