algorithms.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. "fmt"
  24. /*"encoding/pem"
  25. "io/ioutil"
  26. "os/user"
  27. "crypto/sha256"*/)
  28. func ShaHmac1(source, secret string) string {
  29. key := []byte(secret)
  30. hmac := hmac.New(sha1.New, key)
  31. hmac.Write([]byte(source))
  32. signedBytes := hmac.Sum(nil)
  33. signedString := base64.StdEncoding.EncodeToString(signedBytes)
  34. return signedString
  35. }
  36. func Sha256WithRsa(source, secret string) string {
  37. decodeString, err := base64.StdEncoding.DecodeString(secret)
  38. if err != nil {
  39. fmt.Println("DecodeString err", err)
  40. }
  41. private, err := x509.ParsePKCS8PrivateKey(decodeString)
  42. if err != nil {
  43. fmt.Println("ParsePKCS8PrivateKey err", err)
  44. }
  45. h := crypto.Hash.New(crypto.SHA256)
  46. h.Write([]byte(source))
  47. hashed := h.Sum(nil)
  48. signature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey),
  49. crypto.SHA256, hashed)
  50. if err != nil {
  51. fmt.Println("Error from signing:", err)
  52. return ""
  53. }
  54. signedString := base64.StdEncoding.EncodeToString(signature)
  55. //fmt.Printf("Encoded: %v\n", signedString)
  56. return signedString
  57. }