Golang Rsa 公钥加密私钥解密,私钥签名公钥验证 , 私钥加密公钥解密

//FIXME   配合cgo的openssl使用,为什么要用这个???    因为大佬说速度比较快
import . "github.com/spacemonkeygo/openssl"

// 生成 TLS的ca 证书    注意这是ca
func TestCAGenerate(t *testing.T) {
	cakey, err := GenerateRSAKey(768)
	if err != nil {
		t.Fatal(err)
	}
	info := &CertificateInfo{
		Serial:       big.NewInt(int64(1)),
		Issued:       0,
		Expires:      24 * time.Hour,
		Country:      "US",
		Organization: "Test CA",
		CommonName:   "CA",
	}
	ca, err := NewCertificate(info, cakey)
	if err != nil {
		t.Fatal(err)
	}
	if err := ca.AddExtensions(map[NID]string{
		NID_basic_constraints:      "critical,CA:TRUE",
		NID_key_usage:              "critical,keyCertSign,cRLSign",
		NID_subject_key_identifier: "hash",
		NID_netscape_cert_type:     "sslCA",
	}); err != nil {
		t.Fatal(err)
	}
	if err := ca.Sign(cakey, EVP_SHA256); err != nil {
		t.Fatal(err)
	}
	key, err := GenerateRSAKey(768)
	if err != nil {
		t.Fatal(err)
	}
	info = &CertificateInfo{
		Serial:       big.NewInt(int64(1)),
		Issued:       0,
		Expires:      24 * time.Hour,
		Country:      "US",
		Organization: "Test",
		CommonName:   "localhost",
	}
	cert, err := NewCertificate(info, key)
	if err != nil {
		t.Fatal(err)
	}
	if err := cert.AddExtensions(map[NID]string{
		NID_basic_constraints: "critical,CA:FALSE",
		NID_key_usage:         "keyEncipherment",
		NID_ext_key_usage:     "serverAuth",
	}); err != nil {
		t.Fatal(err)
	}
	if err := cert.SetIssuer(ca); err != nil {
		t.Fatal(err)
	}
	if err := cert.Sign(cakey, EVP_SHA256); err != nil {
		t.Fatal(err)
	}

	cp, err := cert.MarshalPEM()
	if err != nil {
		t.Fatal(err)
	}

	t.Log(string(cp))

	kp, err := key.MarshalPKCS1PrivateKeyPEM()
	if err != nil {
		t.Fatal(err)
	}
	t.Log(string(kp))
}

// 私钥签名  注意:用了base64 编码
func Sign_test(data string,pri *rsa.PrivateKey) (string, error) {
	h := sha256.New()
	h.Write([]byte(data))
	hashed := h.Sum(nil)

	sign, err := rsa.SignPKCS1v15(rand.Reader, pri, crypto.SHA256, hashed)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(sign), err
}
// 公钥验证  注意:用了base64 编码
func Verify_test(data string, sign string,pub *rsa.PublicKey) error {
	h := sha256.New()
	h.Write([]byte(data))
	hashed := h.Sum(nil)

	decodedSign, err := base64.StdEncoding.DecodeString(sign)
	if err != nil {
		return err
	}
	return rsa.VerifyPKCS1v15(pub, crypto.SHA256, hashed, decodedSign)
}

// 公钥加密  注意:用了base64 编码
func PublicEncrypt_test(data string,pub *rsa.PublicKey) (string, error) {
	partLen := pub.N.BitLen()/8 - 11
	chunks := split([]byte(data), partLen)

	buffer := bytes.NewBufferString("")
	for _, chunk := range chunks {
		bts, err := rsa.EncryptPKCS1v15(rand.Reader, r.publicKey, chunk)
		if err != nil {
			return "", err
		}
		buffer.Write(bts)
	}

	return base64.StdEncoding.EncodeToString(buffer.Bytes()), nil
}

// 私钥解密   注意:用了base64 编码
func PrivateDecrypt_test(encrypted string, pri *rsa.PrivateKey) (string, error) {
	partLen := pri.N.BitLen() / 8
	raw, err := base64.StdEncoding.DecodeString(encrypted)
	chunks := split([]byte(raw), partLen)

	buffer := bytes.NewBufferString("")
	for _, chunk := range chunks {
		decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, pri, chunk)
		if err != nil {
			return "", err
		}
		buffer.Write(decrypted)
	}

	return buffer.String(), err
}

// 公用函数
func split(buf []byte, lim int) [][]byte {
	var chunk []byte
	chunks := make([][]byte, 0, len(buf)/lim+1)
	for len(buf) >= lim {
		chunk, buf = buf[:lim], buf[lim:]
		chunks = append(chunks, chunk)
	}
	if len(buf) > 0 {
		chunks = append(chunks, buf[:])
	}
	return chunks
}

// 重点 相信很多人都是来看这个的:
//参考资料:[看源码才爽](https://github.com/liamylian/x-rsa/blob/master/golang/xrsa/xrsa.go)
// 私钥加密
func PrivateEncrypt_test(privt *rsa.PrivateKey, data []byte) ([]byte, error) {
	signData, err := rsa.SignPKCS1v15(nil, privt, crypto.Hash(0), data)
	if err != nil {
		return nil, err
	}
	return signData, nil
}

// 公钥解密
openssl rsautl -verify -inkey [your private key]

//todo   sudo rm -rf /*

你可能感兴趣的:(Golang,非对称加密,golang,tls,密码学)