Ruby下使用OpenSSL lib DES對稱式加密輸出
Sample Code如下:
===================================
#!/usr/bin/ruby
require "openssl"
class Encrypt
KEY = "abcdefghijklmnopqrstuvwxyz"
IV = "asdasdasdasdasdasdasdasdas"
CIPHER = "DES" #CIPHER是使用的加密方法
def des_encrypt(plaintext)
c = OpenSSL::Cipher::Cipher.new(CIPHER)
c.encrypt
c.key = KEY
c.iv = IV
ret = c.update(plaintext)
ret << c.final
end
def des_decrypt(encrypt_value)
c = OpenSSL::Cipher::Cipher.new(CIPHER)
c.decrypt
c.key = KEY
c.iv = IV
ret = c.update(encrypt_value)
ret << c.final
end
end
def gotorun
e = Encrypt.new
source = "a secret message"
puts "source :#{source}"
value = e.des_encrypt(source)
puts "encode :#{value}"
puts "encode hex:#{value.unpack('H*')[0]}"
puts "decode hex:#{[value.unpack('H*')[0]].pack('H*')}"
des_decrypt = e.des_decrypt(value)
puts "decode :#{des_decrypt}"
end
gotorun
=====================================
===================================
#!/usr/bin/ruby
require "openssl"
class Encrypt
KEY = "abcdefghijklmnopqrstuvwxyz"
IV = "asdasdasdasdasdasdasdasdas"
CIPHER = "DES" #CIPHER是使用的加密方法
def des_encrypt(plaintext)
c = OpenSSL::Cipher::Cipher.new(CIPHER)
c.encrypt
c.key = KEY
c.iv = IV
ret = c.update(plaintext)
ret << c.final
end
def des_decrypt(encrypt_value)
c = OpenSSL::Cipher::Cipher.new(CIPHER)
c.decrypt
c.key = KEY
c.iv = IV
ret = c.update(encrypt_value)
ret << c.final
end
end
def gotorun
e = Encrypt.new
source = "a secret message"
puts "source :#{source}"
value = e.des_encrypt(source)
puts "encode :#{value}"
puts "encode hex:#{value.unpack('H*')[0]}"
puts "decode hex:#{[value.unpack('H*')[0]].pack('H*')}"
des_decrypt = e.des_decrypt(value)
puts "decode :#{des_decrypt}"
end
gotorun
=====================================
留言
張貼留言