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.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.