0
我遇到了這篇博客文章,其中介紹了他們如何加密他們的ID。爲了教育和娛樂的目的,我決定嘗試一下。雖然我不太明白。在博客上實現ID加密不會產生相同的輸出
如this blog post中所述,我是基於36編碼3DES加密的64位填充值,並保持得到的字符串長度爲25個字符。如何在不使用流密碼的情況下獲得13個字符(如網站聲明) - 博客聲稱使用3DES分組密碼。
下面是我使用的代碼:
require 'openssl'
SECRET_KEY = "secret"
ENCRYPTION_ALGO = "DES-EDE3-CBC"
def base36encode(s)
s.unpack('H*')[0].to_i(16).to_s 36
end
def base36decode(s36)
[s36.to_i(36).to_s(16)].pack 'H*'
end
def num_to_bits(n, bit_count=64)
#Array.new(bit_count) { |i| (n)[i] }.reverse!
sprintf('%064b', n).split("")
end
def bits_to_string(bits)
[bits.join("")].pack("B*")
end
def num_to_binstring(n, bit_count=64)
bits_to_string(num_to_bits(n, bit_count))
end
def binstring_to_num(str)
#elements = str.unpack("N*")
#(elements[0] << 32) | elements[1]
#
ans = 0
str.each_byte do |i|
ans = ans * 256 + i
end
ans
end
def encrypt(message, password)
cipher = OpenSSL::Cipher::Cipher.new(ENCRYPTION_ALGO)
cipher.encrypt
cipher.pkcs5_keyivgen(password)
ciphertext = cipher.update(message)
ciphertext << cipher.final
end
def decrypt(message, password)
cipher = OpenSSL::Cipher::Cipher.new(ENCRYPTION_ALGO)
cipher.decrypt
cipher.pkcs5_keyivgen(password)
decryptedtext = cipher.update(message)
decryptedtext << cipher.final
end
id = 12345678
puts "Encrypting: \"#{id}\""
num_string = num_to_binstring(id)
encrypted = encrypt(num_string, SECRET_KEY)
encoded = base36encode(encrypted).upcase
puts "Encrypted and encoded to: \"#{encoded}\" that's size is: #{encoded.length}\n"
decoded = base36decode(encoded.downcase)
decrypted = decrypt(decoded, SECRET_KEY)
string_num = binstring_to_num(decrypted)
puts "Decoded and decrypted to: \"#{string_num}\""
# ---- OUTPUT ---
# Encrypting: "12345678"
# Encrypted and encoded to: "49OMDVRHHMM24DVMODQU4X7JY" that's size is: 25
# Decoded and decrypted to: "12345678"