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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题