duangua5742 2018-05-24 20:22
浏览 69
已采纳

字符串的简单加密

I want to encrypt a string with Go, my actual code is:

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

Problem is after encrypt string, when I try to decrypt return different output. Where did I go wrong?

  • 写回答

1条回答 默认 最新

  • douzhaolu4780 2018-05-24 20:37
    关注

    It looks like your goal is to xor the the bytes in a string with the bytes in a key. Here's one way to do it:

    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)
    }
    

    The Encrypt and Decrypt functions are the same:

    func Encrypt(input string) string { return xor(input) }
    func Decrypt(input string) string { return xor(input) }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘