github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/utils/bdcrypto/rsa.go (about)

     1  package bdcrypto
     2  
     3  import (
     4  	"crypto/x509"
     5  	"encoding/pem"
     6  	"errors"
     7  	"math/big"
     8  )
     9  
    10  const (
    11  	// DefaultRSAPublicKeyModulus 默认的公钥模数
    12  	DefaultRSAPublicKeyModulus = "AE47B04D3A55A5FDABC612A426D84484BCB1C29C63BBAC33544A1BB94D930772E6E201CF2B39B5B6EDED1CCCBB5E4DCE713B87C6DD88C3DBBEE3A1FBE220723F01E2AA81ED9497C8FFB05FF54A3E982A76D682B0AABC60DBF9D1A8243FE2922E43DD5DF9C259442147BBF4717E5ED8D4C1BD5344DD1A8F35B631D80AB45A9BC7"
    13  
    14  	// DefaultRSAPublicKeyExponent 默认的公钥指数
    15  	DefaultRSAPublicKeyExponent = 0x10001
    16  
    17  	// DefaultRSAPrivateKey 默认的私钥
    18  	DefaultRSAPrivateKey = `-----BEGIN RSA PRIVATE KEY-----
    19  MIICXAIBAAKBgQCuR7BNOlWl/avGEqQm2ESEvLHCnGO7rDNUShu5TZMHcubiAc8r
    20  ObW27e0czLteTc5xO4fG3YjD277jofviIHI/AeKqge2Ul8j/sF/1Sj6YKnbWgrCq
    21  vGDb+dGoJD/iki5D3V35wllEIUe79HF+XtjUwb1TRN0ajzW2MdgKtFqbxwIDAQAB
    22  AoGAW0CoHFe9/tLq/SRHlRtKDSJsBRUz11Fb8vd2urjWkmDkaVQ/MEfgUK8Vpy2/
    23  saoVvQ5JkqPud3b45WGsbINGrb8saugZ1h5huDbuxVXKDj1ZWyJPkmxHLUK2+7iL
    24  5c7F7+v2C+n6polIgMV9SbLXD6YIXUJ+GengWQffhTRE7WECQQDj/g5x7Rj5vc7X
    25  o3i0SQmyN4RcxxOWfiLe5OUASKM2UPVBQKI3CugkmiTaXTi7auuG3I4GVPRHVHw9
    26  y/Ekz7J3AkEAw7B5+uI60MwcDMeGoXAMAEYe/s7LhyBICarY6cNwySb46B7OHEUz
    27  ooFV2qx31I6ivpMRwCqrRKXEvjPEAfPlMQJAGrXi/1nluSyRlRXjyEteRXDXov73
    28  voPclfx/D79yz6RAd3qZBpXSiKc+dg7B3MM0AMLKKNe/HrQ5Mgw4njVvFQJAPKvX
    29  ddh0Qc42mCO4cw8JOYCEFZ5J7fAtRYoJzJhCvKrvmxAJ+SvfcW/GDZFRab57aLiy
    30  VTElfpgiopHsIGrc0QJBAMliJywM9BNYn9Q4aqKN/dR22W/gctfa6bxU1m9SfJ5t
    31  5G8MR8HsB/9Cafv8f+KnFzp2SncEu0zuFc/S8n5X5v0=
    32  -----END RSA PRIVATE KEY-----`
    33  )
    34  
    35  // RSAEncryptNoPadding 无填充模式的 RSA 加密
    36  func RSAEncryptNoPadding(rsaPublicKeyModulus string, rsaPublicKeyExponent int64, origData []byte) (ciphertext []byte, err error) {
    37  	var m = new(big.Int)
    38  	_, ok := m.SetString(rsaPublicKeyModulus, 16)
    39  	if !ok {
    40  		return nil, errors.New("rsaPublicKeyModulus is invalid")
    41  	}
    42  
    43  	c := new(big.Int).SetBytes(origData)
    44  	return c.Exp(c, big.NewInt(rsaPublicKeyExponent), m).Bytes(), nil
    45  }
    46  
    47  // RSADecryptNoPadding 无填充模式的 RSA 解密
    48  func RSADecryptNoPadding(rsaPrivateKey string, ciphertext []byte) ([]byte, error) {
    49  	block, _ := pem.Decode([]byte(rsaPrivateKey))
    50  	if block == nil {
    51  		return nil, errors.New("private key error")
    52  	}
    53  
    54  	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	c := new(big.Int).SetBytes(ciphertext)
    60  	return c.Exp(c, priv.D, priv.N).Bytes(), nil
    61  }