Perl 中的 AES 加密类似于 [电子邮件受保护]

问题描述 投票:0回答:1

以下 JavaScript 代码:

'use strict';
const CryptoJS = require('crypto-js');

const plaintext = 's3cret';
const password  = 'MyPassword';
//const iv   = CryptoJS.lib.WordArray.random(16);
//const salt = CryptoJS.lib.WordArray.random(16);
const iv   = CryptoJS.enc.Hex.parse("43c9ccba630fe1cd61fc2bdb90121c6f"); // For testing
const salt = CryptoJS.enc.Hex.parse("5c788a415851e909d9c7951717714204"); // For testing
const key = CryptoJS.PBKDF2(password, salt, {keySize: 128/32, iterations: 1000});
const b64ciphertext = CryptoJS.AES.encrypt(plaintext, key, {iv: iv}).ciphertext.toString(CryptoJS.enc.Base64);
console.log(b64ciphertext);
  1. 使用
    [email protected]
    ,产生:
eiJkaAmCVjHFKbvY/CnkvQ==
  1. 使用
    [email protected]
    ,产生:
qT1Vtod7ihS2wvtwmlnPow==

[email protected]
输出的 Perl 等效项由这个答案提供:

use strict;
use warnings;
use feature qw( say );

use Crypt::CBC    qw( );
use Crypt::PBKDF2 qw( );
use Mojo::Util qw(b64_encode);

my $plaintext = 's3cret';
my $password  = 'MyPassword';
#my $iv   = Crypt::CBC->random_bytes( 16 );
#my $salt = Crypt::CBC->random_bytes( 16 );
my $iv   = pack( "H*", "43c9ccba630fe1cd61fc2bdb90121c6f" ); # For testing
my $salt = pack( "H*", "5c788a415851e909d9c7951717714204" ); # For testing

my $pbkdf2 = Crypt::PBKDF2->new(output_len=>128/8, iterations=>1000);
my $key = $pbkdf2->PBKDF2($salt,$password);
my $cipher = Crypt::CBC->new(
                 -cipher  => 'Cipher::AES',
                 -header  => 'none',
                 -pbkdf   => 'none',
                 -keysize => length($key),
                 -key     => $key,
                 -iv      => $iv
                );
my $ciphertext = $cipher->encrypt( $plaintext );
my $b64ciphertext = b64_encode($ciphertext,'');

say $b64ciphertext;

使用 Perl,如何获得类似于

[email protected]
的输出?

javascript perl encryption aes cryptojs
1个回答
0
投票

CryptoJS,v4.1.1 默认使用 SHA1 作为 PBKDF2 摘要,CryptoJS,v4.2.0 默认使用 SHA256。为了在 Perl 代码中使用 SHA256,您必须添加

hash_class => 'HMACSHA2'
,即:

my $pbkdf2 = Crypt::PBKDF2->new(output_len=>128/8, iterations=>1000, hash_class => 'HMACSHA2');

为了完整性:在 CryptoJS 中,还可以使用

hasher
选项显式设置摘要:以下代码还将在 v4.1.1 下使用 SHA256 作为 PBKDF2 摘要:

const key = CryptoJS.PBKDF2(password, salt, {keySize: 128/32, iterations: 1000, hasher: CryptoJS.algo.SHA256}); 

请注意,CryptoJS 最近已停产并且不再维护。

© www.soinside.com 2019 - 2024. All rights reserved.