Standard library / crypto/rsa

crypto/rsa.EncryptOAEP()

Encrypts a short message with RSA-OAEP. Use SHA-256, secure randomness and matching label for decryption. Maximum length is modulus bytes minus twice the hash size minus two; use hybrid encryption for large data. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)

Parameters & Attributes

NameTypeDescription
hashhash.HashHash algorithm, hash instance or digest as specified by the signature and description.
randomio.ReaderCryptographically secure random source; see description for exceptions.
pub*PublicKeyPublic key used for the operation.
msg[]byteMessage bytes to encrypt.
label[]byteOAEP label; must match encryption.

Return Value

([]byte, error)

Result as described above; check any returned error before use.

Working Example

Example Snippetgo
package main
import (  "crypto/rand"  "crypto/rsa"  "crypto/sha256"  "fmt")
func main() {  k := must(rsa.GenerateKey(rand.Reader, 2048))  ct := must(rsa.EncryptOAEP(sha256.New(), rand.Reader, &k.PublicKey, []byte("Go"), []byte("demo")))  fmt.Println(len(ct) == k.Size())}func must[T any](v T, e error) T {  if e != nil {    panic(e)  }  return v}func check(e error) {  if e != nil {    panic(e)  }}
Go Reference