1
0

random_auth_key.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package random_auth_key
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "github.com/wumansgy/goEncrypt/aes"
  6. "github.com/jinzhu/now"
  7. )
  8. // RandomAuthKey 伪随机的登录验证 Key
  9. type RandomAuthKey struct {
  10. offset int
  11. authKey AuthKey // 基础的密钥,密钥会基于这个基础的密钥生成
  12. }
  13. // NewRandomAuthKey offset 建议是 5
  14. func NewRandomAuthKey(offset int, authKey AuthKey) *RandomAuthKey {
  15. tmpOffset := offset
  16. if tmpOffset < 0 || tmpOffset > 5 {
  17. tmpOffset = 5
  18. }
  19. return &RandomAuthKey{
  20. offset: tmpOffset,
  21. authKey: authKey,
  22. }
  23. }
  24. // GetAuthKey 获取这个小时的认证密码
  25. func (r *RandomAuthKey) GetAuthKey() (string, error) {
  26. // 当前时间 Unix时间戳 1653099199,这里获取到的是整点的小时时间
  27. nowUnixTime := now.BeginningOfHour().Unix()
  28. return r.getAuthKey(nowUnixTime)
  29. }
  30. func (r RandomAuthKey) getAuthKey(hourUnixTime int64) (string, error) {
  31. nowUnixTimeStr := fmt.Sprintf("%d", hourUnixTime)
  32. prefixStr := nowUnixTimeStr[len(nowUnixTimeStr)-r.offset:] + nowUnixTimeStr[:r.offset]
  33. // 拼接
  34. orgString := prefixStr + r.authKey.BaseKey + nowUnixTimeStr + r.authKey.BaseKey[:r.offset]
  35. plaintext := []byte(orgString)
  36. // 传入明文和自己定义的密钥,密钥为 16 字节 可以自己传入初始化向量,如果不传就使用默认的初始化向量, 16 字节
  37. cryptText, err := aes.AesCbcEncrypt(plaintext, []byte(r.authKey.AESKey16), []byte(r.authKey.AESIv16))
  38. if err != nil {
  39. return "", err
  40. }
  41. // 加密后的字符串
  42. return base64.StdEncoding.EncodeToString(cryptText), nil
  43. }
  44. type AuthKey struct {
  45. BaseKey string // 基础的密钥,密钥会基于这个基础的密钥生成
  46. AESKey16 string // AES密钥
  47. AESIv16 string // 初始化向量
  48. }
  49. const (
  50. BaseKey = "0123456789123456789" // 基础的密钥,密钥会基于这个基础的密钥生成
  51. AESKey16 = "1234567890123456" // AES密钥
  52. AESIv16 = "1234567890123456" // 初始化向量
  53. )