45 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
			
		
		
	
	
			45 lines
		
	
	
		
			1.1 KiB
		
	
	
	
		
			Go
		
	
	
	
| package apicrypt
 | |
| 
 | |
| import (
 | |
| 	"PaymentCenter/app/constants/errorcode"
 | |
| 	"PaymentCenter/app/models/appmodel"
 | |
| 	"PaymentCenter/app/utils/encrypt/rsa"
 | |
| 	"encoding/base64"
 | |
| )
 | |
| 
 | |
| func NewRsa(app *appmodel.App) ApiCrypt {
 | |
| 	return &Rsa{
 | |
| 		App: app,
 | |
| 	}
 | |
| }
 | |
| 
 | |
| func (r *Rsa) Encrypt(data string) (encryptData []byte, errCode int) {
 | |
| 	if r.App.PublicKey == "" {
 | |
| 		return nil, errorcode.AppRsaEncryptKeyNotFound
 | |
| 	}
 | |
| 	publicKeyPEM := `-----BEGIN PUBLIC KEY-----  
 | |
| ` + r.App.PublicKey + `  
 | |
| -----END PUBLIC KEY-----`
 | |
| 	encryptByte, err := rsa.Encrypt(publicKeyPEM, data)
 | |
| 	if err != nil {
 | |
| 		return nil, errorcode.AppRsaEncryptFail
 | |
| 	}
 | |
| 	encryptData = []byte(base64.StdEncoding.EncodeToString(encryptByte))
 | |
| 	return
 | |
| }
 | |
| 
 | |
| func (r *Rsa) Decrypt(encryptData string) (decryptData []byte, errCode int) {
 | |
| 
 | |
| 	if r.App.PrivateKey == "" {
 | |
| 		return nil, errorcode.AppRsaDecryptKeyNotFound
 | |
| 	}
 | |
| 	privateKeyPEM := `-----BEGIN RSA PRIVATE KEY-----  
 | |
| ` + r.App.PrivateKey + `  
 | |
| -----END RSA PRIVATE KEY-----`
 | |
| 	decryptData, err := rsa.Decrypt(privateKeyPEM, encryptData)
 | |
| 	if err != nil || decryptData == nil {
 | |
| 		return nil, errorcode.AppRsaDecryptFail
 | |
| 	}
 | |
| 	return
 | |
| }
 |