crypt-unchat.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package unchat
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/pem"
  8. "fmt"
  9. "log"
  10. )
  11. func main() {
  12. key_pk, err := rsa.GenerateKey(rand.Reader, 2048)
  13. if err != nil {
  14. log.Fatalf("could not generate keypair %s", err)
  15. }
  16. pub_key := &key_pk.PublicKey
  17. msg := []byte("this is a new message to be encrypted")
  18. label := []byte("")
  19. hash := sha256.New()
  20. cipher_text, err := rsa.EncryptOAEP(
  21. hash,
  22. rand.Reader,
  23. pub_key,
  24. msg,
  25. label)
  26. if err != nil {
  27. log.Fatalf("could not encrypt message %s", err)
  28. }
  29. fmt.Printf("message encrypted: \n%x\n", cipher_text)
  30. plain_text, err := rsa.DecryptOAEP(
  31. hash,
  32. rand.Reader,
  33. key_pk,
  34. cipher_text,
  35. label)
  36. if err != nil {
  37. log.Fatalf("could not decrypt message %s", err)
  38. }
  39. fmt.Printf("message decrypted: \n%s\n", plain_text)
  40. pem := ExportPrivKeyAsPEM(key_pk)
  41. fmt.Printf("PEM Priv Key \n%s\n", pem)
  42. ParsePrivKeyFromPEM(pem)
  43. }
  44. func ExportPrivKeyAsPEM(privKey *rsa.PrivateKey) string {
  45. privkey_bytes := x509.MarshalPKCS1PrivateKey(privKey)
  46. privkey_pem := pem.EncodeToMemory(
  47. &pem.Block{
  48. Type: "RSA PRIVATE KEY",
  49. Bytes: privkey_bytes,
  50. },
  51. )
  52. return string(privkey_pem)
  53. }
  54. func ParsePrivKeyFromPEM(pemKey string) (*rsa.PrivateKey, error) {
  55. block, _ := pem.Decode([]byte(pemKey))
  56. if block == nil {
  57. return nil, fmt.Errorf("could not read pem string")
  58. }
  59. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  60. if err != nil {
  61. return nil, err
  62. }
  63. return priv, nil
  64. }