Class Rsa
- All Implemented Interfaces:
AutoCloseable
Encrypt, decrypt, sign, verify, and generate RSA keys.
Use Chilkat.Rsa when an application needs direct RSA
cryptographic operations. It can encrypt data with a public key, decrypt with
a private key, create RSA signatures, verify signatures, sign precomputed
hashes, verify signed hashes, and generate RSA key pairs. It also works with
keys supplied directly as PrivateKey or PublicKey
objects, or indirectly through certificates.
RSA encryption
Encrypt data with a public key for workflows where only the matching private key should be able to decrypt the result.
RSA decryption
Decrypt RSA-encrypted data using a private key, including keys loaded directly or accessed through a certificate.
Sign and verify data
Create and verify RSA signatures over data using the hash algorithm and padding mode required by the application or protocol.
Sign precomputed hashes
Sign or verify already-computed message digests when the hashing step is performed separately or by another component.
Generate RSA keys
Generate RSA key pairs for applications that need new public/private key material.
Certificate-backed keys
Use RSA keys associated with certificates, including non-exportable private keys in smart cards, USB tokens, Windows stores, or Apple Keychain.
Common pattern:
Load or generate the RSA key material, configure the padding, hash, charset,
and encoding options needed by the protocol, then call the method matching
the operation: encrypt, decrypt, sign, verify, sign-hash, or verify-hash.
Use Chilkat.Rsa for direct RSA operations; use higher-level
classes such as Crypt2, Jws, Jwt, or
Mime when the RSA operation is part of a larger format or
protocol.
For an extended overview, see Rsa Class Overview.
</section>
Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when
done; an unclosed instance is freed when it becomes unreachable.
- See Also:
- Online reference
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidRSA decrypts the contents ofbd.decryptStringENC(String str, boolean usePrivateKey)Decryptsstrwith the RSA algorithm.voidRSA encrypts the contents ofbd.encryptStringENC(String str, boolean bUsePrivateKey)Encryptsstrwith the RSA algorithm.voidgenKey(int numBits, PrivateKey privKey)Generates a new RSA key and stores it inprivKey.This property specifies the character encoding used to represent text as bytes for encryption, decryption, signing, and signature validation.This property defines the encoding for methods ending inENC, such as EncryptStringENC.booleanWhen creating RSA signatures, this property determines the endianness: set it totruefor little-endian signatures andfalsefor big-endian signatures.booleanIftrue, skips unpadding when decrypting.intThe bit length, such as 2048, of the imported or generated RSA key.Selects the hash algorithm for use within OAEP padding for encryption.The optional RSA encryption OAEP label is a hex representation of the label bytes used for encrypting with OAEP padding.Selects the MGF (mask generation) hash algorithm for use within OAEP padding for encryption.booleanThis property controls padding for both signing and encryption.intWhen using RSASSA-PSS padding for signatures, you can choose the PSS salt length.This is a catch-all property to be used for uncommon needs.voidsetCharset(String value)Sets theCharsetproperty; seegetCharset().voidsetEncodingMode(String value)Sets theEncodingModeproperty; seegetEncodingMode().voidsetLittleEndian(boolean value)Sets theLittleEndianproperty; seegetLittleEndian().voidsetNoUnpad(boolean value)Sets theNoUnpadproperty; seegetNoUnpad().voidsetOaepHash(String value)Sets theOaepHashproperty; seegetOaepHash().voidsetOaepLabel(String value)Sets theOaepLabelproperty; seegetOaepLabel().voidsetOaepMgfHash(String value)Sets theOaepMgfHashproperty; seegetOaepMgfHash().voidsetPkcsPadding(boolean value)Sets thePkcsPaddingproperty; seegetPkcsPadding().voidsetPssSaltLen(int value)Sets thePssSaltLenproperty; seegetPssSaltLen().voidsetUncommonOptions(String value)Sets theUncommonOptionsproperty; seegetUncommonOptions().voidsetX509Cert(Cert cert, boolean usePrivateKey)Provides the private or public key indirectly through a certificate.voidGenerates an RSA digital signature by first hashing the contents ofbdDatawith the hash algorithm specified byhashAlgorithm, which can besha256,sha384,sha512, orsha1.signHashENC(String encodedHash, String hashAlg)This function creates an RSA digital signature for the hash provided inencodedHash, which should be encoded according to the EncodingMode setting (e.g., base64 if EncodingMode =base64).voidThis is legacy low-level raw RSA that duplicates the (now deprecated)OpenSSLrsautlutility.signStringENC(String strToBeHashed, String hashAlgorithm)Generates an RSA digital signature by first hashingstrToBeHashedwith the hash algorithm specified byhashAlgorithm, which can besha256,sha384,sha512, orsha1.Imports a .snk file to an XML document that can be imported via the ImportPrivateKey method.voidusePrivateKey(PrivateKey privKey)Imports a private key fromprivKeyto use for signing or decrypting.voidusePublicKey(PublicKey pubKey)Imports a public key frompubKeyto use for encrypting or signature verification.voidVerifies the RSA signature passed inbdSigagainst the original data passed inbdData.voidverifyHashENC(String encodedHash, String hashAlg, String encodedSig)Validates an RSA signature provided inencodedSigagainst the hash of the original data inencodedHash.voidverifyRawBd(BinData bd)This is legacy low-level raw RSA that duplicates the (now deprecated)OpenSSLrsautlutility.voidverifyStringENC(String originalString, String hashAlgorithm, String encodedSig)Verifies the encoded RSA signature passed inencodedSigagainst the original data passed inoriginalString.Methods inherited from class com.chilkatsoft.chilkat2.ChilkatObject
close, getDebugLogFilePath, getLastErrorHtml, getLastErrorText, getLastErrorXml, getLastMethodSuccess, getVerboseLogging, getVersion, isClosed, setDebugLogFilePath, setLastMethodSuccess, setVerboseLogging, toString
-
Constructor Details
-
Rsa
public Rsa()Creates a newRsaobject.
-
-
Method Details
-
getCharset
This property specifies the character encoding used to represent text as bytes for encryption, decryption, signing, and signature validation. By default, it uses the computer'sANSIcharset, such as Windows-1252 for locales like the United States, United Kingdom, Western Europe, Australia, and New Zealand.Most applications are advised to set this property to
UTF-8. Chilkat plans to change its default to UTF-8 in a future major version to align with current standards. The current default of ANSI stems from a time when UTF-8 was not widely adopted.- Returns:
- the value of the
Charsetproperty
-
setCharset
Sets theCharsetproperty; seegetCharset().- Parameters:
value- the new value (notnull)
-
getEncodingMode
This property defines the encoding for methods ending inENC, such as EncryptStringENC. Valid modes includebase64,hex,hex_lower, and more. The encoding mode applies to signatures, encrypted data, and hashes used in or returned by a method.- Returns:
- the value of the
EncodingModeproperty
-
setEncodingMode
Sets theEncodingModeproperty; seegetEncodingMode().- Parameters:
value- the new value (notnull)
-
getLittleEndian
public boolean getLittleEndian()When creating RSA signatures, this property determines the endianness: set it totruefor little-endian signatures andfalsefor big-endian signatures.- Returns:
- the value of the
LittleEndianproperty
-
setLittleEndian
public void setLittleEndian(boolean value)Sets theLittleEndianproperty; seegetLittleEndian().- Parameters:
value- the new value
-
getNoUnpad
public boolean getNoUnpad()Iftrue, skips unpadding when decrypting. The default isfalse. This property value is typically left unchanged.- Returns:
- the value of the
NoUnpadproperty
-
setNoUnpad
public void setNoUnpad(boolean value)Sets theNoUnpadproperty; seegetNoUnpad().- Parameters:
value- the new value
-
getNumBits
public int getNumBits()The bit length, such as 2048, of the imported or generated RSA key.- Returns:
- the value of the
NumBitsproperty (read-only)
-
getOaepHash
Selects the hash algorithm for use within OAEP padding for encryption. The valid choices aresha256,sha384,sha512, orsha1.The default is SHA1. You'll likely want to change this to to SHA256. The next major version of Chilkat (11.0.0) will change the default to SHA256.
- Returns:
- the value of the
OaepHashproperty
-
setOaepHash
Sets theOaepHashproperty; seegetOaepHash().- Parameters:
value- the new value (notnull)
-
getOaepLabel
The optional RSA encryption OAEP label is a hex representation of the label bytes used for encrypting with OAEP padding. Typically, this is left empty (0 bytes) unless there's a specific requirement to set it.- Returns:
- the value of the
OaepLabelproperty
-
setOaepLabel
Sets theOaepLabelproperty; seegetOaepLabel().- Parameters:
value- the new value (notnull)
-
getOaepMgfHash
Selects the MGF (mask generation) hash algorithm for use within OAEP padding for encryption. The valid choices aresha256,sha384,sha512, orsha1.Note: This property should typically be set to the same value as the OaepHash property. Many software implementations are not able to handle cases where the MGF hash is different than the OAEP hash.
The default is SHA1. You'll likely want to change this to to SHA256. The next major version of Chilkat (11.0.0) will change the default to SHA256.
- Returns:
- the value of the
OaepMgfHashproperty
-
setOaepMgfHash
Sets theOaepMgfHashproperty; seegetOaepMgfHash().- Parameters:
value- the new value (notnull)
-
getPkcsPadding
public boolean getPkcsPadding()This property controls padding for both signing and encryption. The default value is true, which is to use PKCS#1 v1.5 padding. If set to false, then PSS padding is used for signatures and OAEP padding is used for encryption.This property replaces the deprecated
OaepPaddingproperty. Until the OaepPadding property is removed, setting this property will automatically set OaepPadding to the opposite, and vice-versa. This is to maintain backward compatibility until applications can switch to using this new property.- Returns:
- the value of the
PkcsPaddingproperty
-
setPkcsPadding
public void setPkcsPadding(boolean value)Sets thePkcsPaddingproperty; seegetPkcsPadding().- Parameters:
value- the new value
-
getPssSaltLen
public int getPssSaltLen()When using RSASSA-PSS padding for signatures, you can choose the PSS salt length. By default, the salt length is set to -1, which uses the length of the hash function. For instance, with the SHA256 hash function, the salt length will be 32 bytes. You can specify a different salt length, like 20 bytes, if needed, but it's generally recommended to keep the default setting.- Returns:
- the value of the
PssSaltLenproperty
-
setPssSaltLen
public void setPssSaltLen(int value)Sets thePssSaltLenproperty; seegetPssSaltLen().- Parameters:
value- the new value
-
getUncommonOptions
This is a catch-all property to be used for uncommon needs. This property defaults to the empty string and should typically remain empty.- Returns:
- the value of the
UncommonOptionsproperty
-
setUncommonOptions
Sets theUncommonOptionsproperty; seegetUncommonOptions().- Parameters:
value- the new value (notnull)
-
decryptBd
RSA decrypts the contents ofbd.usePrivateKeyshould be set totrueif the private key is to be used for decrypting. Otherwise it should be set tofalseif (in rare cases) the public key is to be used for decrypting.Important: If trying to match OpenSSL results, set the LittleEndian property =
false.- Parameters:
bd- thebdargument (notnull)usePrivateKey- theusePrivateKeyargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
decryptStringENC
Decryptsstrwith the RSA algorithm.stris the encoded form of the encrypted binary data. The EncodingMode property definesstr's encoding. The Charset property specifies the byte representation for interpreting the decrypted text. SetusePrivateKeytotrueto use the private key for decryption; otherwise, setusePrivateKeytofalseto use the public key (used rarely). Returns the decrypted string.Important: If trying to match OpenSSL results, set the LittleEndian property =
false.- Parameters:
str- thestrargument (notnull)usePrivateKey- theusePrivateKeyargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
encryptBd
RSA encrypts the contents ofbd. SetusePrivateKeytofalseto use the public key for encrypting; otherwise, set it totrueto use the private key (in rare cases).Important: If trying to match OpenSSL results, set the LittleEndian property =
false.Note: The public key's role is to make encryption accessible to anyone while ensuring that only the private key holder can decrypt the messages. The public key is designed to be widely distributed so anyone can use it to encrypt messages intended for the owner of the private key.
- Parameters:
bd- thebdargument (notnull)usePrivateKey- theusePrivateKeyargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
encryptStringENC
Encryptsstrwith the RSA algorithm. The Charset property specifies the byte representation of the string that is encrypted. SetbUsePrivateKeytofalseto use the public key for encrypting; otherwise, set it totrueto use the private key (in rare cases). The encrypted data is returned in the format specified by the EncodingMode property.Important: If trying to match OpenSSL results, set the LittleEndian property =
false.Note: The public key's role is to make encryption accessible to anyone while ensuring that only the private key holder can decrypt the messages. The public key is designed to be widely distributed so anyone can use it to encrypt messages intended for the owner of the private key.
- Parameters:
str- thestrargument (notnull)bUsePrivateKey- thebUsePrivateKeyargument- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
genKey
Generates a new RSA key and stores it inprivKey.numBitsspecifies the key length, which can range from 512 to 8192 bits. Common key lengths are 1024, 2048, or 4096 bits.Note: Generating an 8192-bit key may take a significant amount of time. The method does not support event callbacks or progress monitoring and will block the thread until completion.
- Parameters:
numBits- thenumBitsargumentprivKey- theprivKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
setX509Cert
Provides the private or public key indirectly through a certificate. This method is used when the private key is inaccessible, such as when stored on a smart card, USB token, in the Windows registry (marked as non-exportable), or in the Apple Keychain.- Parameters:
cert- thecertargument (notnull)usePrivateKey- theusePrivateKeyargument- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
signBd
Generates an RSA digital signature by first hashing the contents ofbdDatawith the hash algorithm specified byhashAlgorithm, which can besha256,sha384,sha512, orsha1. The resulting signature is written tobdSig.Note: It is important to be aware of endianness. Make sure the LittleEndian property is set according to your specific needs.
- Parameters:
bdData- thebdDataargument (notnull)hashAlgorithm- thehashAlgorithmargument (notnull)bdSig- thebdSigargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
signHashENC
This function creates an RSA digital signature for the hash provided inencodedHash, which should be encoded according to the EncodingMode setting (e.g., base64 if EncodingMode =base64).hashAlgspecifies the hash algorithm and can besha256,sha384,sha512, orsha1. The function returns the signature encoded as specified by EncodingMode.- Parameters:
encodedHash- theencodedHashargument (notnull)hashAlg- thehashAlgargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
signRawBd
This is legacy low-level raw RSA that duplicates the (now deprecated)OpenSSLrsautlutility. It directly signs raw data rather than signing a hash of the data. PKCS#1 v1.5 padding is always used. The data to be signed is passed inbd, and on return the content ofbdis replaced with the RSA signed data.Note: It is possible to validate and recover the original data by calling
VerifyRawBd.- Parameters:
bd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
signStringENC
Generates an RSA digital signature by first hashingstrToBeHashedwith the hash algorithm specified byhashAlgorithm, which can besha256,sha384,sha512, orsha1. Returns the signature encoded based on the EncodingMode property.Note: It is important to be aware of endianness. Make sure the LittleEndian property is set according to your specific needs.
Note: It is recommended to set the Charset property equal to
utf-8before signing strings.- Parameters:
strToBeHashed- thestrToBeHashedargument (notnull)hashAlgorithm- thehashAlgorithmargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
snkToXml
Imports a .snk file to an XML document that can be imported via the ImportPrivateKey method.- Parameters:
filename- thefilenameargument (notnull)- Returns:
- the result (never
null) - Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
usePrivateKey
Imports a private key fromprivKeyto use for signing or decrypting.- Parameters:
privKey- theprivKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
usePublicKey
Imports a public key frompubKeyto use for encrypting or signature verification.- Parameters:
pubKey- thepubKeyargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
verifyBd
Verifies the RSA signature passed inbdSigagainst the original data passed inbdData. The original data passed inbdDatais hashed using the hash algorithm passed inhashAlgorithm(such assha256,sha384,sha512, orsha1). Returnstrueif the signature is validated, andfalseif not.Note: Knowing the exact hash algorithm used to create the signature is not required. If the signature is not validated using the hash algorithm specified in
hashAlgorithm, Chilkat will automatically try validating using the other supported algorithms and return success if any validate.- Parameters:
bdData- thebdDataargument (notnull)hashAlgorithm- thehashAlgorithmargument (notnull)bdSig- thebdSigargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
verifyHashENC
Validates an RSA signature provided inencodedSigagainst the hash of the original data inencodedHash. Returnstrueif validation is successful, otherwise returnsfalse.hashAlgspecifies the hash algorithm used forencodedHash, such assha256,sha384,sha512, orsha1. Ensure the hash's size (e.g., 32 bytes for sha256, 48 bytes for sha384, 64 bytes for sha512, 20 bytes for sha1) matches that ofencodedHash.Both
encodedHashandencodedSigshould be encoded according to the EncodingMode property (e.g., base64 if EncodingMode =base64)- Parameters:
encodedHash- theencodedHashargument (notnull)hashAlg- thehashAlgargument (notnull)encodedSig- theencodedSigargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
verifyRawBd
This is legacy low-level raw RSA that duplicates the (now deprecated)OpenSSLrsautlutility. It validates signed raw data and recovers the original data. The RSA signature to be verified is passed inbd, and on return the content ofbdis replaced with the original data.- Parameters:
bd- thebdargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-
verifyStringENC
Verifies the encoded RSA signature passed inencodedSigagainst the original data passed inoriginalString. The original data passed inoriginalStringis hashed using the hash algorithm passed inhashAlgorithm(such assha256,sha384,sha512, orsha1). Returnstrueif the signature is validated, andfalseif not.The signature passed in
encodedSigshould be encoded according to the EncodingMode property (e.g., base64 if EncodingMode =base64)Note: Knowing the exact hash algorithm used to create the signature is not required. If the signature is not validated using the hash algorithm specified in
hashAlgorithm, Chilkat will automatically try validating using the other supported algorithms and return success if any validate.- Parameters:
originalString- theoriginalStringargument (notnull)hashAlgorithm- thehashAlgorithmargument (notnull)encodedSig- theencodedSigargument (notnull)- Throws:
ChilkatException- if the operation fails;ChilkatException.getLastErrorText()says why
-