51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
|
package crypto
|
||
|
|
||
|
import (
|
||
|
"crypto/rand"
|
||
|
"crypto/rsa"
|
||
|
"crypto/sha512"
|
||
|
"encoding/base64"
|
||
|
"math/big"
|
||
|
)
|
||
|
|
||
|
type RSAKey string
|
||
|
|
||
|
func (key *RSAKey) Encrypt(data []byte) []byte {
|
||
|
pk := key.PubFromBase64()
|
||
|
encrypted, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, &pk, data, nil)
|
||
|
throw(err)
|
||
|
return encrypted
|
||
|
}
|
||
|
|
||
|
func (key *RSAKey) Decrypt(data []byte) []byte {
|
||
|
pk := key.PKFromBase64()
|
||
|
decrypted, err := rsa.DecryptOAEP(sha512.New(), rand.Reader, &pk, data, nil)
|
||
|
throw(err)
|
||
|
return decrypted
|
||
|
}
|
||
|
|
||
|
func (key *RSAKey) EncryptToString(str string) string {
|
||
|
return base64.StdEncoding.EncodeToString(key.Encrypt([]byte(str)))
|
||
|
}
|
||
|
|
||
|
func (key *RSAKey) DecryptToString(b64 string) string {
|
||
|
raw, _ := base64.StdEncoding.DecodeString(b64)
|
||
|
return string(key.Decrypt(raw))
|
||
|
}
|
||
|
|
||
|
func (key *RSAKey) PubFromBase64() rsa.PublicKey {
|
||
|
raw, err := base64.StdEncoding.DecodeString(string(*key))
|
||
|
throw(err)
|
||
|
pk := rsa.PublicKey{
|
||
|
N: new(big.Int).SetBytes(raw),
|
||
|
E: 65537,
|
||
|
}
|
||
|
return pk
|
||
|
}
|
||
|
|
||
|
func (key *RSAKey) PKFromBase64() rsa.PrivateKey {
|
||
|
pk, err := Base64ToKeys(string(*key))
|
||
|
throw(err)
|
||
|
return *pk
|
||
|
}
|