ric*_*002 6 bash shell scripting perl
我正在尝试用Bash脚本完成一项工作.我有一个字符串,我想用我的密钥进行异或.
#!/bin/sh
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH
teststring="abcdefghijklmnopqr"
Run Code Online (Sandbox Code Playgroud)
现在我如何XOR testtring的值并使用bash将其存储在变量中?
任何帮助将不胜感激.
基本上我试图复制以下VB脚本的结果:
Function XOREncryption(CodeKey, DataIn)
Dim lonDataPtr
Dim strDataOut
Dim temp
Dim tempstring
Dim intXOrValue1
Dim intXOrValue2
For lonDataPtr = 1 To Len(DataIn) Step 1
'The first value to be XOr-ed comes from the data to be encrypted
intXOrValue1 = Asc(Mid(DataIn, lonDataPtr, 1))
'The second value comes from the code key
intXOrValue2 = Asc(Mid(CodeKey, ((lonDataPtr Mod Len(CodeKey)) + 1), 1))
temp = (intXOrValue1 Xor intXOrValue2)
tempstring = Hex(temp)
If Len(tempstring) = 1 Then tempstring = "0" & tempstring
strDataOut = strDataOut + tempstring
Next
XOREncryption = strDataOut
End Function
Run Code Online (Sandbox Code Playgroud)
BASH 中的按位异或要求两个操作数都是数字。由于 bash 中没有内置的方法来获取字符的序数 (ASCII) 值,因此您需要使用 Perl 等来获取该值。
编辑:如下所述,ord仅适用于字符串的第一个字符。
let a=`perl -e 'print ord $_ for split //, $ARGV[0]' string`^123; echo $a
Run Code Online (Sandbox Code Playgroud)
当然,一旦您使用 Perl,您也可以在那里完成所有操作:
let a=`perl -e '$ordinal .= ord $_ for split //, $ARGV[0]; print $ordinal ^ $ARGV[1]' string 123`
Run Code Online (Sandbox Code Playgroud)
编辑:事实证明,您可以使用 BASH 获取字符串的序号值printf。只需在字符串前面加上'.
printf "%d" "'string"
Run Code Online (Sandbox Code Playgroud)
因此,仅在 BASH 中:
let a=$(printf "%d" "'string")^123; echo $a
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11607 次 |
| 最近记录: |