CryptoSys PKI  23.0.0
Public Types | Static Public Member Functions | List of all members
dipki::Rsa Class Reference

RSA Encryption and Public Key Functions. More...

Public Types

enum class  AdvOpts
 Advanced options. More...
 
enum class  EME
 Encoding method for encryption. More...
 
enum class  Format
 Format for saved RSA key file. More...
 
enum class  HashAlg
 Hash function for OAEP encoding. More...
 
enum class  PbeScheme
 Password-based encryption scheme to encrypt the private key file. More...
 
enum class  PublicExponent
 Choice for public exponent (e). More...
 
enum  XmlOptions : unsigned int
 Options when converting between internal RSA key and XML. More...
 

Static Public Member Functions

static bvec_t DecodeMsgForEncryption (const bvec_t &data, EME method=EME::PKCSv1_5)
 Decode a message for encryption. More...
 
static bvec_t DecodeMsgForSignature (const bvec_t &data, bool getFullDigestInfo=false)
 Extract digest (or digestinfo) from an EMSA-PKCS1-v1_5-encoded block. More...
 
static bvec_t Decrypt (const bvec_t &data, const std::string &privateKeyFileOrString, const std::string &password="", EME method=EME::PKCSv1_5, HashAlg hashAlg=HashAlg::Sha1, AdvOpts advOpts=AdvOpts::Default)
 Decrypt a message encrypted using an RSA encryption scheme. More...
 
static bvec_t EncodeMsgForEncryption (int blockBytes, const bvec_t &message, EME method=EME::PKCSv1_5)
 Encode a message for encryption. More...
 
static bvec_t EncodeMsgForSignature (int blockBytes, const bvec_t &message, HashAlg hashAlg=HashAlg::Sha1, bool digestOnly=false)
 Encode a message for signature. More...
 
static bvec_t Encrypt (const bvec_t &data, const std::string &publicKeyFileOrString, EME method=EME::PKCSv1_5, HashAlg hashAlg=HashAlg::Sha1, AdvOpts advOpts=AdvOpts::Default, const std::string &params="")
 Encrypt a short message using RSA encryption. More...
 
static std::string FromXMLString (const std::string &xmlstr, XmlOptions opts=XmlOptions::None)
 Return an RSA key string in internal format from an XML string. More...
 
static int GetPrivateKeyFromPFX (const std::string &outputFile, const std::string &pfxFile)
 Extract an encrypted private key from a PKCS-12 PKCS8ShroudedKeyBag, saving the output directly as a new file. More...
 
static int KeyBits (const std::string &keyStr)
 Get number of significant bits in RSA key modulus. More...
 
static int KeyBytes (const std::string &keyStr)
 Get number of bytes (octets) in RSA key modulus. More...
 
static uint32_t KeyHashCode (const std::string &intKeyString)
 Compute the hash code of an "internal" RSA public or private key string. More...
 
static bool KeyIsPrivate (const std::string &keyStr)
 Determine if keystring is a private key. More...
 
static bool KeyMatch (const std::string &priKeyStr, const std::string &pubKeyStr)
 Determine if a pair of "internal" RSA private and public key strings are matched. More...
 
static std::string KeyValue (const std::string &keyStr, const std::string &fieldName)
 Extract a base64-encoded RSA key value from internal key string. More...
 
static int MakeKeys (const std::string &publicKeyFile, const std::string &privateKeyFile, const std::string &password, int nbits, PublicExponent exponent=PublicExponent::Exp_EQ_65537, PbeScheme pbes=PbeScheme::Default, const std::string &paramString="", Format fileFormat=Format::Binary, bool showProgress=false)
 Generate an RSA public/private key pair and save as two key files. More...
 
static std::string PublicKeyFromPrivate (const std::string &keyStr)
 Get internal RSA public key string from an internal RSA private key string. More...
 
static bvec_t RawPrivate (const bvec_t &data, const std::string &keyStr)
 Transforms (that is, encrypts or decrypts) raw data using an RSA private key. More...
 
static bvec_t RawPublic (const bvec_t &data, const std::string &keyStr)
 Transforms (that is, encrypts or decrypts) raw data using an RSA public key. More...
 
static std::string ReadPrivateKey (const std::string &keyFileOrString, const std::string &password="")
 Read from a file or string containing a private key into an "internal" key string. More...
 
static std::string ReadPublicKey (const std::string &keyFileOrString)
 Read from a file or string containing a public key into an "internal" key string. More...
 
static int SaveEncKey (const std::string &outputFile, const std::string &keyStr, const std::string &password, PbeScheme pbes=PbeScheme::Default, const std::string &paramString="", Format fileFormat=Format::Binary)
 Save an internal RSA key string to an encrypted key file. More...
 
static int SaveKey (const std::string &outputFile, const std::string &keyStr, Format fileFormat=Format::Binary)
 Save an internal RSA key string to a key file. More...
 
static std::string ToXMLString (const std::string &keyStr, XmlOptions opts=XmlOptions::None, const std::string &prefix="")
 Return an XML string representation of an RSA internal key string. More...
 

Detailed Description

RSA Encryption and Public Key Functions.

Member Enumeration Documentation

◆ AdvOpts

enum dipki::Rsa::AdvOpts
strong

Advanced options.

Enumerator
Default 

Default options.

Mgf1_Sha1 

Force the MGF hash function to be SHA-1 (OAEP only, default = same as encoding set by Rsa::HashAlg)

◆ EME

enum dipki::Rsa::EME
strong

Encoding method for encryption.

Remarks
See PKCS#1 v2.2 [RFC8017]
Enumerator
PKCSv1_5 

EME-PKCS1-v1_5 encoding method (default)

OAEP 

EME-OAEP encoding method

◆ Format

enum dipki::Rsa::Format
strong

Format for saved RSA key file.

Enumerator
Binary 

Binary DER-encoded (default)

PEM 

PEM-encoded.

SSL 

PEM-encoded compatible with OpenSSL.

◆ HashAlg

enum dipki::Rsa::HashAlg
strong

Hash function for OAEP encoding.

Enumerator
Sha1 

SHA-1 (default)

Sha224 

SHA-224.

Sha256 

SHA-256.

Sha384 

SHA-384.

Sha512 

SHA-512.

◆ PbeScheme

enum dipki::Rsa::PbeScheme
strong

Password-based encryption scheme to encrypt the private key file.

Enumerator
Default 

Default option: pbeWithSHAAnd3-KeyTripleDES-CBC from PKCS#12.

Pbkdf2_Desede3 

PBKDF2 using des-EDE3-CBC

Pbkdf2_Aes128 

PBKDF2 using aes128-CBC

Pbkdf2_Aes192 

PBKDF2 using aes192-CBC

Pbkdf2_Aes256 

PBKDF2 using aes256-CBC

◆ PublicExponent

Choice for public exponent (e).

Remarks
Fermat Number F(x) = 2^(2^x) + 1. F0 to F4 are prime.
Enumerator
Exp_EQ_3 

Set exponent equal to 3 (F0)

Exp_EQ_5 

Set exponent equal to 5 (F1)

Exp_EQ_17 

Set exponent equal to 17 (F2)

Exp_EQ_257 

Set exponent equal to 257 (F3)

Exp_EQ_65537 

Set exponent equal to 65537 (F4) (default)

◆ XmlOptions

enum dipki::Rsa::XmlOptions : unsigned int

Options when converting between internal RSA key and XML.

Enumerator
None 

No options.

ForceRSAKeyValue 

Create XML in .NET-compatible RSAKeyValue format (ToXML only)

ExcludePrivateParams 

Exclude private key even if present.

RequirePrivate 

Require private key to exist in the XML input or fail (FromXML only)

HexBinaryFormat 

Create XML in non-standard hex format (ToXML only)

Member Function Documentation

◆ DecodeMsgForEncryption()

static bvec_t dipki::Rsa::DecodeMsgForEncryption ( const bvec_t data,
EME  method = EME::PKCSv1_5 
)
static

Decode a message for encryption.

Parameters
dataEncoded block.
methodEncoding method to use [default = EME-PKCS1-v1_5]
Returns
Decoded message.

◆ DecodeMsgForSignature()

static bvec_t dipki::Rsa::DecodeMsgForSignature ( const bvec_t data,
bool  getFullDigestInfo = false 
)
static

Extract digest (or digestinfo) from an EMSA-PKCS1-v1_5-encoded block.

Parameters
dataEncoded message for signature.
getFullDigestInfoIf true, extract the full DigestInfo; otherwise just extract the message digest itself.
Returns
Decoded data.

◆ Decrypt()

static bvec_t dipki::Rsa::Decrypt ( const bvec_t data,
const std::string &  privateKeyFileOrString,
const std::string &  password = "",
EME  method = EME::PKCSv1_5,
HashAlg  hashAlg = HashAlg::Sha1,
AdvOpts  advOpts = AdvOpts::Default 
)
static

Decrypt a message encrypted using an RSA encryption scheme.

Parameters
dataData to be decrypted (must be exactly the same length as the key modulus size).
privateKeyFileOrStringName of the private key file, or a string containing the key in PEM format, or a valid internal private key string.
passwordPassword for encrypted private key, or "" if password is not required.
methodEncoding method to use [default=EME-PKCS1-v1_5]
hashAlgHash function for EME-OAEP encoding, otherwise ignored [default=SHA-1].
advOptsAdvanced options for EME-OEAP only.
Returns
Encrypted data.

◆ EncodeMsgForEncryption()

static bvec_t dipki::Rsa::EncodeMsgForEncryption ( int  blockBytes,
const bvec_t message,
EME  method = EME::PKCSv1_5 
)
static

Encode a message for encryption.

Parameters
blockBytesNumber of bytes in the output block.
messageMessage to be encoded.
methodEncoding method to use [default = EME-PKCS1-v1_5]
Returns
Encoded message block.
Remarks
This function requires the length of the output block to be specified (use Rsa::KeyBytes to find this).

◆ EncodeMsgForSignature()

static bvec_t dipki::Rsa::EncodeMsgForSignature ( int  blockBytes,
const bvec_t message,
HashAlg  hashAlg = HashAlg::Sha1,
bool  digestOnly = false 
)
static

Encode a message for signature.

Parameters
blockBytesNumber of bytes in the output block.
messageMessage to be encoded.
hashAlgMessage digest algorithm to use [default=SHA-1 – CAUTION!]
digestOnlySet true to pass the message digest value instead of the message itself.
Returns
Encoded message block.
Remarks
Only EMSA-PKCS1-v1_5 is supported by this function. Note we can only ever recover the digest from the encoded block.

◆ Encrypt()

static bvec_t dipki::Rsa::Encrypt ( const bvec_t data,
const std::string &  publicKeyFileOrString,
EME  method = EME::PKCSv1_5,
HashAlg  hashAlg = HashAlg::Sha1,
AdvOpts  advOpts = AdvOpts::Default,
const std::string &  params = "" 
)
static

Encrypt a short message using RSA encryption.

Parameters
dataData to be encrypted (must be at least 11 bytes shorter than the key modulus size).
publicKeyFileOrStringName of the public key file or X.509 certificate, or a string containing the key or certificate in PEM format, or a valid internal public key string.
methodEncoding method to use [default=EME-PKCS1-v1_5]
hashAlgHash function for EME-OAEP encoding, otherwise ignored [default=SHA-1].
advOptsAdvanced options for EME-OEAP only.
paramsFor specialist use.
Returns
Encrypted data.

◆ FromXMLString()

static std::string dipki::Rsa::FromXMLString ( const std::string &  xmlstr,
XmlOptions  opts = XmlOptions::None 
)
static

Return an RSA key string in internal format from an XML string.

Parameters
xmlstrThe XML string to use to reconstruct the RSA key.
optsOption flags
Returns
Key string in internal format.
Exceptions
std::runtime_errorException with error code if XML string is invalid.

◆ GetPrivateKeyFromPFX()

static int dipki::Rsa::GetPrivateKeyFromPFX ( const std::string &  outputFile,
const std::string &  pfxFile 
)
static

Extract an encrypted private key from a PKCS-12 PKCS8ShroudedKeyBag, saving the output directly as a new file.

Parameters
outputFileName of output file to be created.
pfxFileName of PFX (.p12) file.
Returns
If successful, it returns the number of bytes written to the output file (NB not zero).
Remarks
The first pkcs-12-pkcs-8ShroudedKeyBag found in the PFX file will be extracted and saved directly as a BER-encoded EncryptedPrivateKeyInfo file. No decryption or other conversion is carried out.
Exceptions
std::runtime_errorException with error code if pfxFile is invalid or if output file cannot be created.

◆ KeyBits()

static int dipki::Rsa::KeyBits ( const std::string &  keyStr)
static

Get number of significant bits in RSA key modulus.

Parameters
keyStrInternal key string (private or public).
Returns
Number of significant bits in key.

◆ KeyBytes()

static int dipki::Rsa::KeyBytes ( const std::string &  keyStr)
static

Get number of bytes (octets) in RSA key modulus.

Parameters
keyStrInternal key string (private or public).
Returns
Minimum number of bytes required to represent key.

◆ KeyHashCode()

static uint32_t dipki::Rsa::KeyHashCode ( const std::string &  intKeyString)
static

Compute the hash code of an "internal" RSA public or private key string.

Parameters
intKeyStringKey as an internal key string.
Returns
A 32-bit hash code for the key.
Remarks
Should be the same for a matching private and public key.

◆ KeyIsPrivate()

static bool dipki::Rsa::KeyIsPrivate ( const std::string &  keyStr)
static

Determine if keystring is a private key.

Parameters
keyStrInternal key string (private or public).
Returns
true if the key string contains a valid RSA private key, or false if a valid RSA public key.
Exceptions
std::runtime_errorException with error code if internal key string is invalid.

◆ KeyMatch()

static bool dipki::Rsa::KeyMatch ( const std::string &  priKeyStr,
const std::string &  pubKeyStr 
)
static

Determine if a pair of "internal" RSA private and public key strings are matched.

Parameters
priKeyStrInternal RSA private key string.
pubKeyStrInternal RSA public key string.
Returns
true if the keystrings are valid and matched, or false if the keystrings are valid but not matched.
Exceptions
std::runtime_errorException with error code if an internal key string is invalid.

◆ KeyValue()

static std::string dipki::Rsa::KeyValue ( const std::string &  keyStr,
const std::string &  fieldName 
)
static

Extract a base64-encoded RSA key value from internal key string.

Parameters
keyStrInternal key string (private or public).
fieldNameName of field to be extracted: Modulus or Exponent.
Returns
Value encoded in base64.

◆ MakeKeys()

static int dipki::Rsa::MakeKeys ( const std::string &  publicKeyFile,
const std::string &  privateKeyFile,
const std::string &  password,
int  nbits,
PublicExponent  exponent = PublicExponent::Exp_EQ_65537,
PbeScheme  pbes = PbeScheme::Default,
const std::string &  paramString = "",
Format  fileFormat = Format::Binary,
bool  showProgress = false 
)
static

Generate an RSA public/private key pair and save as two key files.

Parameters
publicKeyFileOutput filename for public key.
privateKeyFileOutput filename for (encrypted) private key.
passwordPassword for encrypted private key (required).
nbitsRequired key modulus size in bits (min 96).
exponentExponent [default=65537=F4]
pbesEncryption scheme to encrypt private key [default=pbeWithSHAAnd3-KeyTripleDES-CBC from PKCS#12]
paramStringOptional parameters. A set of attribute name=value pairs separated by a semicolon ";" (see remarks).
fileFormatFormat to save file [default = DER binary].
showProgressIndicate progress in console.
Returns
Zero if successful.
Remarks
Valid name-value pair parameters for paramString are:
Parameter Result
count=integer To set the iteration count used in the PBKDF2 method, e.g. "count=5000;" [default=2048].
prf=hmac-name To change the HMAC algorithm used in the PBKDF2 method, e.g. "prf=hmacWithSHA256;" [default=hmacWithSHA1].
rngseed=string To add some user-supplied entropy for the key generation process, e.g. "rngseed=pqrrr1234xyz;".
Valid values for hmac-name are {hmacWithSHA1,hmacWithSHA224,hmacWithSHA256,hmacWithSHA384,hmacWithSHA512}.

◆ PublicKeyFromPrivate()

static std::string dipki::Rsa::PublicKeyFromPrivate ( const std::string &  keyStr)
static

Get internal RSA public key string from an internal RSA private key string.

Parameters
keyStrPrivate key in "internal" format.
Returns
Internal representation of the public key.
Exceptions
std::runtime_errorException with error code if key string is invalid.

◆ RawPrivate()

static bvec_t dipki::Rsa::RawPrivate ( const bvec_t data,
const std::string &  keyStr 
)
static

Transforms (that is, encrypts or decrypts) raw data using an RSA private key.

Parameters
dataData to be transformed (must be same byte length as key modulus).
keyStrPrivate key in internal string format.
Returns
Transformed data.

◆ RawPublic()

static bvec_t dipki::Rsa::RawPublic ( const bvec_t data,
const std::string &  keyStr 
)
static

Transforms (that is, encrypts or decrypts) raw data using an RSA public key.

Parameters
dataData to be transformed (must be same byte length as key modulus).
keyStrPublic key in internal string format.
Returns
Transformed data.

◆ ReadPrivateKey()

static std::string dipki::Rsa::ReadPrivateKey ( const std::string &  keyFileOrString,
const std::string &  password = "" 
)
static

Read from a file or string containing a private key into an "internal" key string.

Parameters
keyFileOrStringName of private key file or a PEM String containing the key.
passwordPassword for private key, if encrypted.
Returns
The key in ephemeral "internal" representation.
Remarks
The output string is an ephemeral internal key string valid only for the current session.

◆ ReadPublicKey()

static std::string dipki::Rsa::ReadPublicKey ( const std::string &  keyFileOrString)
static

Read from a file or string containing a public key into an "internal" key string.

Parameters
keyFileOrStringName of X.509 certificate or public key file or a PEM String containing the key.
Returns
The key in ephemeral "internal" representation.
Remarks
The output string is an ephemeral internal key string valid only for the current session.

◆ SaveEncKey()

static int dipki::Rsa::SaveEncKey ( const std::string &  outputFile,
const std::string &  keyStr,
const std::string &  password,
PbeScheme  pbes = PbeScheme::Default,
const std::string &  paramString = "",
Format  fileFormat = Format::Binary 
)
static

Save an internal RSA key string to an encrypted key file.

Parameters
outputFileName of output file to be created.
keyStrThe private RSA key as an internal key string.
passwordPassword to be used for the encrypted key file.
pbesEncryption scheme to encrypt private key [default=pbeWithSHAAnd3-KeyTripleDES-CBC from PKCS#12]
paramStringOptional parameters. A set of attribute name=value pairs separated by a semicolon ";" (see remarks).
fileFormatFile format [default = binary].
Returns
Zero if successful.
Remarks
Valid name-value pair parameters for paramString are:
Parameter Result
count=integer To set the iteration count used in the PBKDF2 method, e.g. "count=5000;" [default=2048].
prf=hmac-name To change the HMAC algorithm used in the PBKDF2 method, e.g. "prf=hmacWithSHA256;" [default=hmacWithSHA1].
Valid values for hmac-name are {hmacWithSHA1,hmacWithSHA224,hmacWithSHA256,hmacWithSHA384,hmacWithSHA512}.
Exceptions
std::runtime_errorException with error code if keyStr is invalid or if output file cannot be created.

◆ SaveKey()

static int dipki::Rsa::SaveKey ( const std::string &  outputFile,
const std::string &  keyStr,
Format  fileFormat = Format::Binary 
)
static

Save an internal RSA key string to a key file.

Parameters
outputFileName of output file to be created.
keyStrKey string (public or private) in internal format.
fileFormatFile format [default = binary].
Returns
Zero if successful.
Remarks
If the key is a private key it will be saved in unencrypted form.
Exceptions
std::runtime_errorException with error code if keyStr is invalid or if output file cannot be created.

◆ ToXMLString()

static std::string dipki::Rsa::ToXMLString ( const std::string &  keyStr,
XmlOptions  opts = XmlOptions::None,
const std::string &  prefix = "" 
)
static

Return an XML string representation of an RSA internal key string.

Parameters
keyStrInternal key string (private or public).
optsOption flags
prefixPrefix to add to elements, e.g. "ds" or "ds:".
Returns
XML string.
Exceptions
std::runtime_errorException with error code if internal key string is invalid.
Copyright © 2004-24 D.I. Management Services Pty Limited t/a CryptoSys ABN 78 083 210 584 Australia. All rights reserved. <www.di-mgt.com.au> <www.cryptosys.net>. Generated on Mon Sep 23 2024 15:37:33 by Doxygen 1.9.1.