Rsa

简介

  • 非对称加密算法(公钥+私钥)

代码示例

//对数据进行加密操作
func EncyptogRSA(src []byte, publicKey string) (res []byte, err error) {

    pub, err := PublicKeyFrom64(publicKey)

    if err != nil {
        fmt.Println(err.Error())
    }

    return rsa.EncryptPKCS1v15(rand.Reader, pub, src)
}

//对数据进行解密操作
func DecrptogRSA(src []byte, privateKey string) (res []byte, err error) {
    priByte, _ := base64.StdEncoding.DecodeString(privateKey)

    pri, _ := x509.ParsePKCS1PrivateKey(priByte) //还原数据
    return rsa.DecryptPKCS1v15(rand.Reader, pri, src)
}

func GenerateKey() (*rsa.PrivateKey, *rsa.PublicKey, error) {
    pri, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        return nil, nil, err
    }
    return pri, &pri.PublicKey, nil
}

func GenerateKeyBytes() (privateBytes, publicBytes []byte, err error) {
    pri, pub, err := GenerateKey()
    if err != nil {
        return nil, nil, err
    }
    priBytes, err := x509.MarshalPKCS8PrivateKey(pri)
    if err != nil {
        return nil, nil, err
    }
    pubBytes := x509.MarshalPKCS1PublicKey(pub)
    return priBytes, pubBytes, nil
}

func GenerateKey64() (pri64, pub64 string, err error) {
    pri, pub, err := GenerateKeyBytes()
    if err != nil {
        return "", "", nil
    }
    return base64.StdEncoding.EncodeToString(pri),
        base64.StdEncoding.EncodeToString(pub),
        nil
}

func PublicKeyFrom(key []byte) (*rsa.PublicKey, error) {
    pub, err := x509.ParsePKCS1PublicKey(key)
    if err != nil {
        return nil, err
    }

    return pub, nil
}

func PublicKeyFrom64(key string) (*rsa.PublicKey, error) {
    b, err := base64.StdEncoding.DecodeString(key)
    if err != nil {
        return nil, err
    }
    return PublicKeyFrom(b)
}