In view of the importance of RSA encryption and the lack of relevant source code, it is hereby posted. Need to download the bcprov-jdk14-123.jar.
Import javax. crypto. cipher;
Import java. Security .*;
Import java. Security. spec. rsapublickeyspec;
Import java. Security. spec. rsw.vatekeyspec;
Import java. Security. spec. invalidkeyspecexception;
Import java. Security. Interfaces. rsw.vatekey;
Import java. Security. Interfaces. rsapublickey;
Import java. Io .*;
Import java. Math. biginteger;
/**
* RSA tool class. Provides encryption, decryption, and key-to-Peer generation methods.
* The http://www.bouncycastle.org needs to be downloaded from the bcprov-jdk14-123.jar.
*
*/
Public class rsautil {
/**
* Generate a key pair
* @ Return keypair
* @ Throws encryptexception
*/
Public static keypair generatekeypair () throws encryptexception {
Try {
Keypairgenerator keypairgen = keypairgenerator. getinstance ("RSA ",
New org. bouncycastle. JCE. provider. bouncycastleprovider ());
Final int key_size = 1024; // There is nothing to say. This value is related to the block encryption size, which can be changed, but not too large. Otherwise, the efficiency will be low.
Keypairgen. initialize (key_size, new securerandom ());
Keypair = keypairgen. genkeypair ();
Return keypair;
} Catch (exception e ){
Throw new encryptexception (E. getmessage ());
}
}
/**
* Generate a Public Key
* @ Param Modulus
* @ Param publicexponent
* @ Return rsapublickey
* @ Throws encryptexception
*/
Public static rsapublickey generatersapublickey (byte [] modulus, byte [] publicexponent) throws encryptexception {
Keyfactory keyfac = NULL;
Try {
Keyfac = keyfactory. getinstance ("RSA", new org. bouncycastle. JCE. provider. bouncycastleprovider ());
} Catch (nosuchalgorithmexception ex ){
Throw new encryptexception (ex. getmessage ());
}
Rsapublickeyspec pubkeyspec = new rsapublickeyspec (New biginteger (modulus), new biginteger (publicexponent ));
Try {
Return (rsapublickey) keyfac. generatepublic (pubkeyspec );
} Catch (invalidkeyspecexception ex ){
Throw new encryptexception (ex. getmessage ());
}
}
/**
* Generate a private key
* @ Param Modulus
* @ Param privateexponent
* @ Return rsw.vatekey
* @ Throws encryptexception
*/
Public static rsaprivatekey generatersaprivatekey (byte [] modulus, byte [] privateexponent) throws encryptexception {
Keyfactory keyfac = NULL;
Try {
Keyfac = keyfactory. getinstance ("RSA", new org. bouncycastle. JCE. provider. bouncycastleprovider ());
} Catch (nosuchalgorithmexception ex ){
Throw new encryptexception (ex. getmessage ());
}
Rsw.vatekeyspec prikeyspec = new rsw.vatekeyspec (New biginteger (modulus), new biginteger (privateexponent ));
Try {
Return (rsaprivatekey) keyfac. generateprivate (prikeyspec );
} Catch (invalidkeyspecexception ex ){
Throw new encryptexception (ex. getmessage ());
}
}
/**
* Encryption
* @ Param key: the Encrypted Key.
* @ Param data the plaintext data to be encrypted
* @ Return encrypted data
* @ Throws encryptexception
*/
Public static byte [] encrypt (Key key, byte [] data) throws encryptexception {
Try {
Cipher cipher = cipher. getinstance ("RSA", new org. bouncycastle. JCE. provider. bouncycastleprovider ());
Cipher. INIT (Cipher. encrypt_mode, key );
Int blocksize = cipher. getblocksize (); // obtain the size of the encrypted block. For example, the size of the encrypted block is 128 bytes, the size of the encrypted block is 1024 bytes, and the size of the encrypted block is 127 bytes; therefore, there are two encrypted blocks, the first 127 bytes, and the second one as one byte.
Int outputsize = cipher. getoutputsize (data. Length); // obtain the block size after encryption.
Int leavedsize = data. Length % blocksize;
Int blockssize = leavedsize! = 0? Data. Length/blocksize + 1: Data. Length/blocksize;
Byte [] Raw = new byte [outputsize * blockssize];
Int I = 0;
While (data. Length-I * blocksize> 0 ){
If (data. Length-I * blocksize> blocksize)
Cipher. dofinal (data, I * blocksize, blocksize, raw, I * outputsize );
Else
Cipher. dofinal (data, I * blocksize, Data. Length-I * blocksize, raw, I * outputsize );
// The doupdate method is unavailable. After checking the source code, we find that there is no actual action after each doupdate, except to put byte [] into bytearrayoutputstream, in the end, dofinal only encrypts all byte []. However, the size of the encrypted block may have exceeded the outputsize, so we had to use the dofinal method.
I ++;
}
Return raw;
} Catch (exception e ){
Throw new encryptexception (E. getmessage ());
}
}
/**
* Decryption
* @ Param key refers to the key to be decrypted.
* @ Param raw encrypted data
* @ Return refers to the decrypted plaintext.
* @ Throws encryptexception
*/
Public static byte [] decrypt (Key key, byte [] Raw) throws encryptexception {
Try {
Cipher cipher = cipher. getinstance ("RSA", new org. bouncycastle. JCE. provider. bouncycastleprovider ());
Cipher. INIT (Cipher. decrypt_mode, key );
Int blocksize = cipher. getblocksize ();
Bytearrayoutputstream bout = new bytearrayoutputstream (64 );
Int J = 0;
While (raw. Length-J * blocksize> 0 ){
Bout. Write (Cipher. dofinal (raw, J * blocksize, blocksize ));
J ++;
}
Return bout. tobytearray ();
} Catch (exception e ){
Throw new encryptexception (E. getmessage ());
}
}
/**
*
* @ Param ARGs
* @ Throws exception
*/
Public static void main (string [] ARGs) throws exception {
File file = new file ("test.html ");
Fileinputstream in = new fileinputstream (File );
Bytearrayoutputstream bout = new bytearrayoutputstream ();
Byte [] tmpbuf = new byte [1, 1024];
Int COUNT = 0;
While (COUNT = in. Read (tmpbuf ))! =-1 ){
Bout. Write (tmpbuf, 0, count );
Tmpbuf = new byte [2, 1024];
}
In. Close ();
Byte [] orgdata = bout. tobytearray ();
Keypair = rsautil. generatekeypair ();
Rsapublickey pubkey = (rsapublickey) keypair. getpublic ();
Rsw.vatekey prikey = (rsw.vatekey) keypair. getprivate ();
Byte [] pubmodbytes = pubkey. getmodulus (). tobytearray ();
Byte [] pubpubexpbytes = pubkey. getpublicexponent (). tobytearray ();
Byte [] primodbytes = prikey. getmodulus (). tobytearray ();
Byte [] pripriexpbytes = prikey. getprivateexponent (). tobytearray ();
Rsapublickey recoverypubkey = rsautil. generatersapublickey (pubmodbytes, pubpubexpbytes );
Rsw.vatekey recoveryprikey = rsautil. generatersaprivatekey (primodbytes, pripriexpbytes );
Byte [] Raw = rsautil. Encrypt (prikey, orgdata );
File = new file ("encrypt_result.dat ");
Outputstream out = new fileoutputstream (File );
Out. Write (raw );
Out. Close ();
Byte [] DATA = rsautil. decrypt (recoverypubkey, raw );
File = new file ("decrypt_result.html ");
Out = new fileoutputstream (File );
Out. Write (data );
Out. Flush ();
Out. Close ();
}
}
The public key can be used for encryption, and the private key can be used for decryption; or the private key can be used for encryption. Asymmetric encryption is very resource-consuming. Therefore, you can use symmetric encryption for big data such as des (for specific code, see my previous post ), asymmetric encryption of its symmetric key ensures data security and efficiency.