encryptable 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/.standard.yml +13 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/LICENSE.txt +21 -0
- data/README.md +138 -0
- data/Rakefile +10 -0
- data/encryptable.gemspec +36 -0
- data/examples/README.md +20 -0
- data/examples/advanced_usage.rb +27 -0
- data/examples/basic_usage.rb +20 -0
- data/examples/key.rb +22 -0
- data/lib/encryptable/cipher.rb +68 -0
- data/lib/encryptable/configuration.rb +10 -0
- data/lib/encryptable/decryption_handler.rb +61 -0
- data/lib/encryptable/encryption_handler.rb +49 -0
- data/lib/encryptable/version.rb +5 -0
- data/lib/encryptable.rb +23 -0
- data/sig/encryptable.rbs +4 -0
- metadata +68 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: 4b63346e699987deec098df1553a41c40af7e9f3bf65524adfd2e24e9150cbca
|
4
|
+
data.tar.gz: 8fdcdace4cfe4bb291cbf3aca5ffc90b89fb1cf32bd232b4db82ad008c52351a
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: ae726fe9c441a375b1d10ab858b79b93e6923e459119f85ce958a343672eb028f21a2f2e2f4e5c124e13a4e9abc2b43f2421d495d2b715b73e51060624d20e50
|
7
|
+
data.tar.gz: dfb35ad838c75836ef1477a0f3e17ebb82c0c7fe0c5df3c2ebf252d30e77325e78048b3f9e938d9f5d17416db328272f0fa09359819e6f4fcc4c443df1925667
|
data/.rspec
ADDED
data/.standard.yml
ADDED
@@ -0,0 +1,13 @@
|
|
1
|
+
# For available configuration options, see:
|
2
|
+
# https://github.com/testdouble/standard
|
3
|
+
ruby_version: 2.6
|
4
|
+
|
5
|
+
inherit_gem:
|
6
|
+
standard: config/base.yml
|
7
|
+
Style/StringLiterals:
|
8
|
+
Enabled: false
|
9
|
+
AllCops:
|
10
|
+
Exclude:
|
11
|
+
- "spec/**/*"
|
12
|
+
Metrics/BlockLength:
|
13
|
+
Max: 100
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at radon1284@yahoo.com. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2023 raketbizdev
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,138 @@
|
|
1
|
+
# Encryptable
|
2
|
+
|
3
|
+
**Encryptable** is a lightweight and versatile Ruby gem crafted to provide seamless encryption and decryption functionalities. Whether you're building a standalone Ruby application or a Rails-powered web service, Encryptable allows you to maintain the confidentiality of your data with ease.
|
4
|
+
|
5
|
+
### Features:
|
6
|
+
|
7
|
+
- **AES-256-CBC Algorithm:** By default, Encryptable uses the robust and widely recognized AES-256-CBC encryption algorithm, ensuring that your data remains secure.
|
8
|
+
|
9
|
+
- **Base64 Encoding:** After encryption, the data is encoded in Base64 format, making it easier to store in databases or transmit over networks.
|
10
|
+
|
11
|
+
- **Customizable Key and IV:** While the gem provides methods to generate secure keys and initialization vectors (IVs), users can also provide their own to tailor the encryption process to their needs.
|
12
|
+
|
13
|
+
- **Error Handling:** Transparent error messages are provided for common issues such as invalid Base64 strings or incorrect key/IV lengths, making debugging a breeze.
|
14
|
+
|
15
|
+
- **Rails Integration:** Easily integrate **Encryptable** with Rails models to encrypt sensitive attributes before storing them in your database.
|
16
|
+
|
17
|
+
Whether you're looking to securely store user passwords, encrypt sensitive configuration data, or simply want an easy-to-use encryption tool, Encryptable has got you covered!
|
18
|
+
|
19
|
+
## Usage
|
20
|
+
|
21
|
+
### Setup
|
22
|
+
|
23
|
+
1. First, make sure you have added the encryptable gem to your Gemfile:
|
24
|
+
|
25
|
+
```
|
26
|
+
gem 'encryptable'
|
27
|
+
```
|
28
|
+
|
29
|
+
2. Run bundle install to install the gem.
|
30
|
+
|
31
|
+
3. Create an initializer for the Encryptable configuration. This can be done in **`config/initializers/encryptable.rb`:**
|
32
|
+
|
33
|
+
```ruby
|
34
|
+
# config/initializers/encryptable.rb
|
35
|
+
|
36
|
+
Encryptable.configure do |config|
|
37
|
+
# You might want to use Rails secrets or credentials to store these values
|
38
|
+
config.key = Rails.application.credentials.encryptable[:key] || "YOUR_DEFAULT_KEY"
|
39
|
+
config.iv = Rails.application.credentials.encryptable[:iv] || "YOUR_DEFAULT_IV"
|
40
|
+
end
|
41
|
+
```
|
42
|
+
|
43
|
+
### Basic Usage
|
44
|
+
|
45
|
+
```ruby
|
46
|
+
# Encryption
|
47
|
+
plaintext = "Ruel Nopal"
|
48
|
+
encrypted_text = Encryptable.cipher.encrypt(plaintext)
|
49
|
+
puts "Encrypted Text: #{encrypted_text}"
|
50
|
+
|
51
|
+
# Decryption
|
52
|
+
decrypted_text = Encryptable.cipher.decrypt(encrypted_text)
|
53
|
+
puts "Decrypted Text: #{decrypted_text}"
|
54
|
+
|
55
|
+
```
|
56
|
+
|
57
|
+
### Generating Key and IV
|
58
|
+
|
59
|
+
To generate a secure key and IV, you can use the following code:
|
60
|
+
|
61
|
+
```ruby
|
62
|
+
require "openssl"
|
63
|
+
|
64
|
+
def generate_key_iv(key_length: 32, iv_length: 16)
|
65
|
+
key = OpenSSL::Random.random_bytes(key_length)
|
66
|
+
iv = OpenSSL::Random.random_bytes(iv_length)
|
67
|
+
|
68
|
+
# Convert them to base64 format (easier to store in environment variables)
|
69
|
+
key_base64 = [key].pack("m0")
|
70
|
+
iv_base64 = [iv].pack("m0")
|
71
|
+
|
72
|
+
[key_base64, iv_base64]
|
73
|
+
end
|
74
|
+
|
75
|
+
# Default values
|
76
|
+
key_base64, iv_base64 = generate_key_iv
|
77
|
+
puts "Key (Default): #{key_base64}"
|
78
|
+
puts "IV (Default): #{iv_base64}"
|
79
|
+
|
80
|
+
# Example with custom values
|
81
|
+
# key_base64, iv_base64 = generate_key_iv(key_length: 24, iv_length: 12)
|
82
|
+
# puts "Key (Custom): #{key_base64}"
|
83
|
+
# puts "IV (Custom): #{iv_base64}"
|
84
|
+
```
|
85
|
+
|
86
|
+
After generating the key and IV, you can use them in the Encryptable configuration as shown in the basic usage example.
|
87
|
+
|
88
|
+
### Using with Rails Models
|
89
|
+
|
90
|
+
Consider a **`Profile`** model where you want to save encrypted **`first_name`** and **`last_name`**.
|
91
|
+
|
92
|
+
```ruby
|
93
|
+
class Profile < ApplicationRecord
|
94
|
+
before_save :encrypt_name
|
95
|
+
|
96
|
+
private
|
97
|
+
|
98
|
+
def encrypt_name
|
99
|
+
self.first_name = Encryptable.cipher.encrypt(self.first_name)
|
100
|
+
self.last_name = Encryptable.cipher.encrypt(self.last_name)
|
101
|
+
end
|
102
|
+
end
|
103
|
+
```
|
104
|
+
|
105
|
+
When saving the profile:
|
106
|
+
|
107
|
+
```ruby
|
108
|
+
profile = Profile.new(first_name: "Ruel", last_name: "Nopal")
|
109
|
+
profile.save # The names will be encrypted before saving
|
110
|
+
```
|
111
|
+
|
112
|
+
To decrypt them when needed:
|
113
|
+
|
114
|
+
```ruby
|
115
|
+
decrypted_first_name = Encryptable.cipher.decrypt(profile.first_name)
|
116
|
+
decrypted_last_name = Encryptable.cipher.decrypt(profile.last_name)
|
117
|
+
```
|
118
|
+
|
119
|
+
## Development
|
120
|
+
|
121
|
+
If you'd like to contribute to this gem:
|
122
|
+
|
123
|
+
1. Fork the repository.
|
124
|
+
2. Clone your fork and create a new branch for your feature or fix.
|
125
|
+
3. Install dependencies with `bundle install`.
|
126
|
+
4. Make your changes and ensure tests pass with `bundle exec rspec`.
|
127
|
+
5. Commit your changes and push to your branch.
|
128
|
+
6. Open a pull request.
|
129
|
+
|
130
|
+
All contributions are greatly appreciated. Make sure to add tests for new features and bug fixes!
|
131
|
+
|
132
|
+
## License
|
133
|
+
|
134
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
135
|
+
|
136
|
+
## Code of Conduct
|
137
|
+
|
138
|
+
Everyone interacting in the Encryptable project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/raketbizdev/encryptable/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
data/encryptable.gemspec
ADDED
@@ -0,0 +1,36 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "lib/encryptable/version"
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = "encryptable"
|
7
|
+
spec.version = Encryptable::VERSION
|
8
|
+
spec.authors = ["raketbizdev"]
|
9
|
+
spec.email = ["radon1284@yahoo.com"]
|
10
|
+
|
11
|
+
spec.summary = "A simple encryption and decryption library for Ruby on Rails applications."
|
12
|
+
spec.description = "The Encryptable gem provides an easy-to-use module for encrypting and decrypting data in Ruby on Rails applications. It utilizes the AES-256-CBC encryption method from the OpenSSL library."
|
13
|
+
spec.homepage = "https://github.com/raketbizdev/encryptable" # Replace with your actual repository URL
|
14
|
+
spec.license = "MIT"
|
15
|
+
spec.required_ruby_version = ">= 2.6.0"
|
16
|
+
|
17
|
+
spec.metadata["allowed_push_host"] = "https://rubygems.org" # Default RubyGems server
|
18
|
+
spec.metadata["homepage_uri"] = spec.homepage
|
19
|
+
spec.metadata["source_code_uri"] = "https://github.com/raketbizdev/encryptable" # Replace with your actual repository URL
|
20
|
+
spec.metadata["changelog_uri"] = "https://github.com/raketbizdev/encryptable/CHANGELOG.md" # If you maintain a CHANGELOG.md file
|
21
|
+
|
22
|
+
# Specify which files should be added to the gem when it is released.
|
23
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
24
|
+
spec.files = Dir.chdir(__dir__) do
|
25
|
+
`git ls-files -z`.split("\x0").reject do |f|
|
26
|
+
(File.expand_path(f) == __FILE__) ||
|
27
|
+
f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
|
28
|
+
end
|
29
|
+
end
|
30
|
+
spec.bindir = "exe"
|
31
|
+
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
32
|
+
spec.require_paths = ["lib"]
|
33
|
+
|
34
|
+
# Uncomment to register a new dependency of your gem
|
35
|
+
# spec.add_dependency "example-gem", "~> 1.0"
|
36
|
+
end
|
data/examples/README.md
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
# Encryptable Gem - Examples
|
2
|
+
|
3
|
+
This directory contains basic and advanced examples demonstrating the usage of the `Encryptable` gem.
|
4
|
+
|
5
|
+
## Files
|
6
|
+
|
7
|
+
- `basic_usage.rb`: Demonstrates the basic functionalities of the gem, including encryption and decryption.
|
8
|
+
- `advanced_usage.rb`: Showcases advanced features, such as using a custom configuration for one-time encryption/decryption.
|
9
|
+
|
10
|
+
## Running the Examples
|
11
|
+
|
12
|
+
To run an example, navigate to the root directory of the gem and execute:
|
13
|
+
|
14
|
+
```
|
15
|
+
$ ruby examples/basic_usage.rb
|
16
|
+
```
|
17
|
+
|
18
|
+
Replace `basic_usage.rb` with the desired example file.
|
19
|
+
|
20
|
+
**Note**: Before running the examples, ensure that you replace placeholders like `YOUR_ENCRYPTION_KEY` and `YOUR_INITIALIZATION_VECTOR` with actual values.
|
@@ -0,0 +1,27 @@
|
|
1
|
+
# Advanced Usage of the Encryptable Gem
|
2
|
+
|
3
|
+
$LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
|
4
|
+
require "encryptable"
|
5
|
+
|
6
|
+
# Configuration
|
7
|
+
|
8
|
+
new_key = "4oUYHawiAdtCb0mqFndKCZce44PRQ/2+3Tx9iCFUODw="
|
9
|
+
new_iv = "4cSIjYL2YBZsz84kjme0+Q=="
|
10
|
+
|
11
|
+
Encryptable.configure do |config|
|
12
|
+
config.key = new_key
|
13
|
+
config.iv = new_iv
|
14
|
+
end
|
15
|
+
|
16
|
+
# Custom Configuration for One-time Use
|
17
|
+
# I'm using the same key and IV for this example, but in a real scenario, you might want different values.
|
18
|
+
custom_cipher = Encryptable::Cipher.new(key: new_key, iv: new_iv)
|
19
|
+
|
20
|
+
# Encryption with Custom Configuration
|
21
|
+
plaintext = "Advanced Encryption"
|
22
|
+
encrypted_text = custom_cipher.encrypt(plaintext)
|
23
|
+
puts "Encrypted Text with Custom Configuration: #{encrypted_text}"
|
24
|
+
|
25
|
+
# Decryption with Custom Configuration
|
26
|
+
decrypted_text = custom_cipher.decrypt(encrypted_text)
|
27
|
+
puts "Decrypted Text with Custom Configuration: #{decrypted_text}"
|
@@ -0,0 +1,20 @@
|
|
1
|
+
# Basic Usage of the Encryptable Gem
|
2
|
+
|
3
|
+
$LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
|
4
|
+
require "encryptable"
|
5
|
+
require "base64"
|
6
|
+
|
7
|
+
# Configuration
|
8
|
+
Encryptable.configure do |config|
|
9
|
+
config.key = "4oUYHawiAdtCb0mqFndKCZce44PRQ/2+3Tx9iCFUODw="
|
10
|
+
config.iv = "4cSIjYL2YBZsz84kjme0+Q=="
|
11
|
+
end
|
12
|
+
|
13
|
+
# Encryption
|
14
|
+
plaintext = "Ruel Nopal"
|
15
|
+
encrypted_text = Encryptable.cipher.encrypt(plaintext)
|
16
|
+
puts "Encrypted Text: #{encrypted_text}"
|
17
|
+
|
18
|
+
# Decryption
|
19
|
+
decrypted_text = Encryptable.cipher.decrypt(encrypted_text)
|
20
|
+
puts "Decrypted Text: #{decrypted_text}"
|
data/examples/key.rb
ADDED
@@ -0,0 +1,22 @@
|
|
1
|
+
require "openssl"
|
2
|
+
|
3
|
+
def generate_key_iv(key_length: 32, iv_length: 16)
|
4
|
+
key = OpenSSL::Random.random_bytes(key_length)
|
5
|
+
iv = OpenSSL::Random.random_bytes(iv_length)
|
6
|
+
|
7
|
+
# Convert them to base64 format (easier to store in environment variables)
|
8
|
+
key_base64 = [key].pack("m0")
|
9
|
+
iv_base64 = [iv].pack("m0")
|
10
|
+
|
11
|
+
[key_base64, iv_base64]
|
12
|
+
end
|
13
|
+
|
14
|
+
# Default values
|
15
|
+
key_base64, iv_base64 = generate_key_iv
|
16
|
+
puts "Key (Default): #{key_base64}"
|
17
|
+
puts "IV (Default): #{iv_base64}"
|
18
|
+
|
19
|
+
# Example with custom values
|
20
|
+
# key_base64, iv_base64 = generate_key_iv(key_length: 24, iv_length: 12)
|
21
|
+
# puts "Key (Custom): #{key_base64}"
|
22
|
+
# puts "IV (Custom): #{iv_base64}"
|
@@ -0,0 +1,68 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# standard:ignore Metrics/BlockLength
|
4
|
+
|
5
|
+
require 'openssl'
|
6
|
+
require 'base64'
|
7
|
+
require 'digest'
|
8
|
+
require_relative 'encryption_handler'
|
9
|
+
require_relative 'decryption_handler'
|
10
|
+
|
11
|
+
module Encryptable
|
12
|
+
# This class handles encryption and decryption using AES-256-CBC algorithm.
|
13
|
+
class Cipher
|
14
|
+
ALGORITHM = 'AES-256-CBC'
|
15
|
+
|
16
|
+
def initialize(key:, iv:)
|
17
|
+
validate_string_inputs!(key, iv)
|
18
|
+
decode_key_and_iv!(key, iv)
|
19
|
+
validate_lengths!
|
20
|
+
derive_key_and_iv!
|
21
|
+
end
|
22
|
+
|
23
|
+
def encrypt(value)
|
24
|
+
EncryptionHandler.encrypt(value, @key, @iv, ALGORITHM)
|
25
|
+
end
|
26
|
+
|
27
|
+
def decrypt(value)
|
28
|
+
DecryptionHandler.decrypt(value, @key, @iv, ALGORITHM)
|
29
|
+
end
|
30
|
+
|
31
|
+
private
|
32
|
+
|
33
|
+
def validate_string_inputs!(key, iv)
|
34
|
+
raise 'Initialization failed: Key and IV should be strings.' unless key.is_a?(String) && iv.is_a?(String)
|
35
|
+
end
|
36
|
+
|
37
|
+
def decode_key_and_iv!(key, iv)
|
38
|
+
@original_key = Base64.decode64(key)
|
39
|
+
@original_iv = Base64.decode64(iv)
|
40
|
+
rescue ArgumentError
|
41
|
+
raise 'Initialization failed: Key or IV is not a valid Base64 encoded string.'
|
42
|
+
end
|
43
|
+
|
44
|
+
def derive_key_and_iv!
|
45
|
+
@key = derive_key(@original_key, 32)
|
46
|
+
@iv = derive_key(@original_iv, 16)
|
47
|
+
end
|
48
|
+
|
49
|
+
def validate_lengths!
|
50
|
+
if @original_key.bytesize < 32
|
51
|
+
raise ArgumentError, 'Key length is below the minimum required (32 bytes).'
|
52
|
+
elsif @original_key.bytesize > 32
|
53
|
+
raise ArgumentError, 'Key length exceeds the maximum allowed (32 bytes).'
|
54
|
+
end
|
55
|
+
|
56
|
+
if @original_iv.bytesize < 16
|
57
|
+
raise ArgumentError, 'IV length is below the minimum required (16 bytes).'
|
58
|
+
elsif @original_iv.bytesize > 16
|
59
|
+
raise ArgumentError, 'IV length exceeds the maximum allowed (16 bytes).'
|
60
|
+
end
|
61
|
+
end
|
62
|
+
|
63
|
+
def derive_key(input, desired_length)
|
64
|
+
hashed = OpenSSL::Digest::SHA256.digest(input)
|
65
|
+
hashed[0, desired_length]
|
66
|
+
end
|
67
|
+
end
|
68
|
+
end
|
@@ -0,0 +1,61 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# standard:ignore Metrics/BlockLength
|
4
|
+
|
5
|
+
# decryption_handler.rb
|
6
|
+
# DecryptionHandler
|
7
|
+
module DecryptionHandler
|
8
|
+
def self.decrypt(value, key, iv, algorithm)
|
9
|
+
return if value.nil?
|
10
|
+
|
11
|
+
decoded = decode_input(value)
|
12
|
+
validate_decoded_input!(decoded)
|
13
|
+
|
14
|
+
cipher = setup_cipher(key, iv, algorithm)
|
15
|
+
decrypted_value = decrypt_value(cipher, decoded)
|
16
|
+
|
17
|
+
decrypted_value
|
18
|
+
rescue OpenSSL::Cipher::CipherError => e
|
19
|
+
handle_decryption_error(e)
|
20
|
+
rescue ArgumentError => e
|
21
|
+
if e.message.match?(/invalid base64/)
|
22
|
+
raise 'Decryption failed: The input data is not a valid Base64 encoded string.'
|
23
|
+
else
|
24
|
+
raise e
|
25
|
+
end
|
26
|
+
end
|
27
|
+
|
28
|
+
def self.validate_decoded_input!(decoded)
|
29
|
+
if decoded.bytesize % 16 != 0
|
30
|
+
raise 'Decryption failed: The input data is not a valid Base64 encoded string.'
|
31
|
+
end
|
32
|
+
end
|
33
|
+
|
34
|
+
private
|
35
|
+
|
36
|
+
def self.decode_input(value)
|
37
|
+
Base64.decode64(value.encode('ascii-8bit'))
|
38
|
+
end
|
39
|
+
|
40
|
+
def self.setup_cipher(key, iv, algorithm)
|
41
|
+
cipher = OpenSSL::Cipher.new(algorithm)
|
42
|
+
cipher.decrypt
|
43
|
+
cipher.key = key
|
44
|
+
cipher.iv = iv
|
45
|
+
cipher
|
46
|
+
end
|
47
|
+
|
48
|
+
def self.decrypt_value(cipher, decoded)
|
49
|
+
cipher.update(decoded) + cipher.final
|
50
|
+
end
|
51
|
+
|
52
|
+
def self.handle_decryption_error(e)
|
53
|
+
if e.message == 'bad decrypt'
|
54
|
+
raise 'Decryption failed: The provided key or IV might be incorrect.'
|
55
|
+
elsif e.message.include?('wrong final block length')
|
56
|
+
raise 'Decryption failed: The encrypted data might be corrupted.'
|
57
|
+
else
|
58
|
+
raise "Decryption failed: #{e.message}"
|
59
|
+
end
|
60
|
+
end
|
61
|
+
end
|
@@ -0,0 +1,49 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# standard:ignore Metrics/BlockLength
|
4
|
+
|
5
|
+
# encryption_handler.rb
|
6
|
+
|
7
|
+
# EncryptionHandler
|
8
|
+
|
9
|
+
module EncryptionHandler
|
10
|
+
def self.encrypt(value, key, iv, algorithm)
|
11
|
+
validate_input(value)
|
12
|
+
return if value.nil?
|
13
|
+
|
14
|
+
cipher = setup_cipher(key, iv, algorithm)
|
15
|
+
encrypted = encrypt_value(cipher, value)
|
16
|
+
|
17
|
+
Base64.encode64(encrypted).encode('utf-8')
|
18
|
+
rescue OpenSSL::Cipher::CipherError => e
|
19
|
+
handle_encryption_error(e)
|
20
|
+
end
|
21
|
+
|
22
|
+
private
|
23
|
+
|
24
|
+
def self.validate_input(value)
|
25
|
+
unless value.is_a?(String)
|
26
|
+
raise 'Encryption failed: The input value should be a string.'
|
27
|
+
end
|
28
|
+
end
|
29
|
+
|
30
|
+
def self.setup_cipher(key, iv, algorithm)
|
31
|
+
cipher = OpenSSL::Cipher.new(algorithm)
|
32
|
+
cipher.encrypt
|
33
|
+
cipher.key = key
|
34
|
+
cipher.iv = iv
|
35
|
+
cipher
|
36
|
+
end
|
37
|
+
|
38
|
+
def self.encrypt_value(cipher, value)
|
39
|
+
cipher.update(value) + cipher.final
|
40
|
+
end
|
41
|
+
|
42
|
+
def self.handle_encryption_error(e)
|
43
|
+
if e.message == 'data not multiple of block length'
|
44
|
+
raise 'Encryption failed: The input data is not a multiple of the block length.'
|
45
|
+
else
|
46
|
+
raise 'Encryption failed: #{e.message}'
|
47
|
+
end
|
48
|
+
end
|
49
|
+
end
|
data/lib/encryptable.rb
ADDED
@@ -0,0 +1,23 @@
|
|
1
|
+
require "encryptable/cipher"
|
2
|
+
require "encryptable/configuration"
|
3
|
+
|
4
|
+
module Encryptable
|
5
|
+
class << self
|
6
|
+
attr_writer :configuration
|
7
|
+
end
|
8
|
+
|
9
|
+
def self.configuration
|
10
|
+
@configuration ||= Configuration.new
|
11
|
+
end
|
12
|
+
|
13
|
+
def self.configure
|
14
|
+
yield(configuration)
|
15
|
+
end
|
16
|
+
|
17
|
+
def self.cipher
|
18
|
+
Cipher.new(
|
19
|
+
key: configuration.key,
|
20
|
+
iv: configuration.iv
|
21
|
+
)
|
22
|
+
end
|
23
|
+
end
|
data/sig/encryptable.rbs
ADDED
metadata
ADDED
@@ -0,0 +1,68 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: encryptable
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- raketbizdev
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2023-08-24 00:00:00.000000000 Z
|
12
|
+
dependencies: []
|
13
|
+
description: The Encryptable gem provides an easy-to-use module for encrypting and
|
14
|
+
decrypting data in Ruby on Rails applications. It utilizes the AES-256-CBC encryption
|
15
|
+
method from the OpenSSL library.
|
16
|
+
email:
|
17
|
+
- radon1284@yahoo.com
|
18
|
+
executables: []
|
19
|
+
extensions: []
|
20
|
+
extra_rdoc_files: []
|
21
|
+
files:
|
22
|
+
- ".rspec"
|
23
|
+
- ".standard.yml"
|
24
|
+
- CHANGELOG.md
|
25
|
+
- CODE_OF_CONDUCT.md
|
26
|
+
- LICENSE.txt
|
27
|
+
- README.md
|
28
|
+
- Rakefile
|
29
|
+
- encryptable.gemspec
|
30
|
+
- examples/README.md
|
31
|
+
- examples/advanced_usage.rb
|
32
|
+
- examples/basic_usage.rb
|
33
|
+
- examples/key.rb
|
34
|
+
- lib/encryptable.rb
|
35
|
+
- lib/encryptable/cipher.rb
|
36
|
+
- lib/encryptable/configuration.rb
|
37
|
+
- lib/encryptable/decryption_handler.rb
|
38
|
+
- lib/encryptable/encryption_handler.rb
|
39
|
+
- lib/encryptable/version.rb
|
40
|
+
- sig/encryptable.rbs
|
41
|
+
homepage: https://github.com/raketbizdev/encryptable
|
42
|
+
licenses:
|
43
|
+
- MIT
|
44
|
+
metadata:
|
45
|
+
allowed_push_host: https://rubygems.org
|
46
|
+
homepage_uri: https://github.com/raketbizdev/encryptable
|
47
|
+
source_code_uri: https://github.com/raketbizdev/encryptable
|
48
|
+
changelog_uri: https://github.com/raketbizdev/encryptable/CHANGELOG.md
|
49
|
+
post_install_message:
|
50
|
+
rdoc_options: []
|
51
|
+
require_paths:
|
52
|
+
- lib
|
53
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
54
|
+
requirements:
|
55
|
+
- - ">="
|
56
|
+
- !ruby/object:Gem::Version
|
57
|
+
version: 2.6.0
|
58
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
59
|
+
requirements:
|
60
|
+
- - ">="
|
61
|
+
- !ruby/object:Gem::Version
|
62
|
+
version: '0'
|
63
|
+
requirements: []
|
64
|
+
rubygems_version: 3.3.7
|
65
|
+
signing_key:
|
66
|
+
specification_version: 4
|
67
|
+
summary: A simple encryption and decryption library for Ruby on Rails applications.
|
68
|
+
test_files: []
|