Class: AtprotoAuth::Encryption::Service

Inherits:
Object
  • Object
show all
Defined in:
lib/atproto_auth/encryption.rb

Overview

Core encryption service - used internally by serializers

Constant Summary collapse

CIPHER =
"aes-256-gcm"
VERSION =
1

Instance Method Summary collapse

Constructor Details

#initializeService

Returns a new instance of Service.



42
43
44
# File 'lib/atproto_auth/encryption.rb', line 42

def initialize
  @key_provider = KeyProvider.new
end

Instance Method Details

#decrypt(encrypted, context:) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/atproto_auth/encryption.rb', line 70

def decrypt(encrypted, context:)
  validate_decryption_inputs!(encrypted, context)
  validate_encrypted_data!(encrypted)

  iv = Base64.strict_decode64(encrypted[:iv])
  data = Base64.strict_decode64(encrypted[:data])
  auth_tag = Base64.strict_decode64(encrypted[:tag])

  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.decrypt
  cipher.key = @key_provider.key_for_context(context)
  cipher.iv = iv
  cipher.auth_tag = auth_tag
  cipher.auth_data = context.to_s

  cipher.update(data) + cipher.final
rescue ArgumentError => e
  raise DecryptionError, "Invalid encrypted data format: #{e.message}"
rescue StandardError => e
  raise DecryptionError, "Decryption failed: #{e.message}"
end

#encrypt(data, context:) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/atproto_auth/encryption.rb', line 46

def encrypt(data, context:)
  validate_encryption_inputs!(data, context)

  iv = SecureRandom.random_bytes(12)

  cipher = OpenSSL::Cipher.new(CIPHER)
  cipher.encrypt
  cipher.key = @key_provider.key_for_context(context)
  cipher.iv = iv
  cipher.auth_data = context.to_s

  encrypted = cipher.update(data.to_s) + cipher.final
  auth_tag = cipher.auth_tag

  {
    version: VERSION,
    iv: Base64.strict_encode64(iv),
    data: Base64.strict_encode64(encrypted),
    tag: Base64.strict_encode64(auth_tag)
  }
rescue StandardError => e
  raise EncryptionError, "Encryption failed: #{e.message}"
end