13 // CreateMasterRsa Create master key interface implemented by rsa
14 // matDesc will be converted to json string
15 func CreateMasterRsa(matDesc map[string]string, publicKey string, privateKey string) (MasterCipher, error) {
16 var masterCipher MasterRsaCipher
19 b, err := json.Marshal(matDesc)
21 return masterCipher, err
25 masterCipher.MatDesc = jsonDesc
26 masterCipher.PublicKey = publicKey
27 masterCipher.PrivateKey = privateKey
28 return masterCipher, nil
31 // MasterRsaCipher rsa master key interface
32 type MasterRsaCipher struct {
38 // GetWrapAlgorithm get master key wrap algorithm
39 func (mrc MasterRsaCipher) GetWrapAlgorithm() string {
43 // GetMatDesc get master key describe
44 func (mrc MasterRsaCipher) GetMatDesc() string {
48 // Encrypt encrypt data by rsa public key
49 // Mainly used to encrypt object's symmetric secret key and iv
50 func (mrc MasterRsaCipher) Encrypt(plainData []byte) ([]byte, error) {
51 block, _ := pem.Decode([]byte(mrc.PublicKey))
53 return nil, fmt.Errorf("pem.Decode public key error")
56 var pub *rsa.PublicKey
57 if block.Type == "PUBLIC KEY" {
59 pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
63 pub = pubInterface.(*rsa.PublicKey)
64 } else if block.Type == "RSA PUBLIC KEY" {
66 pub = &rsa.PublicKey{}
67 _, err := asn1.Unmarshal(block.Bytes, pub)
72 return nil, fmt.Errorf("not supported public key,type:%s", block.Type)
74 return rsa.EncryptPKCS1v15(rand.Reader, pub, plainData)
77 // Decrypt Decrypt data by rsa private key
78 // Mainly used to decrypt object's symmetric secret key and iv
79 func (mrc MasterRsaCipher) Decrypt(cryptoData []byte) ([]byte, error) {
80 block, _ := pem.Decode([]byte(mrc.PrivateKey))
82 return nil, fmt.Errorf("pem.Decode private key error")
85 if block.Type == "PRIVATE KEY" {
87 privInterface, err := x509.ParsePKCS8PrivateKey(block.Bytes)
91 return rsa.DecryptPKCS1v15(rand.Reader, privInterface.(*rsa.PrivateKey), cryptoData)
92 } else if block.Type == "RSA PRIVATE KEY" {
94 priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
98 return rsa.DecryptPKCS1v15(rand.Reader, priv, cryptoData)
100 return nil, fmt.Errorf("not supported private key,type:%s", block.Type)