crypto.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package crypto
  3. import (
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/ecdh"
  7. "crypto/rand"
  8. "crypto/sha256"
  9. "encoding/json"
  10. "fmt"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "kitty/tools/utils"
  15. "kitty/tools/utils/base85"
  16. )
  17. func curve25519_key_pair() (private_key []byte, public_key []byte, err error) {
  18. curve := ecdh.X25519()
  19. privkey, err := curve.GenerateKey(rand.Reader)
  20. if err == nil {
  21. pubkey := privkey.PublicKey()
  22. return privkey.Bytes(), pubkey.Bytes(), nil
  23. }
  24. return nil, nil, err
  25. }
  26. func curve25519_derive_shared_secret(private_key []byte, public_key []byte) (secret []byte, err error) {
  27. prkey, err := ecdh.X25519().NewPrivateKey(private_key)
  28. if err != nil {
  29. return nil, fmt.Errorf("Invalid X25519 private key: %w", err)
  30. }
  31. pubkey, err := ecdh.X25519().NewPublicKey(public_key)
  32. if err != nil {
  33. return nil, fmt.Errorf("Invalid X25519 public key: %w", err)
  34. }
  35. secret, err = prkey.ECDH(pubkey)
  36. if err != nil {
  37. err = fmt.Errorf("Failed to perform ECDH shared secret derivation: %w", err)
  38. }
  39. return
  40. }
  41. func b85_encode(data []byte) (encoded string) {
  42. encoded = base85.EncodeToString(data)
  43. return
  44. }
  45. func b85_decode(data string) (decoded []byte, err error) {
  46. decoded, err = base85.DecodeString(data)
  47. return
  48. }
  49. func encrypt(plaintext []byte, alice_public_key []byte, encryption_protocol string) (iv []byte, tag []byte, ciphertext []byte, bob_public_key []byte, err error) {
  50. bob_private_key, bob_public_key, err := KeyPair(encryption_protocol)
  51. if err != nil {
  52. return
  53. }
  54. shared_secret_raw, err := curve25519_derive_shared_secret(bob_private_key, alice_public_key)
  55. if err != nil {
  56. return
  57. }
  58. shared_secret_hashed := sha256.Sum256(shared_secret_raw)
  59. shared_secret := shared_secret_hashed[:]
  60. block, err := aes.NewCipher(shared_secret)
  61. if err != nil {
  62. return
  63. }
  64. aesgcm, err := cipher.NewGCM(block)
  65. if err != nil {
  66. return
  67. }
  68. iv = make([]byte, aesgcm.NonceSize())
  69. _, err = rand.Read(iv)
  70. if err != nil {
  71. return
  72. }
  73. output := aesgcm.Seal(nil, iv, plaintext, nil)
  74. ciphertext = output[0 : len(output)-16]
  75. tag = output[len(output)-16:]
  76. return
  77. }
  78. func KeyPair(encryption_protocol string) (private_key []byte, public_key []byte, err error) {
  79. switch encryption_protocol {
  80. case "1":
  81. return curve25519_key_pair()
  82. default:
  83. err = fmt.Errorf("Unknown encryption protocol: %s", encryption_protocol)
  84. return
  85. }
  86. }
  87. func EncodePublicKey(pubkey []byte, encryption_protocol string) (ans string, err error) {
  88. switch encryption_protocol {
  89. case "1":
  90. ans = fmt.Sprintf("1:%s", b85_encode(pubkey))
  91. default:
  92. err = fmt.Errorf("Unknown encryption protocol: %s", encryption_protocol)
  93. return
  94. }
  95. return
  96. }
  97. func DecodePublicKey(raw string) (encryption_protocol string, pubkey []byte, err error) {
  98. encryption_protocol, encoded_pubkey, found := strings.Cut(raw, ":")
  99. if !found {
  100. return "", nil, fmt.Errorf("Invalid encoded pubkey, no : in string")
  101. }
  102. pubkey, err = b85_decode(encoded_pubkey)
  103. return
  104. }
  105. func Encrypt_cmd(cmd *utils.RemoteControlCmd, password string, other_pubkey []byte, encryption_protocol string) (encrypted_cmd utils.EncryptedRemoteControlCmd, err error) {
  106. cmd.Password = password
  107. cmd.Timestamp = time.Now().UnixNano()
  108. plaintext, err := json.Marshal(cmd)
  109. if err != nil {
  110. return
  111. }
  112. iv, tag, ciphertext, pubkey, err := encrypt(plaintext, other_pubkey, encryption_protocol)
  113. encrypted_cmd = utils.EncryptedRemoteControlCmd{
  114. Version: cmd.Version, IV: b85_encode(iv), Tag: b85_encode(tag), Pubkey: b85_encode(pubkey), Encrypted: b85_encode(ciphertext)}
  115. if encryption_protocol != "1" {
  116. encrypted_cmd.EncProto = encryption_protocol
  117. }
  118. return
  119. }
  120. func Encrypt_data(data []byte, other_pubkey []byte, encryption_protocol string) (ans []byte, err error) {
  121. d := make([]byte, 0, len(data)+32)
  122. d = append(d, []byte(fmt.Sprintf("%s:", strconv.FormatInt(time.Now().UnixNano(), 10)))...)
  123. d = append(d, data...)
  124. iv, tag, ciphertext, pubkey, err := encrypt(d, other_pubkey, encryption_protocol)
  125. if err != nil {
  126. return
  127. }
  128. ec := utils.EncryptedRemoteControlCmd{
  129. IV: b85_encode(iv), Tag: b85_encode(tag), Pubkey: b85_encode(pubkey), Encrypted: b85_encode(ciphertext)}
  130. if encryption_protocol != "1" {
  131. ec.EncProto = encryption_protocol
  132. }
  133. ans, err = json.Marshal(ec)
  134. return
  135. }
  136. // }}}