Mcrypt from PHP to Go

huangapple go评论91阅读模式
英文:

Mcrypt from PHP to Go

问题

我正在使用一个 PHP 类来加密/解密字符串。

在 Go 中,我该如何加密/解密字符串?

以下是 PHP 类的代码:

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)
    {
        // 不要使用默认的 PHP 填充,即 '
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)
    {
        // 不要使用默认的 PHP 填充,即 '\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;
    }
}
'
$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; } }

我希望能够在 PHP 和 Go 中使用相同的字符串进行加密/解密。

英文:

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

得分: 0

这是一个示例:

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\n", plaintext)
	ciphertext, err := encrypt(key, plaintext)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%0x\n", ciphertext)
	result, err := decrypt(key, ciphertext)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s\n", 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
}

大部分代码是从这里借用并适应的:https://golang.org/src/crypto/cipher/example_test.go

// 输入 => TEST
// 输出 => 13360adba03733e11dd2702de441ff8bbb90676ad762fc83

更新

要将字符串作为decode函数的参数使用,你需要使用hex.Decodestring将字符串转换为byte

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

不要忘记将"encoding/hex"包包含在包列表中。

英文:

Here is an example:

package main
import (
&quot;crypto/aes&quot;
&quot;crypto/cipher&quot;
&quot;crypto/rand&quot;
&quot;encoding/base64&quot;
&quot;errors&quot;
&quot;fmt&quot;
&quot;io&quot;
&quot;log&quot;
)
func main() {
key := []byte(&quot;xxxxxxxxxxxxxxxx&quot;) // 32 bytes
plaintext := []byte(&quot;TEST&quot;)
fmt.Printf(&quot;%s\n&quot;, plaintext)
ciphertext, err := encrypt(key, plaintext)
if err != nil {
log.Fatal(err)
}
fmt.Printf(&quot;%0x\n&quot;, ciphertext)
result, err := decrypt(key, ciphertext)
if err != nil {
log.Fatal(err)
}
fmt.Printf(&quot;%s\n&quot;, 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) &lt; aes.BlockSize {
return nil, errors.New(&quot;ciphertext too short&quot;)
}
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 =&gt; TEST
// Output =&gt; 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(&quot;1d6f12d3aa2353b23c6012dbc85816632129363d58a76063&quot;)
result, err := decrypt(key, data)
if err != nil {
log.Fatal(err)
}
fmt.Printf(&quot;%s\n&quot;, result)

Do not forget to include &quot;encoding/hex&quot; into package list.

huangapple
  • 本文由 发表于 2016年1月15日 16:47:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/34807248.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定