go - 字符串的简单加密

标签 go encryption

我想用Go加密一个字符串,我的实际代码是:

package main

import (
    "fmt"
)

const key = "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"  //some random numbers here

func Encrypt(input string) (output string) {
  for i := 0; i < len(input); i++ {
    output += fmt.Sprintf("\\x%02x", input[i] ^ key[i % len(key)])
      }
  return output;
} 

func Decrypt(input string) (output string) {
  key := "\xbd\xb2\x3d\xbc\x20\xe2\x8c\x98"
  for i := 0; i < len(input); i++ {
    output += string(input[i] ^ key[i % len(key)])
    }
    return output;
} 


func main() {

   stringa := "password"
   encrypted := Encrypt(stringa)
   fmt.Println(encrypted)

   fmt.Println(Decrypt(encrypted))
   fmt.Println(stringa)
}

\xcd\xd3\x4e\xcf\x57\x8d\xfe\xfc
áE^O|?è«áE      U|?ï_á?|?'üáE[U|?êû
password

问题是在加密字符串之后,当我尝试解密时返回不同的输出。我哪里出错了?

最佳答案

看起来您的目标是将字符串中的字节与键中的字节进行异或运算。这是一种方法:

func xor(input string) string {
    output := make([]byte, len(input))
    for i := 0; i < len(input); i++ {
        output[i] = input[i] ^ key[i%len(key)]
    }
    return string(output)
}

加密和解密函数是一样的:

func Encrypt(input string) string { return xor(input) }
func Decrypt(input string) string { return xor(input) }

关于go - 字符串的简单加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50517588/

相关文章:

git - 是否有golang提交后构建过程

go - Go中的原型(prototype)结构

go - 如何优雅的关闭 channel ?

java - 使用什么模式在 Java 中解密来自 iPhone 的 RSA 消息?

PHP crypt函数及算法

java - Kotlin 将 PKCS1 转换为 PKCS8

rest - 如何设置OAuth1.0a的授权 header

unit-testing - testify包错误 `The code you are testing needs to make 1 more call(s)`

encryption - OpenResty lua-resty-string : Unable to decrypt cipher encrypted by Crypto-JS (AES default)

c - 穷人序列号生成方案,第2部分