工作,学习,生活,这里将会有一些记录. 备用域名:http://meisw.51099.com 注册 | 登陆
浏览模式: 标准 | 列表2019年04月的文章

默认的 rand.Intn () 生成的是伪随机数

 rand.Intn () 函数是个伪随机函数,不管运行多少次都只会返回同样的随机数,因为它默认的资源就是单一值,所以必须调用 rand.Seed (), 并且传入一个变化的值作为参数,如 time.Now().UnixNano() , 就是可以生成时刻变化的值.


package main

import ("fmt"
        "math/rand"
        "time")

func main() {
    // 初始化随机数的资源库, 如果不执行这行, 不管运行多少次都返回同样的值
    rand.Seed(time.Now().UnixNano())
    fmt.Println("A number from 1-100", rand.Intn(81))
}

--------------
//rand.Float64 返回一个64位浮点数 f,0.0 <= f <= 1.0。
    fmt.Println(rand.Float64())
//这个技巧可以用来生成其他范围的随机浮点数,例如5.0 <= f <= 10.0
    fmt.Print((rand.Float64()*5)+5, ",")
    fmt.Print((rand.Float64() * 5) + 5)
    fmt.Println()
//要让伪随机数生成器有确定性,可以给它一个明确的种子。
    s1 := rand.NewSource(42)
    r1 := rand.New(s1)
//调用上面返回的 rand.Source 的函数和调用 rand 包中函数是相同的。
    fmt.Print(r1.Intn(100), ",")
    fmt.Print(r1.Intn(100))
    fmt.Println()
如果使用相同的种子生成的随机数生成器,将会产生相同的随机数序列。
    s2 := rand.NewSource(42)
    r2 := rand.New(s2)
    fmt.Print(r2.Intn(100), ",")
    fmt.Print(r2.Intn(100))
    fmt.Println()

golang实现md5、RSA、base64 加密解密

 package tools

 
import (
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/hex"
"encoding/pem"
"errors"
)
 
const (
base64Table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
)
 
var coder = base64.NewEncoding(base64Table)
 
func Base64Encode(src []byte) []byte {
return []byte(coder.EncodeToString(src))
}
 
func Base64Decode(src []byte) ([]byte, error) {
return coder.DecodeString(string(src))
}
 
func RsaEncrypt(origData []byte, publicKey string) ([]byte, error) {
block, _ := pem.Decode([]byte(publicKey))
if block == nil {
return nil, errors.New("public key error")
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
pub := pubInterface.(*rsa.PublicKey)
return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}
 
func RsaDecrypt(ciphertext []byte, privateKey string) ([]byte, error) {
block, _ := pem.Decode([]byte(privateKey))
if block == nil {
return nil, errors.New("private key error!")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
 
func Md5Encrypt(data string) string {
md5Ctx := md5.New()                            //md5 init
md5Ctx.Write([]byte(data))                     //md5 updata
cipherStr := md5Ctx.Sum(nil)                   //md5 final
encryptedData := hex.EncodeToString(cipherStr) //hex_digest
return encryptedData
}
 
--------
https://blog.csdn.net/yue7603835/article/details/73433617