You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

keypair_test.go 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package activitypub
  5. import (
  6. "crypto"
  7. "crypto/rand"
  8. "crypto/rsa"
  9. "crypto/sha256"
  10. "crypto/x509"
  11. "encoding/pem"
  12. "regexp"
  13. "testing"
  14. "github.com/stretchr/testify/assert"
  15. )
  16. func TestKeygen(t *testing.T) {
  17. priv, pub, err := GenerateKeyPair()
  18. assert.NoError(t, err)
  19. assert.NotEmpty(t, priv)
  20. assert.NotEmpty(t, pub)
  21. assert.Regexp(t, regexp.MustCompile("^-----BEGIN RSA PRIVATE KEY-----.*"), priv)
  22. assert.Regexp(t, regexp.MustCompile("^-----BEGIN PUBLIC KEY-----.*"), pub)
  23. }
  24. func TestSignUsingKeys(t *testing.T) {
  25. priv, pub, err := GenerateKeyPair()
  26. assert.NoError(t, err)
  27. privPem, _ := pem.Decode([]byte(priv))
  28. if privPem == nil || privPem.Type != "RSA PRIVATE KEY" {
  29. t.Fatal("key is wrong type")
  30. }
  31. privParsed, err := x509.ParsePKCS1PrivateKey(privPem.Bytes)
  32. assert.NoError(t, err)
  33. pubPem, _ := pem.Decode([]byte(pub))
  34. if pubPem == nil || pubPem.Type != "PUBLIC KEY" {
  35. t.Fatal("key failed to decode")
  36. }
  37. pubParsed, err := x509.ParsePKIXPublicKey(pubPem.Bytes)
  38. assert.NoError(t, err)
  39. // Sign
  40. msg := "activity pub is great!"
  41. h := sha256.New()
  42. h.Write([]byte(msg))
  43. d := h.Sum(nil)
  44. sig, err := rsa.SignPKCS1v15(rand.Reader, privParsed, crypto.SHA256, d)
  45. assert.NoError(t, err)
  46. // Verify
  47. err = rsa.VerifyPKCS1v15(pubParsed.(*rsa.PublicKey), crypto.SHA256, d, sig)
  48. assert.NoError(t, err)
  49. }