加密解密
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"testing"
)
// 可通过openssl产生
//openssl genrsa -out rsa_private_key.pem 1024
var privateKey = []byte(`
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDP2z9C4/iLNrlzP/RYuKNdJ3MzvYh7j2yrGAo9MvZGy4hvCJfY
djS+SSXn++YEIORr+9X+SMHu9gHGi3kBxTbEUmVIc0ee13xmh12mpcu6QoOGseD7
Q2dPx9Kjc21jeqJU3WS5QSelMN3DZVLrwt9Hjy8Tw0Cxp0yhkCPZ3ZVPUQIDAQAB
AoGAVqnmZYBht8G4buoief959bQmH1OOHV5+g5PBaSTfdEMWfp0JmrImaZRcHq5z
iBMiyjc1URGK8pRVxy+N44QTweRoEmFjGWuHVoO1exElH3Oh18+Xvlmm3wJ22rpz
MvUqlA0hMhLfo2keSTy4wS4ZNz/lzPImuWPZo08FbjrqfrECQQD4iKLUvw6MLs4S
icaNQYLBHV9fjlZTNCI552ELKs9OLDk8++9FNFxFXOO8T6hdAbhhwoD75m7IPAb3
Kmj1i7T9AkEA1hnHn5ZuX6BIinNe0g6s6DVgPeTTJoIczMst29x78VlhpEa7WX/l
q4vLVH0CtVYmaluUeZOe6d3hVaJw2zbd5QJBAJ+a567mT0pZGH+xOPAn3Pd1jHUK
LIfcWAqFe723LVBPeCagyATSXlsxDxM0uLOZ0jX9ueWLEyPF4NdDxgnCQWUCQQDE
/E8oy/WdUhGsIN4bEpmPxJxaFhEYGxp4anA1G7WFp6EozlNN01jy7toTUDmPskYC
EWSYP3Q05IqQibagWujpAkAo5vcQE7E5NB5Fhmb5fliul+gQ232W+LM8QqScRI2j
F9iSqwhhwFTD/KgEL1cLnO9D4LPaUSaVBN7SL6nK0i3h
-----END RSA PRIVATE KEY-----
`)
//openssl
//openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
var publicKey = []byte(`
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDP2z9C4/iLNrlzP/RYuKNdJ3Mz
vYh7j2yrGAo9MvZGy4hvCJfYdjS+SSXn++YEIORr+9X+SMHu9gHGi3kBxTbEUmVI
c0ee13xmh12mpcu6QoOGseD7Q2dPx9Kjc21jeqJU3WS5QSelMN3DZVLrwt9Hjy8T
w0Cxp0yhkCPZ3ZVPUQIDAQAB
-----END PUBLIC KEY-----
`)
// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
//解密pem格式的公钥
block, _ := pem.Decode(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) {
//解密
block, _ := pem.Decode(privateKey)
if block == nil {
return nil, errors.New("private key error!")
}
//解析PKCS1格式的私钥
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
// 解密
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
func TestSecurity(t *testing.T) {
data, _ := RsaEncrypt([]byte("hello world"))
fmt.Printf("加密后的密文:%s", base64.StdEncoding.EncodeToString(data))
origData, _ := RsaDecrypt(data)
fmt.Println("start===================end")
fmt.Printf("解密后的明文:%s", string(origData))
}
密钥对不是pem格式
/**
* 密码Rsa加密
*/
func RsaPwdEncrypt(password string) (string, error) {
if len(password) == 0 {
return "", nil
}
return rsaEncryptWithSha1Base64(password, "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwPdQAMcV5YdOIK2p3C3efA31Jw/mceoL9Y8EdkBD5OMBeFoPn2RVyMDGfyAjZoPiSJFeXIZMfL/Lwidbs0kMCcOrMOyncf6gydGNUIPVnJXt2vdjAWk7OwOVgwaj2cigSjRjIoV9H6IA7+AA0knf47jFppNPM+yPMM+d3spGvRQIDAQAB")
}
/**
* 密码Rsa解密
*/
func RsaPwdDecrypt(password string) (string, error) {
if len(password) == 0 {
return "", nil
}
return rsaDecryptWithSha1Base64(password, "MIICXAIBAAKBgQCwPdQAMcV5YdOIK2p3C3efA31Jw/mceoL9Y8EdkBD5OMBeFoPn2RVyMDGfyAjZoPiSJFeXIZMfL/Lwidbs0kMCcOrMOyncf6gydGNUIPVnJXt2vdjAWk7OwOVgwaj2cigSjRjIoV9H6IA7+AA0knf47jFppNPM+yPMM+d3spGvRQIDAQABAoGALMRXwIDj/1QpDjKxBXIlPX/+aCleky/PbBvVpvO8TAHtYzjm4pKSzwGM6WA/V0B7Q2v1z87YdxiP5ietL1Stblpj3auQlipVLfCgOHhe0Kx2CxRJp+YzvH/WpKofWyszGRrCtno2pEM129BGn/GdwRVHdzo1uFg1j46J5dpn5sECQQDWubPiZRuTP2BZWvDtJVcquOZrvfY9yaW8VvLl3GPHxVIM1xX5bQKheWOfTnq3b9VQMFX0Rnrirpv/eceJUnURAkEA0h5k9DzYf9mNwLL13ryIEC+l5CO8mKCdZAl+IdyTu8Y6f32To7M+X/vNoDYVEzZ6ZUQKe67KVp4g5upmHFVG9QJBAIQdQDukoAHKNbrkxGX02pvzpfpWp+I+ZpXqHYsmPdJVavVxhRixZLP7XztOaxzgVyv+gXRJxSQh8OOQhx/LtzECQHN2KkmgCeQve1qxvLQ565bhaAp2rNM+J17qbHpVCIV9x3V5XyDshVEfQH5SWcBmBloRSqVuhleUq0XY9mWJYuUCQBDFROe00M3qY2ltkDVtpzatXgfcUqZzI+/q2+a2VJgEt/HdNBrnV5qUr3hTNMk50tdED6m99pEaAK9dDkeDHFM=")
}
/**
* (1)加密:采用sha1算法加密后转base64格式
*/
func rsaEncryptWithSha1Base64(originalData, publicKey string) (string, error) {
key, _ := base64.StdEncoding.DecodeString(publicKey)
pubKey, _ := x509.ParsePKIXPublicKey(key)
originalData1 := base64.StdEncoding.EncodeToString([]byte(originalData))
originalDataBytes := []byte(originalData1)
originalMaxLen := len(originalDataBytes)
if originalMaxLen > 117 {
var tempByte string
countForm := 0
countTo := 117
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), originalDataBytes[countForm:countTo])
if err != nil {
return "", err
}
tempByte += string(encryptedData)
for {
if countTo+117 > originalMaxLen {
countForm += 117
countTo = originalMaxLen
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), originalDataBytes[countForm:countTo])
if err != nil {
return "", err
}
tempByte += string(encryptedData)
break
} else {
countForm += 117
countTo += 117
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), originalDataBytes[countForm:countTo])
if err != nil {
return "", err
}
tempByte += string(encryptedData)
}
}
return base64.StdEncoding.EncodeToString([]byte(tempByte)), err
} else {
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), []byte(originalData))
return base64.StdEncoding.EncodeToString(encryptedData), err
}
}
/**
* (2)解密:对采用sha1算法加密后转base64格式的数据进行解密(私钥PKCS1格式)
*/
func rsaDecryptWithSha1Base64(encryptedData, privateKey string) (string, error) {
key, _ := base64.StdEncoding.DecodeString(privateKey)
prvKey, _ := x509.ParsePKCS1PrivateKey(key)
encryptedDecodeBytes, err := base64.StdEncoding.DecodeString(encryptedData)
if err != nil {
return "", err
}
if len(encryptedDecodeBytes) > 128 {
var tempByte string
for i := 0; i < len(encryptedDecodeBytes)/128; i++ {
originalData, err := rsa.DecryptPKCS1v15(rand.Reader, prvKey, encryptedDecodeBytes[(i*128):128*(i+1)])
if err != nil {
return "", err
}
tempByte += string(originalData)
}
laststr, err := base64.StdEncoding.DecodeString(tempByte)
return string(laststr), err
} else {
originalData, err := rsa.DecryptPKCS1v15(rand.Reader, prvKey, encryptedDecodeBytes)
return string(originalData), err
}
}
func main() {
data, _ := RsaPwdEncrypt("hello world")
fmt.Printf("加密后的密文:%s", data) // O1Hbq/QDmvzvSctf/OJRsv7/FQFFtBbS2Yax9xynn+Y970eyO8r2XHRqyhREEH4h6lJ1bCKck4TBU6/hARjSwM1CUmJ3E97rygCaybaPDwHroht91kxWUc84iDx9ya8X7yFShfs36Irn5mFbbLETX8zZt+V7B+aAYMv4wQqRd6Y=
origData, _ := RsaPwdDecrypt(data)
fmt.Println()
fmt.Printf("解密后的明文:%s", origData) // hello world
}
或
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
)
// 可通过openssl产生
//openssl genrsa -out rsa_private_key.pem 1024
var privateKey = []byte(`
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDP2z9C4/iLNrlzP/RYuKNdJ3MzvYh7j2yrGAo9MvZGy4hvCJfY
djS+SSXn++YEIORr+9X+SMHu9gHGi3kBxTbEUmVIc0ee13xmh12mpcu6QoOGseD7
Q2dPx9Kjc21jeqJU3WS5QSelMN3DZVLrwt9Hjy8Tw0Cxp0yhkCPZ3ZVPUQIDAQAB
AoGAVqnmZYBht8G4buoief959bQmH1OOHV5+g5PBaSTfdEMWfp0JmrImaZRcHq5z
iBMiyjc1URGK8pRVxy+N44QTweRoEmFjGWuHVoO1exElH3Oh18+Xvlmm3wJ22rpz
MvUqlA0hMhLfo2keSTy4wS4ZNz/lzPImuWPZo08FbjrqfrECQQD4iKLUvw6MLs4S
icaNQYLBHV9fjlZTNCI552ELKs9OLDk8++9FNFxFXOO8T6hdAbhhwoD75m7IPAb3
Kmj1i7T9AkEA1hnHn5ZuX6BIinNe0g6s6DVgPeTTJoIczMst29x78VlhpEa7WX/l
q4vLVH0CtVYmaluUeZOe6d3hVaJw2zbd5QJBAJ+a567mT0pZGH+xOPAn3Pd1jHUK
LIfcWAqFe723LVBPeCagyATSXlsxDxM0uLOZ0jX9ueWLEyPF4NdDxgnCQWUCQQDE
/E8oy/WdUhGsIN4bEpmPxJxaFhEYGxp4anA1G7WFp6EozlNN01jy7toTUDmPskYC
EWSYP3Q05IqQibagWujpAkAo5vcQE7E5NB5Fhmb5fliul+gQ232W+LM8QqScRI2j
F9iSqwhhwFTD/KgEL1cLnO9D4LPaUSaVBN7SL6nK0i3h
-----END RSA PRIVATE KEY-----
`)
//openssl
//openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
var publicKey []byte
// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
//解密pem格式的公钥
block, _ := pem.Decode(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) {
//解密
block, _ := pem.Decode(privateKey)
if block == nil {
return nil, errors.New("private key error!")
}
//解析PKCS1格式的私钥
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
// 解密
return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}
func main() {
publicKey = []byte("-----BEGIN PUBLIC KEY-----\n") // 换行符可以有多个,但不能没有
publicKey = append(publicKey, []byte("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDP2z9C4/iLNrlzP/RYuKNdJ3MzvYh7j2yrGAo9MvZGy4hvCJfYdjS+SSXn++YEIORr+9X+SMHu9gHGi3kBxTbEUmVIc0ee13xmh12mpcu6QoOGseD7Q2dPx9Kjc21jeqJU3WS5QSelMN3DZVLrwt9Hjy8Tw0Cxp0yhkCPZ3ZVPUQIDAQAB")...)
publicKey = append(publicKey, []byte("\n-----END PUBLIC KEY-----")...) // 换行符可以有多个,但不能没有
data, _ := RsaEncrypt([]byte("hello world"))
fmt.Printf("加密后的密文:%s\n", base64.StdEncoding.EncodeToString(data))
origData, _ := RsaDecrypt(data)
fmt.Println("start===================end")
fmt.Printf("解密后的明文:%s", string(origData))
}