📜  Perl 中的加密和解密

📅  最后修改于: 2022-05-13 01:55:19.255000             🧑  作者: Mango

Perl 中的加密和解密

Perl 中的Crypt函数基本上用于存储敏感数据和密码,使用 ASCII字符作为加密字符串(该函数对字符串进行加密)。字符串只能被加密,不能像加密一样被解密。

注意: $salt变量可以是以下给定集合中任意两个字符的组合:

['.', '/', 0..9, 'A'..'Z', 'a'..'z']

我们可以使用/包含除此给定字符,此集仅用于推荐目的。加密字符串中的前两个字符存储为盐字符,可用于以后的比较。我们甚至可以使用rand函数(随机选择)来选择盐的字符。如果在$字符串或 $salt中进行了小的更改,我们可以观察 / 看到结果 / 最终加密字符串的巨大变化。
示例:下面是说明上述加密函数的示例。

Perl
#!usr/bin/perl
print "Content-type: text/html\n\n";
 
# Setting the password
$password = 'geekforgeeks';
 
# Encrypting the password using crypt function
$hidden = crypt $password, join "",
          ('.', '/', 0..9, 'A'..'Z', 'a'..'z') [rand 64, rand 64];
 
print "$hidden \n";
 
$salt = substr ($hidden, 0, 2);
 
# Taking user input
print "Enter Your Password: \n";
while ()
{
    if ($hidden eq (crypt $_, $salt))
    {
        print "Successfully Logged In \n";
        exit;
    }
    else
    {
        print "Entered Password is Incorrect \n";
        print "Please Try Again: \n";
    }
}


Perl
#!/usr/bin/perl
use strict;
use warnings;
use MIME::Base64;
 
# Setting the password
my $password = "GeeksforGeeks";
 
# For encrypting the plaintext password
# using crypt function
my $encoded = crypt $password, join "",
             ('.', '/', 0..9, 'A'..'Z', 'a'..'z') [rand 64, rand 64];
 
my $salt = substr ($encoded, 0, 2);
 
# For decrypting the encrypted password
# using base_64 module
my $decoded = decode_base64($encoded);
print "\n";
 
# For printing the Encrypted password
print "Encrypted Password :: $encoded\n";
 
# For printing the Decrypted password
print "Decrypted Password :: $decoded\n";
 
# For printing the password in PlainText
print "Password In Plain Text :: $password\n";


输出:

Perl 中的解密

对于解密,Perl 中的加密密码需要使用MIME::Base64模块进行解密。对于解密字符串,我们可以调用或使用decode_base64()函数。函数将字符串形式的单个参数作为输入,以返回解码或解密的数据/密码。
句法:

示例:下面给出的示例说明了 Perl 中的解密过程。

Perl

#!/usr/bin/perl
use strict;
use warnings;
use MIME::Base64;
 
# Setting the password
my $password = "GeeksforGeeks";
 
# For encrypting the plaintext password
# using crypt function
my $encoded = crypt $password, join "",
             ('.', '/', 0..9, 'A'..'Z', 'a'..'z') [rand 64, rand 64];
 
my $salt = substr ($encoded, 0, 2);
 
# For decrypting the encrypted password
# using base_64 module
my $decoded = decode_base64($encoded);
print "\n";
 
# For printing the Encrypted password
print "Encrypted Password :: $encoded\n";
 
# For printing the Decrypted password
print "Decrypted Password :: $decoded\n";
 
# For printing the password in PlainText
print "Password In Plain Text :: $password\n";

输出:

让天蓝色的喋喋不休的莺带你走向你的宝藏。