RSA OAEP Encrypt And Decrypt

Encrypt short payloads with RSA-OAEP and a context label, then verify that a mismatched label is rejected at decrypt time.

GoSecurity Boundaries

Code

gosnippet
42 lines
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"fmt"
)

func main() {
	// 生成 2048 位密钥;演示用,生产中应加载已有密钥
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("key generation failed:", err)
		return
	}
	publicKey := &privateKey.PublicKey

	message := []byte("transfer=42 amount=19.90")
	fmt.Println("plaintext bytes:", len(message))

	// OAEP 加密带随机填充:同一明文每次密文都不同
	label := []byte("payments")
	ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, message, label)
	if err != nil {
		fmt.Println("encrypt failed:", err)
		return
	}
	fmt.Println("ciphertext bytes:", len(ciphertext), "modulus bits:", publicKey.N.BitLen())

	// 解密必须提供相同的 hash 与 label
	plaintext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, ciphertext, label)
	if err != nil {
		fmt.Println("decrypt failed:", err)
		return
	}
	fmt.Println("recovered:", string(plaintext))

	// label 不匹配时解密失败,阻止跨上下文重放
	_, err = rsa.DecryptOAEP(sha256.New(), rand.Reader, privateKey, ciphertext, []byte("other"))
	fmt.Println("wrong label rejected:", err != nil)
}

What runs when

RSA OAEP Encrypt And Decrypt is built around the function main.

Error handling is inline: 3 places test err != nil and branch immediately.

Applying it

The run emits 7 labeled sections — key generation failed:, plaintext bytes:, encrypt failed:, ciphertext bytes:, decrypt failed:, recovered:, wrong label rejected: — one per step.

Statements that matter

if err != nil {
	fmt.Println("key generation failed:", err)
	return
}
if err != nil {
	fmt.Println("encrypt failed:", err)
	return
}
if err != nil {
	fmt.Println("decrypt failed:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does RSA OAEP Encrypt And Decrypt print when run?
Execute the whole file; each printed line is prefixed with a label like `key generation failed:`, `plaintext bytes:`, `encrypt failed:`.