DES以红宝石

时间:2015-04-22 09:06:32

标签: php ruby-on-rails ruby encryption openssl

我在我的ruby应用程序中使用了一些http apis,需要检查由DES加密的签名,我的代码使用OpenSSL::Cipher来执行此操作,但我在文档中显示了不同的答案。

DES模式是CBC。

标准输入:random1242timestamp1375685363

键:2-------

预期输出:041F03E83D85AD43B0BCE79FBB6841DAA87CC6C874BB71B45F5214DDF80BEB16

在php中有一个加密演示,我在用ruby加密时得到了不同的答案。

php代码:

<?php

class DES {
    var $key;
    var $iv; //偏移量

function GetKey($key) {
    $tmp = "--------";
    $key = substr ( $key . $tmp, 0, 8 );
    return $key;
}
function DES($key, $iv = 0) {

    //key长度8例如:1234abcd
    $this->key =$this->GetKey($key);
    if ($iv == 0) {
        $this->iv = $key;
    } else {
        $this->iv = $iv; //mcrypt_create_iv ( mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM );
    }
}

function encrypt($str) {
    //加密,返回大写十六进制字符串
    $size = mcrypt_get_block_size ( MCRYPT_DES, MCRYPT_MODE_CBC );
    $str = $this->pkcs5Pad ( $str, $size );
    return strtoupper ( bin2hex ( mcrypt_cbc ( MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->iv ) ) );
}

function decrypt($str) {
    //解密
    $strBin = $this->hex2bin ( strtolower ( $str ) );
    $str = mcrypt_cbc ( MCRYPT_DES, $this->key, $strBin, MCRYPT_DECRYPT, $this->iv );
    $str = $this->pkcs5Unpad ( $str );
    return $str;
}

function hex2bin($hexData) {
    $binData = "";
    for($i = 0; $i < strlen ( $hexData ); $i += 2) {
        $binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) );
    }
    return $binData;
}

function pkcs5Pad($text, $blocksize) {
    $pad = $blocksize - (strlen ( $text ) % $blocksize);
    return $text . str_repeat ( chr ( $pad ), $pad );
}

function pkcs5Unpad($text) {
    $pad = ord ( $text {strlen ( $text ) - 1} );
    if ($pad > strlen ( $text ))
        return false;
    if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad)
        return false;
    return substr ( $text, 0, - 1 * $pad );
}

} ?&GT;

我的红宝石代码:

class Des  
require 'openssl'
#require 'base64'
ALG = 'DES-CBC'  
KEY_LENGTH = 8
PADDING = '-'

def initialize key
    @cipher = OpenSSL::Cipher.new 'DES-CBC'
    @key = key.to_s.ljust KEY_LENGTH, PADDING
end

#加密
def encode(str,key = nil, options={})
    @cipher.encrypt
    @cipher.key = key.nil? ? @key : key.ljust(KEY_LENGTH, PADDING)

    plain = @cipher.update(str)
plain << @cipher.final
    unless options[:text]
                    plain = plain.to_hex_sequence.upcase
    end
    plain
end  

#解密    
def decode(plain,key = nil, options={})
    @cipher.key = key.nil? ? @key : key.ljust(KEY_LENGTH, PADDING)
    unless options[:text]
        plain = plain.de_hex_sequence
    end
    text = @cipher.update plain
    text << cipher.final
    text
end 

0 个答案:

没有答案