是的,Ruby中有一些加密和解密的庫(kù)可以使用。以下是一些常用的庫(kù):
openssl
gem來(lái)調(diào)用OpenSSL的功能。例如,你可以使用OpenSSL::Cipher
類(lèi)來(lái)創(chuàng)建一個(gè)加密和解密的cipher對(duì)象。安裝:gem install openssl
示例:
require 'openssl'
key = OpenSSL::PKey::RSA.new(2048)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.encrypt
cipher.key = key.export
cipher.iv = cipher.random_iv
plaintext = "Hello, World!"
ciphertext = cipher.update(plaintext) + cipher.final
puts "Plaintext: #{plaintext}"
puts "Ciphertext: #{ciphertext}"
安裝:gem install digest
示例:
require 'digest'
plaintext = "Hello, World!"
hash = Digest::SHA256.hexdigest(plaintext)
puts "Plaintext: #{plaintext}"
puts "Hash: #{hash}"
RbNaCl
和bcrypt
。安裝:gem install rbNaCl
(對(duì)于NaCl庫(kù))和gem install bcrypt
(對(duì)于bcrypt庫(kù))
示例(RbNaCl):
require 'rbnacl'
key = RbNaCl::Random.random_bytes(32)
cipher = RbNaCl::Cipher.new(:aes256_cbc)
cipher.encrypt(key, "Hello, World!")
ciphertext = cipher.finalize
puts "Plaintext: Hello, World!"
puts "Ciphertext: #{ciphertext.unpack1('H*')}"
示例(bcrypt):
require 'bcrypt'
password = "Hello, World!"
salt = BCrypt::Engine.random_salt
hashed_password = BCrypt::Password.create(password, salt: salt)
puts "Plaintext: #{password}"
puts "Hashed Password: #{hashed_password}"
根據(jù)你的需求,可以選擇合適的庫(kù)進(jìn)行加密和解密操作。