go,  php

php 和 go:aes 加密

生成公私钥

openssl genrsa -out private.pem 1024
openssl rsa -in private.pem -pubout -out public.pem

go:加密、解密

func RsaEncrypt(origData []byte) ([]byte, error) {
    publicKey := `-----BEGIN PUBLIC KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-----END PUBLIC KEY-----`
    block, _ := pem.Decode([]byte(publicKey))
    if block == nil {
        return nil, errors.New("public key error")
    }
    pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    pub := pubInterface.(*rsa.PublicKey)
    return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

func RsaDecrypt(ciphertext []byte) ([]byte, error) {
    privateKey := `-----BEGIN RSA PRIVATE KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-----END RSA PRIVATE KEY-----`
    block, _ := pem.Decode([]byte(privateKey))
    if block == nil {
        return nil, errors.New("private key error")
    }
    priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        return nil, err
    }
    return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}

php:加密、解密

function rsaEncrypt($data)
{
    global $publicKey;
    openssl_public_encrypt($data, $crypted, $publicKey);
    return $crypted;
}
function rsaDecrypt($data)
{
    global $privateKey;
    openssl_private_decrypt($data, $decrypted, $privateKey);
    return $decrypted;
}

发表评论