2011-05-23 46 views
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" 

回答

1

什麼尺寸的加密輸出,你base36編碼過嗎?我的猜測是你的代碼在CBC模式下進行加密(假設你的代碼提到了pkcs5)並且你得到了IV和密文,總共有16個字節。我從博客文章推斷,作者正在使用ECB模式,您可能認爲是「原始」3DES,這通常是在大多數情況下都是錯誤的,但在這裏看起來似乎合理。

相關問題