-1

我无法让 Perl 和 Ruby 就 CBC AES 达成一致:

Perl

use Crypt::CBC;
use MIME::Base64::Perl;

my $cipher = Crypt::CBC->new(
        -key         => 'd2cb415e067c7b13',
        -iv          => 'e36dc751d0433f05', #random 16chars!!!!!! shold NOT repeat between requests
        -cipher      => 'OpenSSL::AES',     #this is same as Rijndael
        -literal_key => 1,        
        -header      => "none",
        -keysize     => 16
  );  

$encypted = $cipher->encrypt("a really really long long text has differrent results???");
$base64 = encode_base64($encypted);

print("Ciphertext(b64): $base64");

$de_base64 = decode_base64($base64);
$decrypted = $cipher->decrypt($de_base64);
$c = $cipher->finish;

密文(b64):qz4eSQaFkQUkDOyJSbZf5W03HoldwtgvTLq0yJFRViKJnytf3PVSCGW2CYDjO+tRqV20oxeB2VPa 7NqN1TDSNQ==

节后有一个换行符2VPa,末尾有一个换行符

红宝石

require 'openssl'
require 'digest/sha2'
require 'base64'

message = "a really really long long text has differrent results???" 
cipher = OpenSSL::Cipher.new('aes-128-cbc')

# digest the key, iv and hmac_key so we have 16-byte length 
# also, it looks more of a funky password
# prepare cipher
cipher.encrypt
cipher.key = aes_key = "d2cb415e067c7b13"
cipher.iv = aes_iv = "e36dc751d0433f05"


encrypted = cipher.update(message)
encrypted << cipher.final()
b64_encoded = Base64.encode64(encrypted).encode('utf-8') #strict_encode64 guarantees no newlines, encode64 is default

puts "AES Key        : '#{aes_key}'"
puts "AES IV         : '#{aes_iv}'"
puts "Ciphertext(b64): '#{b64_encoded}'"

密文(b64):'qz4eSQaFkQUkDOyJSbZf5W03HoldwtgvTLq0yJFRViKJnytf3PVSCGW2CYDj O+tRqV20oxeB2VPa7NqN1TDSNQ=='

注意前后的newlines字符CYDj==

我看过以下内容:Perl & Ruby exchange AES encrypted information,但我没有使用padding=0

4

2 回答 2

7

换行符在 Base64 中并不重要。您从两种语言中得到完全相同的结果。

虽然绝对没有理由这样做,但您可以让 Perl 版本返回与 Ruby 版本相同的字符串,如下所示:

$base64 = encode_base64($encypted, '');
$base64 =~ s/\G.{60}\K/\n/sg;
于 2012-10-15T17:27:19.757 回答
3

encode_base64函数采用第二个参数,称为“eol”(行尾),默认情况下为“\n”。

返回的编码字符串被分成每行不超过 76 个字符的行,并且它将以 $eol 结尾,除非它为空

尝试:

$base64 = encode_base64($encypted, '');

反而。

于 2012-10-15T17:26:45.127 回答