I am using AES encryption in Go and PHP. But both the languages does not encrypt/decrypt each other ciphertext. Following i have tried in php
class Crypto {
private $encryptKey = "keyforencryption";
private $iv = 'ivusedforencrypt';
private $blocksize = 16;
public function encrypt($toEncrypt){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB);
//$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return base64_encode($this->iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->encryptKey, $toEncrypt, MCRYPT_MODE_CFB, $this->iv));
}
public function decrypt($toDecrypt){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CFB);//$this->blocksize;
$toDecrypt = base64_decode($toDecrypt);
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->encryptKey, substr($toDecrypt, $iv_size), MCRYPT_MODE_CFB, substr($toDecrypt, 0, $iv_size)));
}
}
$c = new Crypto();
echo "Encrypted : ".$e = $c->encrypt("test");
echo "<br/>Decrypted : ".$c->decrypt($e);
output : aXZ1c2VkZm9yZW5jcnlwdDpdZEinU2rB
and this one in Go with AES
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
)
func main() {
key := []byte("keyforencryption")
plaintext := []byte("test")
fmt.Printf("%s
", plaintext)
ciphertext, err := encrypt(key, plaintext)
if err != nil {
log.Fatal(err)
}
b := base64.StdEncoding.EncodeToString(ciphertext)
fmt.Printf("Encrypted text : %s
", b)
result, err := decrypt(key, b)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Decrypted Text : %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(text))
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(text))
return ciphertext, nil
}
func decrypt(key []byte, text1 string) ([]byte, error) {
text, _ := base64.StdEncoding.DecodeString(string(text1))
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)
b := base64.StdEncoding.EncodeToString(text)
data, err := base64.StdEncoding.DecodeString(string(b))
if err != nil {
return nil, err
}
return data, nil
}
output : ZVnhCXjIvtGKBdqvjwHRZKcVy34=
any help would be appreciable.