如何使用openssl将加密/解密的消息输出到stdout

时间:2019-05-23 18:50:41

标签: bash shell encryption openssl

我只是想用shell加密/解密密码(非交互式-用于自动脚本)。我正在关注以下示例: https://superuser.com/a/20552/362669

我尝试将其转换为此,以便它不使用文件output.bin来存储加密的文本:

#!/usr/bin/env bash

cd `dirname "$BASH_SOURCE"`

# generate a 2048-bit RSA key and store it in key.txt
openssl genrsa -out key.txt 2048

# encrypt "hello world" using the RSA key in key.txt
encrypted="$(echo "hello world" | openssl rsautl -inkey key.txt -encrypt)"

echo "encrypted: $encrypted"

# decrypt the message and output to stdout
decrypted="$(echo "$encrypted" | openssl rsautl -inkey key.txt -decrypt)"

echo "decrypted: $decrypted";

但我得到的只是这个乱七八糟的东西:

Generating RSA private key, 2048 bit long modulus
........................................................................................................................+++
............................+++
e is 65537 (0x10001)
��◆J��┌ܥײ��R▒��%⎽F��    1l�}�%��?�0���+��%���C�8|_/!�A"Ꜵ:�������.��W2Pras��1���� ��(�a
��]�[�남␍◆�=┬─�з≤�ɦ�;�└�1MFP��^␋�@D�    �T_⎺F�Eπ�2��U2Ÿ┌π��N│�� ⎽��_\2�� 8V��%��(�^���␍4�#�π���*^D ���/�└�
RSA ⎺⎻␊⎼▒├␋⎺┼ ␊⎼⎼⎺⎼
4662363756:␊⎼⎼⎺⎼:04FFF06B:⎼⎽▒ ⎼⎺┤├␋┼␊⎽:CRYPTO_␋┼├␊⎼┼▒┌:␉┌⎺␌┐ ├≤⎻␊ ␋⎽ ┼⎺├ 02:/B┤␋┌␍R⎺⎺├/L␋␉⎼▒⎼≤/C▒␌␤␊⎽/␌⎺└.▒⎻⎻┌␊.│␉⎽/S⎺┤⎼␌␊⎽/┌␋␉⎼␊⎽⎽┌/┌␋␉⎼␊⎽⎽┌-22.260.1/┌␋␉⎼␊⎽⎽┌-2.6/␌⎼≤⎻├⎺/⎼⎽▒/⎼⎽▒_⎻┐1.␌:185:
4662363756:␊⎼⎼⎺⎼:04FFF072:⎼⎽▒ ⎼⎺┤├␋┼␊⎽:CRYPTO_␋┼├␊⎼┼▒┌:⎻▒␍␍␋┼± ␌␤␊␌┐ °▒␋┌␊␍:/B┤␋┌␍R⎺⎺├/L␋␉⎼▒⎼≤/C▒␌␤␊⎽/␌⎺└.▒⎻⎻┌␊.│␉⎽/S⎺┤⎼␌␊⎽/┌␋␉⎼␊⎽⎽┌/┌␋␉⎼␊⎽⎽┌-22.260.1/┌␋␉⎼␊⎽⎽┌-2.6/␌⎼≤⎻├⎺/⎼⎽▒/⎼⎽▒_␊▒≤.␌:580:
␍␊␌⎼≤⎻├␊␍: 
▒┌␊│⎽-└▒␌:␋┼├␊⎼⎺⎽ ▒┌␊│$ 

,我的shell会话基本上被搞砸了。

有人知道那是什么吗?也许是输出shell无法处理的字符?

更新:如果我不记录加密值,那么我会得到:

Generating RSA private key, 2048 bit long modulus
........................+++
..........+++
e is 65537 (0x10001)
RSA operation error
4558829164:error:04FFF06B:rsa routines:CRYPTO_internal:block type is not 02:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.260.1/libressl-2.6/crypto/rsa/rsa_pk1.c:185:
4558829164:error:04FFF072:rsa routines:CRYPTO_internal:padding check failed:/BuildRoot/Library/Caches/com.apple.xbs/Sources/libressl/libressl-22.260.1/libressl-2.6/crypto/rsa/rsa_eay.c:580:
decrypted: 

1 个答案:

答案 0 :(得分:1)

我认为最好的主意是将二进制文件与base64相互转换。

只需通过“ openssl base64”管道输出命令即可启用,而通过“ openssl base64 -d”命令进行解码。

如此:

  

encrypted =“ $(echo” hello world“ | openssl rsautl -inkey key.txt   加密| openssl base64)“

  

decrypted =“ $(echo” $ encrypted“ | openssl base64 -d | openssl rsautl   -inkey key.txt -decrypt)“