# 异或加密(XOR)原理及实现

0 ^ 0 = 0

1 ^ 1 = 0

1 ^ 0 = 1

0 ^ 1 = 1

## 异或加密特性

1. A ^ 0 = A

2. A ^ A = 0

3. (A ^ B) ^ C = A ^ (B ^ C)

4. (B ^ A) ^ A = B ^ 0 = B

## 异或加密算法

1. 明文
2. 密钥
3. 异或运算规则

1. 明文与密钥按照异或运算规则进行异或运算，产生密钥
2. 将得到的密文进行base64 编码，最后返回

1. 将密文进行 base64 解码，得到原始的密文
2. 将密文按照相同的异或运算规则与密文进行异或，得到明文

## Power shell 实现

```\$Script:key = "3567d8cndkei%*x9(-32[]KDF(32222"

function Decode(\$cyphertext) {
\$keyArray =[System.Text.Encoding]::ASCII.GetBytes(\$key)
\$encodedArray= [System.Text.Encoding]::ASCII.GetBytes([System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String(\$cyphertext)))
\$plainText = ""
\$keyposition = 0
\$encodedArray | foreach-object -process {
\$plainText += [char](\$_ -bxor \$KeyArray[\$keyposition % \$KeyArray.Length])
\$keyposition += 1
}

return \$plainText
}

function Encode(\$plainText)
{
\$KeyArray= [System.Text.Encoding]::ASCII.GetBytes(\$key)
\$cyphertext = [System.Byte[]]::new(\$plainText.Length);
\$keyposition = 0
\$plainText.ToCharArray() | foreach-object -process {
\$cyphertext[\$keyposition] = \$_ -bxor \$KeyArray[\$keyposition % \$KeyArray.Length]
\$keyposition += 1
}

return [Convert]::ToBase64String(\$cyphertext)
}```

### 测试

`Decode(Encode("324328***)x-sdfsaf2344")) | out-string`