diff --git a/cryptor/crypto.go b/cryptor/crypto.go index cdca8a0..978ed87 100644 --- a/cryptor/crypto.go +++ b/cryptor/crypto.go @@ -13,6 +13,7 @@ import ( "crypto/des" "crypto/rand" "crypto/rsa" + "crypto/sha256" "crypto/x509" "encoding/pem" "io" @@ -505,3 +506,32 @@ func RsaDecrypt(data []byte, privateKeyFileName string) []byte { } return plainText } + +// GenerateRsaKeyPair create rsa private and public key. +// Play: todo +func GenerateRsaKeyPair(keySize int) (*rsa.PrivateKey, *rsa.PublicKey) { + privateKey, _ := rsa.GenerateKey(rand.Reader, keySize) + return privateKey, &privateKey.PublicKey +} + +// RsaEncryptOAEP encrypts the given data with RSA-OAEP. +// Play: todo +func RsaEncryptOAEP(data []byte, label []byte, key rsa.PublicKey) ([]byte, error) { + encryptedBytes, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, &key, data, label) + if err != nil { + return nil, err + } + + return encryptedBytes, nil +} + +// RsaDecryptOAEP decrypts the data with RSA-OAEP. +// Play: todo +func RsaDecryptOAEP(ciphertext []byte, label []byte, key rsa.PrivateKey) ([]byte, error) { + decryptedBytes, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, &key, ciphertext, label) + if err != nil { + return nil, err + } + + return decryptedBytes, nil +} diff --git a/cryptor/crypto_example_test.go b/cryptor/crypto_example_test.go index 7266c95..574da99 100644 --- a/cryptor/crypto_example_test.go +++ b/cryptor/crypto_example_test.go @@ -1,6 +1,8 @@ package cryptor -import "fmt" +import ( + "fmt" +) func ExampleAesEcbEncrypt() { data := "hello" @@ -484,3 +486,25 @@ func ExampleSha512WithBase64() { // Output: // m3HSJL1i83hdltRq0+o9czGb+8KJDKra4t/3JRlnPKcjI8PZm6XBHXx6zG4UuMXaDEZjR1wuXDre9G9zvN7AQw== } + +func ExampleRsaEncryptOAEP() { + pri, pub := GenerateRsaKeyPair(1024) + + data := []byte("hello world") + label := []byte("123456") + + encrypted, err := RsaEncryptOAEP(data, label, *pub) + if err != nil { + return + } + + decrypted, err := RsaDecryptOAEP([]byte(encrypted), label, *pri) + if err != nil { + return + } + + fmt.Println(string(decrypted)) + + // Output: + // hello world +} diff --git a/cryptor/crypto_test.go b/cryptor/crypto_test.go index 98e92f4..58813c9 100644 --- a/cryptor/crypto_test.go +++ b/cryptor/crypto_test.go @@ -150,3 +150,21 @@ func TestRsaEncrypt(t *testing.T) { assert := internal.NewAssert(t, "TestRsaEncrypt") assert.Equal(string(data), string(decrypted)) } + +func TestRsaEncryptOAEP(t *testing.T) { + assert := internal.NewAssert(t, "TestRsaEncrypt") + t.Parallel() + + pri, pub := GenerateRsaKeyPair(1024) + + data := []byte("hello world") + label := []byte("123456") + + encrypted, err := RsaEncryptOAEP(data, label, *pub) + assert.IsNil(err) + + decrypted, err := RsaDecryptOAEP([]byte(encrypted), label, *pri) + + assert.IsNil(err) + assert.Equal("hello world", string(decrypted)) +}