algorithms.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Licensed under the Apache License, Version 2.0 (the "License");
  3. * you may not use this file except in compliance with the License.
  4. * You may obtain a copy of the License at
  5. *
  6. * http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. * See the License for the specific language governing permissions and
  12. * limitations under the License.
  13. */
  14. package signers
  15. import (
  16. "crypto"
  17. "crypto/hmac"
  18. "crypto/rand"
  19. "crypto/rsa"
  20. "crypto/sha1"
  21. "crypto/x509"
  22. "encoding/base64"
  23. )
  24. func ShaHmac1(source, secret string) string {
  25. key := []byte(secret)
  26. hmac := hmac.New(sha1.New, key)
  27. hmac.Write([]byte(source))
  28. signedBytes := hmac.Sum(nil)
  29. signedString := base64.StdEncoding.EncodeToString(signedBytes)
  30. return signedString
  31. }
  32. func Sha256WithRsa(source, secret string) string {
  33. // block, _ := pem.Decode([]byte(secret))
  34. decodeString, err := base64.StdEncoding.DecodeString(secret)
  35. if err != nil {
  36. panic(err)
  37. }
  38. private, err := x509.ParsePKCS8PrivateKey(decodeString)
  39. if err != nil {
  40. panic(err)
  41. }
  42. h := crypto.Hash.New(crypto.SHA256)
  43. h.Write([]byte(source))
  44. hashed := h.Sum(nil)
  45. signature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey),
  46. crypto.SHA256, hashed)
  47. if err != nil {
  48. panic(err)
  49. }
  50. return base64.StdEncoding.EncodeToString(signature)
  51. }