gitee.com/lh-her-team/common@v1.5.1/crypto/pkcs11/rand.go (about) 1 package pkcs11 2 3 import ( 4 "errors" 5 "fmt" 6 ) 7 8 const ( 9 defaultRandomLen = 6 10 ) 11 12 func GenerateOTP(p11 *P11Handle, length int) (string, error) { 13 if length <= 0 { 14 length = defaultRandomLen 15 } 16 randBytes, err := GenerateBytesOTP(p11, length) 17 if err != nil { 18 return "", err 19 } 20 r, err := bytesToInt(randBytes) 21 if err != nil { 22 return "", err 23 } 24 rStr := fmt.Sprintf("%0*d", length, r) 25 if len(rStr) < length { 26 return "", errors.New("generate random failed, len is too low") 27 } 28 return rStr[:length], nil 29 } 30 31 func GenerateBytesOTP(p11 *P11Handle, length int) ([]byte, error) { 32 if length <= 0 { 33 length = defaultRandomLen 34 } 35 return p11.GenerateRandom(length) 36 }