溫馨提示×

Ruby加密與解密有相關工具嗎

小樊
101
2024-11-05 19:18:29
欄目: 編程語言

是的,Ruby中有一些加密和解密的庫可以使用。以下是一些常用的庫:

  1. OpenSSL:OpenSSL是一個強大的加密庫,提供了許多加密算法。在Ruby中,你可以使用openssl gem來調用OpenSSL的功能。例如,你可以使用OpenSSL::Cipher類來創建一個加密和解密的cipher對象。

安裝: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}"
  1. Digest:Digest庫提供了多種哈希算法,如MD5、SHA-1、SHA-256等。你可以使用這些算法對數據進行加密(實際上是生成哈希值)。

安裝:gem install digest

示例:

require 'digest'

plaintext = "Hello, World!"
hash = Digest::SHA256.hexdigest(plaintext)

puts "Plaintext: #{plaintext}"
puts "Hash: #{hash}"
  1. Ruby加密庫:除了上述庫外,還有一些專門用于加密和解密的Ruby庫,如RbNaClbcrypt。

安裝:gem install rbNaCl(對于NaCl庫)和gem install bcrypt(對于bcrypt庫)

示例(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}"

根據你的需求,可以選擇合適的庫進行加密和解密操作。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女