加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 按位XOR在Bash中的字符串

发布时间:2020-12-16 06:25:42 所属栏目:大数据 来源:网络整理
导读:我正在尝试用 Bash脚本完成一项工作.我有一个字符串,我想用我的密钥进行异或. #!/bin/shPATH=/bin:/usr/bin:/sbin:/usr/sbin export PATHteststring="abcdefghijklmnopqr" 现在我如何XOR testtring的值并使用bash将其存储在变量中? 任何帮助将不胜感激. 基
我正在尝试用 Bash脚本完成一项工作.我有一个字符串,我想用我的密钥进行异或.

#!/bin/sh
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH

teststring="abcdefghijklmnopqr"

现在我如何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

解决方法

在 these hints的帮助下,我写了这个快速的脚本来完成Pedro的答案:

#!/bin/bash

function ascii2dec
{
  RES=""
  for i in `echo $1 | sed "s/./& /g"`
  do 
    RES="$RES `printf "%d" "'$i"`"
  done 
  echo $RES
}

function dec2ascii
{
  RES=""
  for i in $*
  do 
    RES="$RES`printf \$(printf '%03o' $i)`"
  done 
  echo $RES
}

function xor
{
  KEY=$1
  shift
  RES=""
  for i in $*
  do
    RES="$RES $(($i ^$KEY))"
  done

  echo $RES
}


KEY=127
TESTSTRING="abcdefghijklmnopqr"

echo "Original String: $TESTSTRING"
STR_DATA=`ascii2dec "$TESTSTRING"`
echo "Original String Data: $STR_DATA"
XORED_DATA=`xor $KEY $STR_DATA`
echo "XOR-ed Data: $XORED_DATA"
RESTORED_DATA=`xor $KEY $XORED_DATA`
echo "Restored Data: $RESTORED_DATA"
RESTORED_STR=`dec2ascii $RESTORED_DATA`
echo "Restored String: $RESTORED_STR"

结果:

iMac:Desktop fer$bash test.sh
Original String: abcdefghijklmnopqr
Original String Data: 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 
XOR-ed Data: 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13
Restored Data: 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 
Restored String: abcdefghijklmnopqr

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读