RSA 加密解密和签名验签 Go 语言实现
package crypto
import ( "crypto" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "errors" "github.com/containous/traefik/v2/pkg/log" )
type pkcsClient struct { privateKey *rsa.PrivateKey publicKey *rsa.PublicKey } type Type int64
const ( PKCS1 Type = iota PKCS8 )
func (this *pkcsClient) Encrypt(plaintext []byte) ([]byte, error) { return rsa.EncryptPKCS1v15(rand.Reader, this.publicKey, plaintext) } func (this *pkcsClient) Decrypt(ciphertext []byte) ([]byte, error) { return rsa.DecryptPKCS1v15(rand.Reader, this.privateKey, ciphertext) }
func (this *pkcsClient) Sign(src []byte, hash crypto.Hash) ([]byte, error) { h := hash.New() h.Write(src) hashed := h.Sum(nil) return rsa.SignPKCS1v15(rand.Reader, this.privateKey, hash, hashed) }
func (this *pkcsClient) Verify(src []byte, sign []byte, hash crypto.Hash) error { h := hash.New() h.Write(src) hashed := h.Sum(nil) return rsa.VerifyPKCS1v15(this.publicKey, hash, hashed, sign) }
type Cipher interface { Encrypt(plaintext []byte) ([]byte, error) Decrypt(ciphertext []byte) ([]byte, error) Sign(src []byte, hash crypto.Hash) ([]byte, error) Verify(src []byte, sign []byte, hash crypto.Hash) error }
//默认客户端,pkcs8私钥格式,pem编码 func NewDefault(privateKey, publicKey string) (Cipher, error) { blockPri, _ := pem.Decode([]byte(privateKey)) if blockPri == nil { return nil, errors.New('private key error') }
blockPub, _ := pem.Decode([]byte(publicKey))
if blockPub == nil {
return nil, errors.New('public key error')
}
return NewRsa(blockPri.Bytes, blockPub.Bytes, PKCS8)
}
func NewRsa(privateKey, publicKey []byte, privateKeyType Type) (Cipher, error) {
priKey, err := genPriKey(privateKey, privateKeyType)
if err != nil {
return nil, err
}
pubKey, err := genPubKey(publicKey)
if err != nil {
return nil, err
}
return &pkcsClient{privateKey: priKey, publicKey: pubKey}, nil
}
func genPubKey(publicKey []byte) (*rsa.PublicKey, error) { pub, err := x509.ParsePKIXPublicKey(publicKey) if err != nil { return nil, err } return pub.(*rsa.PublicKey), nil }
func genPriKey(privateKey []byte, privateKeyType Type) (*rsa.PrivateKey, error) { var priKey *rsa.PrivateKey var err error switch privateKeyType { case PKCS1: { priKey, err = x509.ParsePKCS1PrivateKey([]byte(privateKey)) if err != nil { return nil, err } } case PKCS8: { prkI, err := x509.ParsePKCS8PrivateKey([]byte(privateKey)) if err != nil { return nil, err } priKey = prkI.(*rsa.PrivateKey) } default: { return nil, errors.New('unsupport private key type') } } return priKey, nil }
func KeyPair() (priKey, pubKey string, err error) { privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { log.WithoutContext().Errorln(err) return } priKey = base64.StdEncoding.EncodeToString(x509.MarshalPKCS1PrivateKey(privateKey))
// 生成公钥文件
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
log.WithoutContext().Errorln(err)
return
}
pubKey = base64.StdEncoding.EncodeToString(derPkix)
return
} func KeyPairPem() (priKey, pubKey string, err error) { privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return "", "", err } var pemPrivateBlock = &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey), } priKey = string(pem.EncodeToMemory(pemPrivateBlock))
// 生成公钥文件
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return "", "", err
}
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: derPkix,
}
pubKey = string(pem.EncodeToMemory(block))
return priKey, pubKey, nil
}
转为java内容:package crypto;
import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.Cipher; import java.util.Base64;
public class RSAUtil { private static final String ALGORITHM = "RSA";
public static byte[] encrypt(byte[] data, String publicKey) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] encryptedData, String privateKey) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, priKey);
return cipher.doFinal(encryptedData);
}
public static byte[] sign(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PrivateKey priKey = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance('SHA256withRSA');
signature.initSign(priKey);
signature.update(data);
return signature.sign();
}
public static boolean verify(byte[] data, byte[] sign, String publicKey) throws Exception {
byte[] keyBytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance('SHA256withRSA');
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(sign);
}
public static void main(String[] args) throws Exception {
String publicKey = ""; // The public key
String privateKey = ""; // The private key
String plaintext = "Hello, World!";
byte[] encrypted = encrypt(plaintext.getBytes(StandardCharsets.UTF_8), publicKey);
byte[] decrypted = decrypt(encrypted, privateKey);
System.out.println('Plaintext: ' + plaintext);
System.out.println('Encrypted: ' + Base64.getEncoder().encodeToString(encrypted));
System.out.println('Decrypted: ' + new String(decrypted, StandardCharsets.UTF_8));
byte[] signature = sign(plaintext.getBytes(StandardCharsets.UTF_8), privateKey);
boolean verified = verify(plaintext.getBytes(StandardCharsets.UTF_8), signature, publicKey);
System.out.println('Signature: ' + Base64.getEncoder().encodeToString(signature));
System.out.println('Verified: ' + verified);
}
原文地址: http://www.cveoy.top/t/topic/phbX 著作权归作者所有。请勿转载和采集!