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

前端之家收集整理的这篇文章主要介绍了perl – 按位XOR在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

猜你在找的Perl相关文章