string.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // Copyright 2013 com authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package com
  15. import (
  16. "crypto/aes"
  17. "crypto/cipher"
  18. "crypto/rand"
  19. "encoding/base64"
  20. "errors"
  21. "io"
  22. r "math/rand"
  23. "strconv"
  24. "strings"
  25. "time"
  26. )
  27. // AESEncrypt encrypts text and given key with AES.
  28. func AESEncrypt(key, text []byte) ([]byte, error) {
  29. block, err := aes.NewCipher(key)
  30. if err != nil {
  31. return nil, err
  32. }
  33. b := base64.StdEncoding.EncodeToString(text)
  34. ciphertext := make([]byte, aes.BlockSize+len(b))
  35. iv := ciphertext[:aes.BlockSize]
  36. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  37. return nil, err
  38. }
  39. cfb := cipher.NewCFBEncrypter(block, iv)
  40. cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
  41. return ciphertext, nil
  42. }
  43. // AESDecrypt decrypts text and given key with AES.
  44. func AESDecrypt(key, text []byte) ([]byte, error) {
  45. block, err := aes.NewCipher(key)
  46. if err != nil {
  47. return nil, err
  48. }
  49. if len(text) < aes.BlockSize {
  50. return nil, errors.New("ciphertext too short")
  51. }
  52. iv := text[:aes.BlockSize]
  53. text = text[aes.BlockSize:]
  54. cfb := cipher.NewCFBDecrypter(block, iv)
  55. cfb.XORKeyStream(text, text)
  56. data, err := base64.StdEncoding.DecodeString(string(text))
  57. if err != nil {
  58. return nil, err
  59. }
  60. return data, nil
  61. }
  62. // IsLetter returns true if the 'l' is an English letter.
  63. func IsLetter(l uint8) bool {
  64. n := (l | 0x20) - 'a'
  65. if n >= 0 && n < 26 {
  66. return true
  67. }
  68. return false
  69. }
  70. // Expand replaces {k} in template with match[k] or subs[atoi(k)] if k is not in match.
  71. func Expand(template string, match map[string]string, subs ...string) string {
  72. var p []byte
  73. var i int
  74. for {
  75. i = strings.Index(template, "{")
  76. if i < 0 {
  77. break
  78. }
  79. p = append(p, template[:i]...)
  80. template = template[i+1:]
  81. i = strings.Index(template, "}")
  82. if s, ok := match[template[:i]]; ok {
  83. p = append(p, s...)
  84. } else {
  85. j, _ := strconv.Atoi(template[:i])
  86. if j >= len(subs) {
  87. p = append(p, []byte("Missing")...)
  88. } else {
  89. p = append(p, subs[j]...)
  90. }
  91. }
  92. template = template[i+1:]
  93. }
  94. p = append(p, template...)
  95. return string(p)
  96. }
  97. // Reverse s string, support unicode
  98. func Reverse(s string) string {
  99. n := len(s)
  100. runes := make([]rune, n)
  101. for _, rune := range s {
  102. n--
  103. runes[n] = rune
  104. }
  105. return string(runes[n:])
  106. }
  107. // RandomCreateBytes generate random []byte by specify chars.
  108. func RandomCreateBytes(n int, alphabets ...byte) []byte {
  109. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  110. var bytes = make([]byte, n)
  111. var randby bool
  112. if num, err := rand.Read(bytes); num != n || err != nil {
  113. r.Seed(time.Now().UnixNano())
  114. randby = true
  115. }
  116. for i, b := range bytes {
  117. if len(alphabets) == 0 {
  118. if randby {
  119. bytes[i] = alphanum[r.Intn(len(alphanum))]
  120. } else {
  121. bytes[i] = alphanum[b%byte(len(alphanum))]
  122. }
  123. } else {
  124. if randby {
  125. bytes[i] = alphabets[r.Intn(len(alphabets))]
  126. } else {
  127. bytes[i] = alphabets[b%byte(len(alphabets))]
  128. }
  129. }
  130. }
  131. return bytes
  132. }