Using asymmetric block ciphers - ivan-zaera/cipher GitHub Wiki
To use an asymmetric block cipher for encryption with the public you can use the following code:
var modulus = getRSAModulus();
var publicExponent = getRSAPublicExponent();
var pubk = new RSAPublicKey(modulus, publicExponent);
var pubpar = () => new PublicKeyParameter<RSAPublicKey>(pubk);
var cipher = new AsymmetricBlockCipher("RSA")
..init( true, pubpar )
;
var plainText = inputPlainText();
var cipherText = cipher.process( plainText );
outputCipherText( cipherText );
For decryption, the code is similar but we need to use the other key:
var modulus = getRSAModulus();
var privateExponent = getRSAPrivateExponent();
var p = getRSAPrimeFactorP();
var q = getRSAPrimeFactorQ();
var privk = new RSAPrivateKey(modulus, privateExponent, p, q);
var privpar = () => new PrivateKeyParameter<RSAPrivateKey>(privk);
var cipher = new AsymmetricBlockCipher("RSA")
..init( false, privpar )
;
var cipherText = inputCipherText();
var plainText = cipher.process( cipherText );
outputPlainText( plainText );
In general, you construct the AsymmetricBlockCipher with the factory constructor which receives the standard algorithm name
and then init() the cipher with its corresponding CipherParameters. See Algorithm nomenclature for documentation on
standard algorithm names.
The type of CipherParameters to be used depends on the algorithm. For the example (RSA) it consists of the public or secret
key but, for other algorithms, it can change. See the Table of provided algorithms to get information on which
CipherParameters to use for the algorithm of your choice.
To encrypt you make a call to process() with the plain text and the cipher text buffer is returned. Alternatively, if you want
more performance, you can use the processBlock() method which doesn't create the output buffer. Keep in mind that the buffers
must be of the corresponding input/ouput block size (you can get the block sizes programmatically by calling inputBlockSize
and ouputBlockSize getters on the cipher).
To decrypt you also use process() or processBlock() but pass false as the first parameter when calling init().
Finally, you can reset an algorithm to its initial state with the reset() method.
NOTE: You can generate key pairs for asymmetric block ciphers as explained in Using key generators.