duanjinchi1982 2016-01-15 08:47
浏览 24
已采纳

从PHP到Mcrypt

Im using a class to encrypt/decrypt strings in PHP.

How could I encrypt/decrypt the strings in Go?

The PHP class:

class Crypto {
    private $encryptKey = 'xxxxxxxxxxxxxxxx';
    private $iv = 'xxxxxxxxxxxxxxxx';
    private $blocksize = 16;
    public function decrypt($data)
    {
        return $this->unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, 
            $this->encryptKey, 
            hex2bin($data),
            MCRYPT_MODE_CBC, $this->iv), $this->blocksize);
    }
    public function encrypt($data)
    {
        //don't use default php padding which is '\0'
        $pad = $this->blocksize - (strlen($data) % $this->blocksize);
        $data = $data . str_repeat(chr($pad), $pad);
        return bin2hex(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,
            $this->encryptKey,
            $data, MCRYPT_MODE_CBC, $this->iv));
    }
    private function unpad($str, $blocksize)
    {
        $len = strlen($str);
        $pad = ord($str[$len - 1]);
        if ($pad && $pad <= $blocksize) {
            if (substr($str, -$pad) === str_repeat(chr($pad), $pad)) {
                return substr($str, 0, $len - $pad);
            }
        }
        return $str;
    }
}

What to be able to encrypt/decrypt same string in both PHP and Go.

  • 写回答

1条回答 默认 最新

  • dovt85093 2016-01-15 09:32
    关注

    Here is an example:

    package main
    
    import (
        "crypto/aes"
        "crypto/cipher"
        "crypto/rand"
        "encoding/base64"
        "errors"
        "fmt"
        "io"
        "log"
    )
    
    func main() {
        key := []byte("xxxxxxxxxxxxxxxx") // 32 bytes
        plaintext := []byte("TEST")
        fmt.Printf("%s
    ", plaintext)
        ciphertext, err := encrypt(key, plaintext)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%0x
    ", ciphertext)
        result, err := decrypt(key, ciphertext)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Printf("%s
    ", result)
    }
    
    func encrypt(key, text []byte) ([]byte, error) {
        block, err := aes.NewCipher(key)
        if err != nil {
            return nil, err
        }
        b := base64.StdEncoding.EncodeToString(text)
        ciphertext := make([]byte, aes.BlockSize+len(b))
        iv := ciphertext[:aes.BlockSize]
        if _, err := io.ReadFull(rand.Reader, iv); err != nil {
            return nil, err
        }
        cfb := cipher.NewCFBEncrypter(block, iv)
        cfb.XORKeyStream(ciphertext[aes.BlockSize:], []byte(b))
        return ciphertext, nil
    }
    
    func decrypt(key, text []byte) ([]byte, error) {
        block, err := aes.NewCipher(key)
        if err != nil {
            return nil, err
        }
        if len(text) < aes.BlockSize {
            return nil, errors.New("ciphertext too short")
        }
        iv := text[:aes.BlockSize]
        text = text[aes.BlockSize:]
        cfb := cipher.NewCFBDecrypter(block, iv)
        cfb.XORKeyStream(text, text)
        data, err := base64.StdEncoding.DecodeString(string(text))
        if err != nil {
            return nil, err
        }
        return data, nil
    }
    

    Mostly borrowed and adapted from: https://golang.org/src/crypto/cipher/example_test.go

    // Input => TEST
    // Output => 13360adba03733e11dd2702de441ff8bbb90676ad762fc83
    

    UPDATE

    To use a string as a parameter for decode function, you need to convert the string to byte using hex.Decodestring

    data, _ := hex.DecodeString("1d6f12d3aa2353b23c6012dbc85816632129363d58a76063")
    result, err := decrypt(key, data)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s
    ", result)
    

    Do not forget to include "encoding/hex" into package list.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入