如何使用“crypto / rand”包生成随机int?

时间:2015-09-02 09:44:11

标签: go

假设我想使用:

在0到27之间生成一个安全的随机int
-

func Int(rand io.Reader, max *big.Int) (n *big.Int, err error) 包中。

我该怎么做?

我真的不明白它是如何工作的,为什么它不返回内置的Go ints而不是指向某个big.Int类型的指针?

编辑:

对于令牌,这会被认为是否足够安全?

"crypto/rand"

这将输出如下内容:

func getToken(length int) string {
    token := ""
    codeAlphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    codeAlphabet += "abcdefghijklmnopqrstuvwxyz"
    codeAlphabet += "0123456789"

    for i := 0; i < length; i++ {
        token += string(codeAlphabet[cryptoRandSecure(int64(len(codeAlphabet)))])
    }
    return token
}

func cryptoRandSecure(max int64) int64 {
    nBig, err := rand.Int(rand.Reader, big.NewInt(max))
    if err != nil {
        log.Println(err)
    }
    return nBig.Int64()
}

func main() {
    fmt.Println(getToken(32))
}

3 个答案:

答案 0 :(得分:20)

如果您正在为会话ID,OAuth承载令牌,CSRF或类似物生成安全令牌:您希望生成(理想情况下)256位(32字节)或不小于192位(24字节)的令牌。

值(0-27)之间的标记可以在不到一秒的时间内被强制强制,并且不能被认为是安全的。

e.g。

[INFO] --- maven-install-plugin:2.4:install (default-install) @ JBossEAP ---
[INFO] Installing D:\Aly da Cristianio\My WorkSpace\JBossEAP\target\JBossEAP.war to C:\Users\amotiwal\.m2\repository\com\subversion\svn\JBossEAP\0.0.1-SNAPSHOT\JBossEAP-0.0.1-SNAPSHOT.war
[INFO] Installing D:\Aly da Cristianio\My WorkSpace\JBossEAP\pom.xml to C:\Users\amotiwal\.m2\repository\com\subversion\svn\JBossEAP\0.0.1-SNAPSHOT\JBossEAP-0.0.1-SNAPSHOT.pom
[INFO] 
[INFO] >>> jboss-as-maven-plugin:7.4.Final:deploy (default) > package @ JBossEAP >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ JBossEAP ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ JBossEAP ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ JBossEAP ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory D:\Aly da Cristianio\My WorkSpace\JBossEAP\src\test\resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ JBossEAP ---
[INFO] No sources to compile
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ JBossEAP ---
[INFO] No tests to run.
[INFO] Skipping execution of surefire because it has already been run for this configuration
[JENKINS] Recording test results
[INFO] 
[INFO] --- maven-war-plugin:2.2:war (default-war) @ JBossEAP ---
[INFO] Packaging webapp
[INFO] Assembling webapp [JBossEAP] in [D:\Aly da Cristianio\My WorkSpace\JBossEAP\target\JBossEAP]
[INFO] Processing war project
[INFO] Copying webapp resources [D:\Aly da Cristianio\My WorkSpace\JBossEAP\src\main\webapp]
[INFO] Webapp assembled in [13 msecs]
[INFO] Building war: D:\Aly da Cristianio\My WorkSpace\JBossEAP\target\JBossEAP.war
[INFO] WEB-INF\web.xml already added, skipping
[WARNING] Failed to getClass for org.jboss.as.plugin.deployment.Deploy
[INFO] 
[INFO] <<< jboss-as-maven-plugin:7.4.Final:deploy (default) < package @ JBossEAP <<<
[INFO] 
[INFO] --- jboss-as-maven-plugin:7.4.Final:deploy (default) @ JBossEAP ---
[INFO] XNIO Version 3.0.7.GA
[INFO] XNIO NIO Implementation Version 3.0.7.GA
[INFO] JBoss Remoting version 3.2.12.GA
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 6.308 s
[INFO] Finished at: 2015-09-02T14:00:07+05:30
[INFO] Final Memory: 20M/86M
[INFO] ------------------------------------------------------------------------
[JENKINS] Archiving D:\Aly da Cristianio\My WorkSpace\JBossEAP\pom.xml to com.subversion.svn/JBossEAP/0.0.1-SNAPSHOT/JBossEAP-0.0.1-SNAPSHOT.pom
[JENKINS] Archiving D:\Aly da Cristianio\My WorkSpace\JBossEAP\target\JBossEAP.war to com.subversion.svn/JBossEAP/0.0.1-SNAPSHOT/JBossEAP-0.0.1-SNAPSHOT.war
channel stopped
ERROR: Build step failed with exception
org.codehaus.cargo.container.ContainerException: Failed to create deployer with implementation class org.codehaus.cargo.container.jboss.JBoss7xRemoteDeployer for the parameters (container [id = [jboss7x]], deployer type [remote]).
    at org.codehaus.cargo.generic.spi.AbstractGenericHintFactory.createImplementation(AbstractGenericHintFactory.java:154)
    at org.codehaus.cargo.generic.spi.AbstractIntrospectionGenericHintFactory.createImplementation(AbstractIntrospectionGenericHintFactory.java:93)
    at org.codehaus.cargo.generic.deployer.DefaultDeployerFactory.createDeployer(DefaultDeployerFactory.java:141)
    at org.codehaus.cargo.generic.deployer.DefaultDeployerFactory.createDeployer(DefaultDeployerFactory.java:161)
    at hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:61)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:116)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:103)
    at hudson.FilePath.act(FilePath.java:991)
    at hudson.FilePath.act(FilePath.java:969)
    at hudson.plugins.deploy.CargoContainerAdapter.redeploy(CargoContainerAdapter.java:103)
    at hudson.plugins.deploy.DeployPublisher.perform(DeployPublisher.java:61)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)
    at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:726)
    at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.post2(MavenModuleSetBuild.java:1047)
    at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:671)
    at hudson.model.Run.execute(Run.java:1766)
    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:531)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:408)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at org.codehaus.cargo.generic.deployer.DefaultDeployerFactory.createInstance(DefaultDeployerFactory.java:220)
    at org.codehaus.cargo.generic.deployer.DefaultDeployerFactory.createInstance(DefaultDeployerFactory.java:43)
    at org.codehaus.cargo.generic.spi.AbstractGenericHintFactory.createImplementation(AbstractGenericHintFactory.java:150)
    ... 19 more
Caused by: org.codehaus.cargo.util.CargoException: Cannot locate the JBoss connector classes! Make sure the required JBoss JARs (or Maven dependencies) are in CARGO's classpath.
More information on: http://cargo.codehaus.org/JBoss+Remote+Deployer
    at org.codehaus.cargo.container.jboss.JBoss5xRemoteDeployer.<init>(JBoss5xRemoteDeployer.java:161)
    at org.codehaus.cargo.container.jboss.JBoss7xRemoteDeployer.<init>(JBoss7xRemoteDeployer.java:41)
    ... 26 more
Caused by: java.lang.ClassNotFoundException: org.jboss.as.controller.client.ModelControllerClient
    at jenkins.util.AntClassLoader.findClassInComponents(AntClassLoader.java:1376)
    at jenkins.util.AntClassLoader.findClass(AntClassLoader.java:1326)
    at jenkins.util.AntClassLoader.loadClass(AntClassLoader.java:1079)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.codehaus.cargo.container.jboss.JBoss5xRemoteDeployer.<init>(JBoss5xRemoteDeployer.java:156)
    ... 27 more
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at org.codehaus.cargo.generic.deployer.DefaultDeployerFactory.createInstance(DefaultDeployerFactory.java:220)
    at org.codehaus.cargo.generic.deployer.DefaultDeployerFactory.createInstance(DefaultDeployerFactory.java:43)
    at org.codehaus.cargo.generic.spi.AbstractGenericHintFactory.createImplementation(AbstractGenericHintFactory.java:150)
    at org.codehaus.cargo.generic.spi.AbstractIntrospectionGenericHintFactory.createImplementation(AbstractIntrospectionGenericHintFactory.java:93)
    at org.codehaus.cargo.generic.deployer.DefaultDeployerFactory.createDeployer(DefaultDeployerFactory.java:141)
    at org.codehaus.cargo.generic.deployer.DefaultDeployerFactory.createDeployer(DefaultDeployerFactory.java:161)
    at hudson.plugins.deploy.CargoContainerAdapter.deploy(CargoContainerAdapter.java:61)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:116)
    at hudson.plugins.deploy.CargoContainerAdapter$1.invoke(CargoContainerAdapter.java:103)
    at hudson.FilePath.act(FilePath.java:991)
    at hudson.FilePath.act(FilePath.java:969)
    at hudson.plugins.deploy.CargoContainerAdapter.redeploy(CargoContainerAdapter.java:103)
    at hudson.plugins.deploy.DeployPublisher.perform(DeployPublisher.java:61)
    at hudson.tasks.BuildStepMonitor$3.perform(BuildStepMonitor.java:45)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)
    at hudson.model.AbstractBuild$AbstractBuildExecution.performAllBuildSteps(AbstractBuild.java:726)
    at hudson.maven.MavenModuleSetBuild$MavenModuleSetBuildExecution.post2(MavenModuleSetBuild.java:1047)
    at hudson.model.AbstractBuild$AbstractBuildExecution.post(AbstractBuild.java:671)
    at hudson.model.Run.execute(Run.java:1766)
    at hudson.maven.MavenModuleSetBuild.run(MavenModuleSetBuild.java:531)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:408)
Caused by: org.codehaus.cargo.util.CargoException: Cannot locate the JBoss connector classes! Make sure the required JBoss JARs (or Maven dependencies) are in CARGO's classpath.`enter code here`
More information on: http://cargo.codehaus.org/JBoss+Remote+Deployer
    at org.codehaus.cargo.container.jboss.JBoss5xRemoteDeployer.<init>(JBoss5xRemoteDeployer.java:161)
    at org.codehaus.cargo.container.jboss.JBoss7xRemoteDeployer.<init>(JBoss7xRemoteDeployer.java:41)
    ... 26 more
Caused by: java.lang.ClassNotFoundException: org.jboss.as.controller.client.ModelControllerClient
    at jenkins.util.AntClassLoader.findClassInComponents(AntClassLoader.java:1376)
    at jenkins.util.AntClassLoader.findClass(AntClassLoader.java:1326)
    at jenkins.util.AntClassLoader.loadClass(AntClassLoader.java:1079)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.codehaus.cargo.container.jboss.JBoss5xRemoteDeployer.<init>(JBoss5xRemoteDeployer.java:156)
    ... 27 more
Build step 'Deploy war/ear to a container' marked build as failure
Finished: FAILURE

base64输出对于标头,HTTP表单,JSON主体等是安全的。

如果你需要一个整数,它可能有助于解释你的用例,因为系统要求令牌作为整数是奇怪的。

答案 1 :(得分:18)

以下是一些有效的代码:

package main

import (
    "fmt"
    "crypto/rand"
    "math/big"
)

func main() {
    nBig, err := rand.Int(rand.Reader, big.NewInt(27))
    if err != nil {
        panic(err)
    }
    n := nBig.Int64()
    fmt.Printf("Here is a random %T in [0,27) : %d\n", n, n)
}

但要生成随机令牌,我会做这样的事情:

package main

import (
    "crypto/rand"
    "encoding/base32"
    "fmt"
)

func main() {
    token := getToken(10)
    fmt.Println("Here is a random token : ", token)
}

func getToken(length int) string {
    randomBytes := make([]byte, 32)
    _, err := rand.Read(randomBytes)
    if err != nil {
        panic(err)
    }
    return base32.StdEncoding.EncodeToString(randomBytes)[:length]
}

答案 2 :(得分:0)

如果你只需要一个小数字(即[0,255]),你就可以从包Reader中读出一个字节:

b := []byte{0}
if _, err := rand.Reader.Read(b); err != nil {
    panic(err)
}
n := b[0]
fmt.Println(n)

游乐场:http://play.golang.org/p/4VO52LiEVh(示例不会在那里工作,我不知道它是否按预期工作,或者它是游乐场的错误)。