crytology.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // Author : Eric Kim
  2. // Build Date : 23 Jul 2018 Last Update 02 Aug 2018
  3. // End-Agent for Passcon Multi OS go binding with Windows, MacOS, iOS, and Android
  4. // All rights are reserved.
  5. package etc
  6. import (
  7. "bytes"
  8. "crypto"
  9. "crypto/aes"
  10. "crypto/cipher"
  11. "crypto/rand"
  12. "crypto/rsa"
  13. "crypto/sha256"
  14. "crypto/x509"
  15. "encoding/base64"
  16. "encoding/pem"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "math/big"
  21. "strings"
  22. )
  23. func RsaPrPbPair(keyLeng int) ([]byte, []byte) {
  24. prKey, _ := rsa.GenerateKey(rand.Reader, keyLeng)
  25. pbKey := &prKey.PublicKey
  26. prBytes := x509.MarshalPKCS1PrivateKey(prKey)
  27. prMem := pem.EncodeToMemory(&pem.Block{
  28. Type: "RSA PRIVATE KEY",
  29. Bytes: prBytes,
  30. })
  31. // Bytes: 에 직접 넣으면 런타임에서 에러남.(중요!!)
  32. pbBytes, err := x509.MarshalPKIXPublicKey(pbKey)
  33. if err != nil {
  34. fmt.Println(err)
  35. }
  36. pbMem := pem.EncodeToMemory(&pem.Block{
  37. Type: "RSA PUBLIC KEY",
  38. Bytes: pbBytes,
  39. })
  40. return prMem, pbMem
  41. }
  42. func RsaSignature(prKey []byte, msg []byte) ([]byte, error) { // msg 245=(256-11)bytes 이하
  43. block, _ := pem.Decode(prKey)
  44. if block == nil {
  45. return nil, MyErr("QROPBDHCF-pem.Decode", nil, false)
  46. }
  47. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  48. if err != nil {
  49. return nil, MyErr("QERDVAEQYG-x509.ParsePKCS1PrivateKey", err, false)
  50. }
  51. sign, err := rsa.SignPKCS1v15(nil, priv, crypto.Hash(0), msg)
  52. if err != nil {
  53. return nil, MyErr("CZGSRFVA-rsa.SignPKCS1v15", err, false)
  54. }
  55. return sign, nil
  56. }
  57. func RsaOriginal(pubKey []byte, msg []byte) ([]byte, error) {
  58. block, _ := pem.Decode(pubKey)
  59. if block == nil {
  60. return nil, MyErr("ADYERFBJ-pem.Decode", nil, false)
  61. }
  62. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  63. if err != nil {
  64. return nil, MyErr("MNCHSTRGB-x509.ParsePKIXPublicKey", err, false)
  65. }
  66. pbKey := pubInterface.(*rsa.PublicKey)
  67. c := new(big.Int)
  68. m := new(big.Int)
  69. m.SetBytes(msg)
  70. e := big.NewInt(int64(pbKey.E))
  71. c.Exp(m, e, pbKey.N)
  72. out := c.Bytes()
  73. skip := 0
  74. for i := 2; i < len(out); i++ {
  75. if i+1 >= len(out) {
  76. break
  77. }
  78. if out[i] == 0xff && out[i+1] == 0 {
  79. skip = i + 2
  80. break
  81. }
  82. }
  83. return out[skip:], nil
  84. }
  85. func RsaPbEncrypt(publicKey []byte, msg []byte) ([]byte, error) {
  86. origData := msg
  87. block, _ := pem.Decode(publicKey)
  88. if block == nil {
  89. return nil, MyErr("QEROBVSRAE-pem.Decode", nil, false)
  90. }
  91. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  92. if err != nil {
  93. return nil, MyErr("KDGBSAERT-x509.ParsePKIXPublicKey", err, false)
  94. }
  95. pub := pubInterface.(*rsa.PublicKey)
  96. label := []byte("")
  97. sha256hash := sha256.New()
  98. enBytes, err := rsa.EncryptOAEP(sha256hash, rand.Reader, pub, origData, label)
  99. if err != nil {
  100. return nil, MyErr("rsa.EncryptOAEP", err, false)
  101. }
  102. return enBytes, nil
  103. }
  104. func RsaPrDecrypt(privateKey []byte, msg []byte) ([]byte, error) {
  105. ciphertext := msg
  106. block, _ := pem.Decode(privateKey)
  107. if block == nil {
  108. return nil, MyErr("USFBSHWER-pem.Decode", nil, false)
  109. }
  110. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  111. if err != nil {
  112. return nil, MyErr("MTVZQFGAEW-x509.ParsePKCS1PrivateKey", err, false)
  113. }
  114. label := []byte("")
  115. sha256hash := sha256.New()
  116. deBytes, err := rsa.DecryptOAEP(sha256hash, rand.Reader, priv, ciphertext, label)
  117. if err != nil {
  118. return nil, MyErr("QGOTRVBAE-rsa.DecryptOAEP", err, false)
  119. }
  120. return deBytes, nil
  121. }
  122. func AddBase64Padding(value string) string {
  123. m := len(value) % 4
  124. if m != 0 {
  125. value += strings.Repeat("=", 4-m)
  126. }
  127. return value
  128. }
  129. func RemoveBase64Padding(value string) string {
  130. return strings.Replace(value, "=", "", -1)
  131. }
  132. func AesPad(src []byte) []byte {
  133. padding := aes.BlockSize - len(src)%aes.BlockSize
  134. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  135. return append(src, padtext...)
  136. }
  137. func AesUnpad(src []byte) ([]byte, error) {
  138. length := len(src)
  139. unpadding := int(src[length-1])
  140. if unpadding > length {
  141. return nil, errors.New("OYNSTBZE-unpad error. This could happen when incorrect myEncryption key is used")
  142. }
  143. return src[:(length - unpadding)], nil
  144. }
  145. func AesEncrypt(key []byte, text []byte) ([]byte, error) {
  146. block, err := aes.NewCipher(key)
  147. if err != nil {
  148. fmt.Println("WERFAV-Error: NewCipher in myEncrypt - " + err.Error())
  149. return nil, err
  150. }
  151. msg := AesPad(text)
  152. ciphertext := make([]byte, aes.BlockSize+len(msg))
  153. iv := ciphertext[:aes.BlockSize]
  154. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  155. return nil, MyErr("-NYTZVCEF-io.ReadFull", err, false)
  156. }
  157. cfb := cipher.NewCFBEncrypter(block, iv)
  158. cfb.XORKeyStream(ciphertext[aes.BlockSize:], msg)
  159. finalMsg := RemoveBase64Padding(base64.URLEncoding.EncodeToString(ciphertext))
  160. return []byte(finalMsg), nil
  161. }
  162. func AesDecrypt(key []byte, text []byte) ([]byte, error) {
  163. block, err := aes.NewCipher(key)
  164. if err != nil {
  165. return nil, MyErr("YGBARZDF-aes.NewCipher", err, false)
  166. }
  167. decodedMsg, err := base64.URLEncoding.DecodeString(AddBase64Padding(string(text)))
  168. if err != nil {
  169. return nil, MyErr("VSGRERGBEW-base64.URLEncoding.DecodeString, Possibley Decryption string is too long", err, false)
  170. }
  171. if (len(decodedMsg) % aes.BlockSize) != 0 {
  172. return nil, MyErr("MHETYGVBA-aes.BlockSize-blocksize must be multipe of decoded message length", err, false)
  173. }
  174. iv := decodedMsg[:aes.BlockSize]
  175. msg := decodedMsg[aes.BlockSize:]
  176. cfb := cipher.NewCFBDecrypter(block, iv)
  177. cfb.XORKeyStream(msg, msg)
  178. unpadMsg, err := AesUnpad(msg)
  179. if err != nil {
  180. return nil, MyErr("WERQFAERGQ-AesUnpad", err, false)
  181. }
  182. return unpadMsg, nil
  183. }
  184. func Sha256Hash(data []byte, leng int) []byte {
  185. hash := sha256.New() //SHA-3 규격임.
  186. hash.Write(data)
  187. mdStr := base64.URLEncoding.EncodeToString(hash.Sum(nil))
  188. rtn := ""
  189. if leng == 0 {
  190. rtn = mdStr
  191. } else {
  192. rtn = mdStr[10 : 10+leng]
  193. }
  194. return []byte(rtn)
  195. }
  196. func Aes256Encrypt(key []byte, nonce []byte, plaintext []byte) ([]byte, error) {
  197. // The key argument should be the AES key, either 16 or 32 bytes
  198. block, err := aes.NewCipher(key)
  199. if err != nil {
  200. return nil, MyErr("YBBAERFRYY-NewCipher", err, false)
  201. }
  202. // Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
  203. // nonce := make([]byte, 12) // Do not change 12
  204. // if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
  205. // return nil, myErr("io.ReadFull", err)
  206. // }
  207. aesgcm, err := cipher.NewGCM(block)
  208. if err != nil {
  209. return nil, MyErr("ERGVSER-cipher.NewGCM", err, false)
  210. }
  211. text := aesgcm.Seal(nil, nonce, plaintext, nil)
  212. return text, nil
  213. }
  214. func Aes256Decrypt(key []byte, nonce []byte, text []byte) ([]byte, error) {
  215. block, err := aes.NewCipher(key)
  216. if err != nil {
  217. return nil, MyErr("NSTRFGBSAF-NewCipher", err, false)
  218. }
  219. aesgcm, err := cipher.NewGCM(block)
  220. if err != nil {
  221. return nil, MyErr("PQWKKLVASD-cipher.NewGCM", err, false)
  222. }
  223. plaintext, err := aesgcm.Open(nil, nonce, text, nil)
  224. if err != nil {
  225. return nil, MyErr("POQWEIRUNVAIK-aesgcm.Open", err, false)
  226. }
  227. return plaintext, nil
  228. }