algorithms.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. decodeString, err := base64.StdEncoding.DecodeString(secret)
  34. if err != nil {
  35. panic(err)
  36. }
  37. private, err := x509.ParsePKCS8PrivateKey(decodeString)
  38. if err != nil {
  39. panic(err)
  40. }
  41. h := crypto.Hash.New(crypto.SHA256)
  42. h.Write([]byte(source))
  43. hashed := h.Sum(nil)
  44. signature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey),
  45. crypto.SHA256, hashed)
  46. if err != nil {
  47. panic(err)
  48. }
  49. return base64.StdEncoding.EncodeToString(signature)
  50. }