rsa
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package rsa implements RSA encryption as specified in PKCS #1 andRFC 8017.
RSA is a single, fundamental operation that is used in this package toimplement either public-key encryption or public-key signatures.
The original specification for encryption and signatures with RSA is PKCS #1and the terms "RSA encryption" and "RSA signatures" by default refer toPKCS #1 version 1.5. However, that specification has flaws and new designsshould use version 2, usually called by just OAEP and PSS, wherepossible.
Two sets of interfaces are included in this package. When a more abstractinterface isn't necessary, there are functions for encrypting/decryptingwith v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstractover the public key primitive, the PrivateKey type implements theDecrypter and Signer interfaces from the crypto package.
Operations involving private keys are implemented using constant-timealgorithms, except forGenerateKey and for some operations involvingdeprecated multi-prime keys.
Minimum key size¶
GenerateKey returns an error if a key of less than 1024 bits is requested,and all Sign, Verify, Encrypt, and Decrypt methods return an error if usedwith a key smaller than 1024 bits. Such keys are insecure and should not beused.
The rsa1024min=0 GODEBUG setting suppresses this error, but we recommenddoing so only in tests, if necessary. Tests can set this option usingtesting.T.Setenv or by including "//go:debug rsa1024min=0" in a *_test.gosource file.
Alternatively, see theGenerateKey (TestKey) example for a pregeneratedtest-only 2048-bit key.
Index¶
- Constants
- Variables
- func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, ...) ([]byte, error)
- func DecryptPKCS1v15(random io.Reader, priv *PrivateKey, ciphertext []byte) ([]byte, error)
- func DecryptPKCS1v15SessionKey(random io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) error
- func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)
- func EncryptPKCS1v15(random io.Reader, pub *PublicKey, msg []byte) ([]byte, error)
- func SignPKCS1v15(random io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) ([]byte, error)
- func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, ...) ([]byte, error)
- func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) error
- func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error
- type CRTValue
- type OAEPOptions
- type PKCS1v15DecryptOptions
- type PSSOptions
- type PrecomputedValues
- type PrivateKey
- func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)
- func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool
- func (priv *PrivateKey) Precompute()
- func (priv *PrivateKey) Public() crypto.PublicKey
- func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
- func (priv *PrivateKey) Validate() error
- type PublicKey
Examples¶
Constants¶
const (// PSSSaltLengthAuto causes the salt in a PSS signature to be as large// as possible when signing, and to be auto-detected when verifying.//// When signing in FIPS 140-3 mode, the salt length is capped at the length// of the hash function used in the signature.PSSSaltLengthAuto = 0// PSSSaltLengthEqualsHash causes the salt length to equal the length// of the hash used in the signature.PSSSaltLengthEqualsHash = -1)
Variables¶
var ErrDecryption =errors.New("crypto/rsa: decryption error")ErrDecryption represents a failure to decrypt a message.It is deliberately vague to avoid adaptive attacks.
var ErrMessageTooLong =errors.New("crypto/rsa: message too long for RSA key size")ErrMessageTooLong is returned when attempting to encrypt or sign a messagewhich is too large for the size of the key. When usingSignPSS, this can alsobe returned if the size of the salt is too large.
var ErrVerification =errors.New("crypto/rsa: verification error")ErrVerification represents a failure to verify a signature.It is deliberately vague to avoid adaptive attacks.
Functions¶
funcDecryptOAEP¶
func DecryptOAEP(hashhash.Hash, randomio.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte,error)
DecryptOAEP decrypts ciphertext using RSA-OAEP.
OAEP is parameterised by a hash function that is used as a random oracle.Encryption and decryption of a given message must use the same hash functionand sha256.New() is a reasonable choice.
The random parameter is legacy and ignored, and it can be nil.
The label parameter must match the value given when encrypting. SeeEncryptOAEP for details.
Example¶
ciphertext, _ := hex.DecodeString("4d1ee10e8f286390258c51a5e80802844c3e6358ad6690b7285218a7c7ed7fc3a4c7b950fbd04d4b0239cc060dcc7065ca6f84c1756deb71ca5685cadbb82be025e16449b905c568a19c088a1abfad54bf7ecc67a7df39943ec511091a34c0f2348d04e058fcff4d55644de3cd1d580791d4524b92f3e91695582e6e340a1c50b6c6d78e80b4e42c5b4d45e479b492de42bbd39cc642ebb80226bb5200020d501b24a37bcc2ec7f34e596b4fd6b063de4858dbf5a4e3dd18e262eda0ec2d19dbd8e890d672b63d368768360b20c0b6b8592a438fa275e5fa7f60bef0dd39673fd3989cc54d2cb80c08fcd19dacbc265ee1c6014616b0e04ea0328c2a04e73460")label := []byte("orders")plaintext, err := rsa.DecryptOAEP(sha256.New(), nil, test2048Key, ciphertext, label)if err != nil {fmt.Fprintf(os.Stderr, "Error from decryption: %s\n", err)return}fmt.Printf("Plaintext: %s\n", plaintext)// Remember that encryption only provides confidentiality. The// ciphertext should be signed before authenticity is assumed and, even// then, consider that messages might be reordered.funcDecryptPKCS1v15¶
DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS #1 v1.5.The random parameter is legacy and ignored, and it can be nil.
Note that whether this function returns an error or not discloses secretinformation. If an attacker can cause this function to run repeatedly andlearn whether each instance returned an error then they can decrypt andforge signatures as if they had the private key. SeeDecryptPKCS1v15SessionKey for a way of solving this problem.
funcDecryptPKCS1v15SessionKey¶
func DecryptPKCS1v15SessionKey(randomio.Reader, priv *PrivateKey, ciphertext []byte, key []byte)error
DecryptPKCS1v15SessionKey decrypts a session key using RSA and the paddingscheme from PKCS #1 v1.5. The random parameter is legacy and ignored, and itcan be nil.
DecryptPKCS1v15SessionKey returns an error if the ciphertext is the wronglength or if the ciphertext is greater than the public modulus. Otherwise, noerror is returned. If the padding is valid, the resulting plaintext messageis copied into key. Otherwise, key is unchanged. These alternatives occur inconstant time. It is intended that the user of this function generate arandom session key beforehand and continue the protocol with the resultingvalue.
Note that if the session key is too small then it may be possible for anattacker to brute-force it. If they can do that then they can learn whether arandom value was used (because it'll be different for the same ciphertext)and thus whether the padding was correct. This also defeats the point of thisfunction. Using at least a 16-byte key will protect against this attack.
This method implements protections against Bleichenbacher chosen ciphertextattacks [0] described inRFC 3218 Section 2.3.2 [1]. While these protectionsmake a Bleichenbacher attack significantly more difficult, the protectionsare only effective if the rest of the protocol which usesDecryptPKCS1v15SessionKey is designed with these considerations in mind. Inparticular, if any subsequent operations which use the decrypted session keyleak any information about the key (e.g. whether it is a static or randomkey) then the mitigations are defeated. This method must be used extremelycarefully, and typically should only be used when absolutely necessary forcompatibility with an existing protocol (such as TLS) that is designed withthese properties in mind.
- [0] “Chosen Ciphertext Attacks Against Protocols Based on the RSA EncryptionStandard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology (Crypto '98)
- [1]RFC 3218, Preventing the Million Message Attack on CMS,https://www.rfc-editor.org/rfc/rfc3218.html
Example¶
RSA is able to encrypt only a very limited amount of data. In orderto encrypt reasonable amounts of data a hybrid scheme is commonlyused: RSA is used to encrypt a key for a symmetric primitive likeAES-GCM.
Before encrypting, data is “padded” by embedding it in a knownstructure. This is done for a number of reasons, but the mostobvious is to ensure that the value is large enough that theexponentiation is larger than the modulus. (Otherwise it could bedecrypted with a square-root.)
In these designs, when using PKCS #1 v1.5, it's vitally important toavoid disclosing whether the received RSA message was well-formed(that is, whether the result of decrypting is a correctly paddedmessage) because this leaks secret information.DecryptPKCS1v15SessionKey is designed for this situation and copiesthe decrypted, symmetric key (if well-formed) in constant-time overa buffer that contains a random key. Thus, if the RSA result isn'twell-formed, the implementation uses a random key in constant time.
// The hybrid scheme should use at least a 16-byte symmetric key. Here// we read the random key that will be used if the RSA decryption isn't// well-formed.key := make([]byte, 32)if _, err := rand.Read(key); err != nil {panic("RNG failure")}rsaCiphertext, _ := hex.DecodeString("aabbccddeeff")if err := rsa.DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, rsaCiphertext, key); err != nil {// Any errors that result will be “public” – meaning that they// can be determined without any secret information. (For// instance, if the length of key is impossible given the RSA// public key.)fmt.Fprintf(os.Stderr, "Error from RSA decryption: %s\n", err)return}// Given the resulting key, a symmetric scheme can be used to decrypt a// larger ciphertext.block, err := aes.NewCipher(key)if err != nil {panic("aes.NewCipher failed: " + err.Error())}// Since the key is random, using a fixed nonce is acceptable as the// (key, nonce) pair will still be unique, as required.var zeroNonce [12]byteaead, err := cipher.NewGCM(block)if err != nil {panic("cipher.NewGCM failed: " + err.Error())}ciphertext, _ := hex.DecodeString("00112233445566")plaintext, err := aead.Open(nil, zeroNonce[:], ciphertext, nil)if err != nil {// The RSA ciphertext was badly formed; the decryption will// fail here because the AES-GCM key will be incorrect.fmt.Fprintf(os.Stderr, "Error decrypting: %s\n", err)return}fmt.Printf("Plaintext: %s\n", plaintext)funcEncryptOAEP¶
func EncryptOAEP(hashhash.Hash, randomio.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte,error)
EncryptOAEP encrypts the given message with RSA-OAEP.
OAEP is parameterised by a hash function that is used as a random oracle.Encryption and decryption of a given message must use the same hash functionand sha256.New() is a reasonable choice.
The random parameter is used as a source of entropy to ensure thatencrypting the same message twice doesn't result in the same ciphertext.Most applications should usecrypto/rand.Reader as random.
The label parameter may contain arbitrary data that will not be encrypted,but which gives important context to the message. For example, if a givenpublic key is used to encrypt two types of messages then distinct labelvalues could be used to ensure that a ciphertext for one purpose cannot beused for another by an attacker. If not required it can be empty.
The message must be no longer than the length of the public modulus minustwice the hash length, minus a further 2.
Example¶
secretMessage := []byte("send reinforcements, we're going to advance")label := []byte("orders")// crypto/rand.Reader is a good source of entropy for randomizing the// encryption function.rng := rand.Readerciphertext, err := rsa.EncryptOAEP(sha256.New(), rng, &test2048Key.PublicKey, secretMessage, label)if err != nil {fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)return}// Since encryption is a randomized function, ciphertext will be// different each time.fmt.Printf("Ciphertext: %x\n", ciphertext)funcEncryptPKCS1v15¶
EncryptPKCS1v15 encrypts the given message with RSA and the paddingscheme from PKCS #1 v1.5. The message must be no longer than thelength of the public modulus minus 11 bytes.
The random parameter is used as a source of entropy to ensure thatencrypting the same message twice doesn't result in the sameciphertext. Most applications should usecrypto/rand.Readeras random. Note that the returned ciphertext does not dependdeterministically on the bytes read from random, and may changebetween calls and/or between versions.
WARNING: use of this function to encrypt plaintexts other thansession keys is dangerous. Use RSA OAEP in new protocols.
funcSignPKCS1v15¶
SignPKCS1v15 calculates the signature of hashed usingRSASSA-PKCS1-V1_5-SIGN from RSA PKCS #1 v1.5. Note that hashed mustbe the result of hashing the input message using the given hashfunction. If hash is zero, hashed is signed directly. This isn'tadvisable except for interoperability.
The random parameter is legacy and ignored, and it can be nil.
This function is deterministic. Thus, if the set of possiblemessages is small, an attacker may be able to build a map frommessages to signatures and identify the signed messages. As ever,signatures provide authenticity, not confidentiality.
Example¶
message := []byte("message to be signed")// Only small messages can be signed directly; thus the hash of a// message, rather than the message itself, is signed. This requires// that the hash function be collision resistant. SHA-256 is the// least-strong hash function that should be used for this at the time// of writing (2016).hashed := sha256.Sum256(message)signature, err := rsa.SignPKCS1v15(nil, rsaPrivateKey, crypto.SHA256, hashed[:])if err != nil {fmt.Fprintf(os.Stderr, "Error from signing: %s\n", err)return}fmt.Printf("Signature: %x\n", signature)funcSignPSS¶added ingo1.2
func SignPSS(randio.Reader, priv *PrivateKey, hashcrypto.Hash, digest []byte, opts *PSSOptions) ([]byte,error)
SignPSS calculates the signature of digest using PSS.
digest must be the result of hashing the input message using the given hashfunction. The opts argument may be nil, in which case sensible defaults areused. If opts.Hash is set, it overrides hash.
The signature is randomized depending on the message, key, and salt size,using bytes from rand. Most applications should usecrypto/rand.Reader asrand.
funcVerifyPKCS1v15¶
VerifyPKCS1v15 verifies an RSA PKCS #1 v1.5 signature.hashed is the result of hashing the input message using the given hashfunction and sig is the signature. A valid signature is indicated byreturning a nil error. If hash is zero then hashed is used directly. Thisisn't advisable except for interoperability.
The inputs are not considered confidential, and may leak through timing sidechannels, or if an attacker has control of part of the inputs.
Example¶
message := []byte("message to be signed")signature, _ := hex.DecodeString("ad2766728615cc7a746cc553916380ca7bfa4f8983b990913bc69eb0556539a350ff0f8fe65ddfd3ebe91fe1c299c2fac135bc8c61e26be44ee259f2f80c1530")// Only small messages can be signed directly; thus the hash of a// message, rather than the message itself, is signed. This requires// that the hash function be collision resistant. SHA-256 is the// least-strong hash function that should be used for this at the time// of writing (2016).hashed := sha256.Sum256(message)err := rsa.VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.SHA256, hashed[:], signature)if err != nil {fmt.Fprintf(os.Stderr, "Error from verification: %s\n", err)return}// signature is a valid signature of message from the public key.funcVerifyPSS¶added ingo1.2
VerifyPSS verifies a PSS signature.
A valid signature is indicated by returning a nil error. digest must be theresult of hashing the input message using the given hash function. The optsargument may be nil, in which case sensible defaults are used. opts.Hash isignored.
The inputs are not considered confidential, and may leak through timing sidechannels, or if an attacker has control of part of the inputs.
Types¶
typeCRTValue¶
type CRTValue struct {Exp *big.Int// D mod (prime-1).Coeff *big.Int// R·Coeff ≡ 1 mod Prime.R *big.Int// product of primes prior to this (inc p and q).}CRTValue contains the precomputed Chinese remainder theorem values.
typeOAEPOptions¶added ingo1.5
type OAEPOptions struct {// Hash is the hash function that will be used when generating the mask.Hashcrypto.Hash// MGFHash is the hash function used for MGF1.// If zero, Hash is used instead.MGFHashcrypto.Hash// Label is an arbitrary byte string that must be equal to the value// used when encrypting.Label []byte}OAEPOptions is an interface for passing options to OAEP decryption using thecrypto.Decrypter interface.
typePKCS1v15DecryptOptions¶added ingo1.5
type PKCS1v15DecryptOptions struct {// SessionKeyLen is the length of the session key that is being// decrypted. If not zero, then a padding error during decryption will// cause a random plaintext of this length to be returned rather than// an error. These alternatives happen in constant time.SessionKeyLenint}PKCS1v15DecryptOptions is for passing options to PKCS #1 v1.5 decryption usingthecrypto.Decrypter interface.
typePSSOptions¶added ingo1.2
type PSSOptions struct {// SaltLength controls the length of the salt used in the PSS signature. It// can either be a positive number of bytes, or one of the special// PSSSaltLength constants.SaltLengthint// Hash is the hash function used to generate the message digest. If not// zero, it overrides the hash function passed to SignPSS. It's required// when using PrivateKey.Sign.Hashcrypto.Hash}PSSOptions contains options for creating and verifying PSS signatures.
func (*PSSOptions)HashFunc¶added ingo1.4
func (opts *PSSOptions) HashFunc()crypto.Hash
HashFunc returns opts.Hash so thatPSSOptions implementscrypto.SignerOpts.
typePrecomputedValues¶
type PrecomputedValues struct {Dp, Dq *big.Int// D mod (P-1) (or mod Q-1)Qinv *big.Int// Q^-1 mod P// CRTValues is used for the 3rd and subsequent primes. Due to a// historical accident, the CRT for the first two primes is handled// differently in PKCS #1 and interoperability is sufficiently// important that we mirror this.//// Deprecated: These values are still filled in by Precompute for// backwards compatibility but are not used. Multi-prime RSA is very rare,// and is implemented by this package without CRT optimizations to limit// complexity.CRTValues []CRTValue// contains filtered or unexported fields}typePrivateKey¶
type PrivateKey struct {PublicKey// public part.D *big.Int// private exponentPrimes []*big.Int// prime factors of N, has >= 2 elements.// Precomputed contains precomputed values that speed up RSA operations,// if available. It must be generated by calling PrivateKey.Precompute and// must not be modified.PrecomputedPrecomputedValues}A PrivateKey represents an RSA key
funcGenerateKey¶
func GenerateKey(randomio.Reader, bitsint) (*PrivateKey,error)
GenerateKey generates a random RSA private key of the given bit size.
If bits is less than 1024,GenerateKey returns an error. See the "Minimumkey size" section for further details.
Most applications should usecrypto/rand.Reader as rand. Note that thereturned key does not depend deterministically on the bytes read from rand,and may change between calls and/or between versions.
Example¶
package mainimport ("crypto/rand""crypto/rsa""crypto/x509""encoding/pem""fmt""os")func main() {privateKey, err := rsa.GenerateKey(rand.Reader, 2048)if err != nil {fmt.Fprintf(os.Stderr, "Error generating RSA key: %s", err)return}der, err := x509.MarshalPKCS8PrivateKey(privateKey)if err != nil {fmt.Fprintf(os.Stderr, "Error marshalling RSA private key: %s", err)return}fmt.Printf("%s", pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY",Bytes: der,}))}Example (TestKey)¶
package mainimport ("crypto/x509""encoding/pem""fmt""strings")func main() {// This is an insecure, test-only key from RFC 9500, Section 2.1.// It can be used in tests to avoid slow key generation.block, _ := pem.Decode([]byte(strings.ReplaceAll(`-----BEGIN RSA TESTING KEY-----MIIEowIBAAKCAQEAsPnoGUOnrpiSqt4XynxA+HRP7S+BSObI6qJ7fQAVSPtRkqsotWxQYLEYzNEx5ZSHTGypibVsJylvCfuToDTfMul8b/CZjP2Ob0LdpYrNH6l5hvFE89FU1nZQF15oVLOpUgA7wGiHuEVawrGfey92UE68mOyUVXGweJIVDdxqdMoPvNNUl86BU02vlBiESxOuox+dWmuVV7vfYZ79Toh/LUK43YvJh+rhv4nKuF7iHjVjBd9sB6iDjj70HFldzOQ9r8SRI+9NirupPTkF5AKNe6kUhKJ1luB7S27ZkvB3tSTT3P593VVJvnzOjaA1z6Cz+4+eRvcysqhrRgFlwI9TEwIDAQABAoIBAEEYiyDP29vCzx/+dS3LqnI5BjUuJhXUnc6AWX/PCgVAO+8A+gZRgvct7PtZb0sM6P9ZcLrweomlGezIFrL0/6xQaa8bBr/ve/a8155OgcjFo6fZEw3Dz7ra5fbSiPmu4/b/kvrg+Br1l77Jaun6uUAs1f5B9wW+vbR7tzbT/mxaUeDiBzKpe15GwcvbJtdIVMa2YErtRjc1/5B2BGVXyvlJv0SIlcIEMsHgnAFOp1ZgQ08aDzvilLq8XVMOahAhP1O2A3X8hKdXPyrxIVWE9bS9ptTo+eF6eNl+d7htpKGEZHUxinoQpWEBTv+iOoHsVunkEJ3vjLP3lyI/fY0NQ1ECgYEA3RBXAjgvIys2gfU3keImF8e/TprLge1I2vbWmV2j6rZCg5r/AS0upii5CvJ5/T5vfJPNgPBy8B/yRDs+6PJO1GmnlhOkG9JAIPkv0RBZvR0PMBtbp6nTY3yo1lwamBVBfY6rc0sLTzosZh2aGoLzrHNMQFMGaauORzBFpY5lU50CgYEAzPHlu5DI6Xgep1vr8QvCUuEesCOgJg8Yh1UqVoY/SmQh6MYAv1I9bLGwrb3WW/7kqIoDfj0aQV5buVZI2loMomtU9KY5SFIsPV+JuUpy7/+VE01ZQM5FdY8wiYCQiVZYju9XWz5LxMNoz+gT7pwlLCsC4N+R8aoBk404aF1gum8CgYAJ7VTq7Zj4TFV7Soa/T1eEk9y8a+kdoYk3BASpCHJ29M5R2KEA7YV9wrBklHTz8VzSTFTbKHEQ5W5csAhoL5FoqoHzFFi3Qx7MHESQb9qHyolHEMNx6QdsHUn7rlEnaTTyrXh3ifQtD6C0yTmFXUISCW9wKApOrnyKJ9nI0HcuZQKBgQCMtoV6e9VGX4AEfpuHvAAnMYQFgeBiYTkBKltQXwozhH63uMMomUmtSG87Sz1TmrXadjAhy8gsG6I0pWaN7QgBuFnzQ/HOkwTm+qKwAsrZt4zeXNwsH7QXHEJCFnCmqw9QzEoZTrNtHJHpNboBuVnYcoueZEJrP8OnUG3rUjmopwKBgAqB2KYYMUqAOvYcBnEfLDmyZv9BTVNHbR2lKkMYqv5LlvDaBxVfilE02riO4p6BaAdvzXjKeRrGNEKoHNBpOSfYCOM16NjL8hIZB1CaV3WbT5oY+jp7Mzd57d56RZOE+ERK2uz/7JX9VSsM/LbH9pJibd4e8mikDS9ntciqOH/3-----END RSA TESTING KEY-----`, "TESTING KEY", "PRIVATE KEY")))testRSA2048, _ := x509.ParsePKCS1PrivateKey(block.Bytes)fmt.Println("Private key bit size:", testRSA2048.N.BitLen())} funcGenerateMultiPrimeKeydeprecated
GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bitsize and the given random source.
Table 1 in "On the Security of Multi-prime RSA" suggests maximum numbers ofprimes for a given bit size.
Although the public keys are compatible (actually, indistinguishable) fromthe 2-prime case, the private keys are not. Thus it may not be possible toexport multi-prime private keys in certain formats or to subsequently importthem into other code.
This package does not implement CRT optimizations for multi-prime RSA, so thekeys with more than two primes will have worse performance.
Deprecated: The use of this function with a number of primes different fromtwo is not recommended for the above security, compatibility, and performancereasons. UseGenerateKey instead.
func (*PrivateKey)Decrypt¶added ingo1.5
func (priv *PrivateKey) Decrypt(randio.Reader, ciphertext []byte, optscrypto.DecrypterOpts) (plaintext []byte, errerror)
Decrypt decrypts ciphertext with priv. If opts is nil or of type*PKCS1v15DecryptOptions then PKCS #1 v1.5 decryption is performed. Otherwiseopts must have type *OAEPOptions and OAEP decryption is done.
func (*PrivateKey)Equal¶added ingo1.15
func (priv *PrivateKey) Equal(xcrypto.PrivateKey)bool
Equal reports whether priv and x have equivalent values. It ignoresPrecomputed values.
func (*PrivateKey)Precompute¶
func (priv *PrivateKey) Precompute()
Precompute performs some calculations that speed up private key operationsin the future. It is safe to run on non-validated private keys.
func (*PrivateKey)Public¶added ingo1.4
func (priv *PrivateKey) Public()crypto.PublicKey
Public returns the public key corresponding to priv.
func (*PrivateKey)Sign¶added ingo1.4
func (priv *PrivateKey) Sign(randio.Reader, digest []byte, optscrypto.SignerOpts) ([]byte,error)
Sign signs digest with priv, reading randomness from rand. If opts is a*PSSOptions then the PSS algorithm will be used, otherwise PKCS #1 v1.5 willbe used. digest must be the result of hashing the input message usingopts.HashFunc().
This method implementscrypto.Signer, which is an interface to support keyswhere the private part is kept in, for example, a hardware module. Commonuses should use the Sign* functions in this package directly.
func (*PrivateKey)Validate¶
func (priv *PrivateKey) Validate()error
Validate performs basic sanity checks on the key.It returns nil if the key is valid, or else an error describing a problem.
It runs faster on valid keys if run afterPrivateKey.Precompute.
typePublicKey¶
A PublicKey represents the public part of an RSA key.
The values of N and E are not considered confidential, and may leak throughside channels, or could be mathematically derived from other public values.