github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/access_contoller/crypto/pkcs11/rand.go (about) 1 /* 2 Copyright (C) BABEC. All rights reserved. 3 Copyright (C) THL A29 Limited, a Tencent company. All rights reserved. 4 5 SPDX-License-Identifier: Apache-2.0 6 */ 7 8 package pkcs11 9 10 import ( 11 "errors" 12 "fmt" 13 ) 14 15 const ( 16 defaultRandomLen = 6 17 ) 18 19 func GenerateOTP(p11 *P11Handle, length int) (string, error) { 20 if length <= 0 { 21 length = defaultRandomLen 22 } 23 randBytes, err := GenerateBytesOTP(p11, length) 24 if err != nil { 25 return "", err 26 } 27 r, err := bytesToInt(randBytes) 28 if err != nil { 29 return "", err 30 } 31 rStr := fmt.Sprintf("%0*d", length, r) 32 if len(rStr) < length { 33 return "", errors.New("generate random failed, len is too low") 34 } 35 return rStr[:length], nil 36 } 37 38 func GenerateBytesOTP(p11 *P11Handle, length int) ([]byte, error) { 39 if length <= 0 { 40 length = defaultRandomLen 41 } 42 return p11.GenerateRandom(length) 43 }