In view of the importance of RSA encryption and the lack of relevant source code, it is organized. Needed
Http://www.bouncecastle.org download bcprov-jdk14-123.jar.
Import javax.crypto.cipher;
Import java.security. *;
Import java.security.spec.rsapublicKeyspec;
Import java.security.spec.rsapriVateKeyspec;
Import java.security.spec.invalidKeyspecexception;
Import java.security.interfaces.rsapriVateKey;
Import java.security.Interfaces.rsapublicKey;
Import java.io. *;
Import java.math.biginteger;
/ **
* RSA tool class. Provide encryption, decryption, generating key peers.
* Need to
Http://www.bouncecastle.org download bcprov-jdk14-123.jar.
* @Author xiaoyusong
* Mail: xiaoyusong@etang.com
* Msn: xiao_yu_song@hotmail.com
* @Since 2004-5-20
*
* /
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.bouncecastle.jce.Provider.bouncycastleProvider ());
Final int key_size = 1024; // Nothing, this value is related to the size of the block encryption, can be changed, but don't be too big, otherwise the efficiency will be low
Keypairgen.Initialize (key_size, new security);
Keypair Keypair = keypairgen.genkeypair ();
Return Keypair;
} Catch (exception e) {
Throw new encryptexception (E.getMessage ());
}
}
/ **
* Generate public keys
* @Param MODULUS
* @Param Publicexponent
* @Return RsapublicKey
* @Throws EncryptException
* /
Public Static RsapublicKey GeneretesapublicKey (Byte [] MODULUS, BYTE [] PUBLICEXPONENT "
KeyFactory Keyfac = NULL;
Try {
Keyfac = KeyFactory.GetInstance ("RSA", New Org.bouncecastle.jce.Provider.bouncycastleProvider ());
} Catch (nosuchaalgorithmexception 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 private keys
* @Param MODULUS
* @Param PrivateExponent
* @Return RsapriVateKey
* @Throws EncryptException
* /
Public Static RsaprivateKey GeneretesAprivateKey (Byte [] MODULUS, BYTE [] privateexponent) throws encryptexception {
KeyFactory Keyfac = NULL;
Try {
Keyfac = KeyFactory.GetInstance ("RSA", New Org.bouncecastle.jce.Provider.bouncycastleProvider ());
} Catch (nosuchaalgorithmexception ex) {
Throw new encryptException (ex.getMessage ());
}
RSAPRIVATEYSPEC PRIKEYSPEC = New RsaprivateKeyspec (New Biginteger (MODULUS), New Biginteger (PrivateExponent);
Try {
Return (RsapriVateKey) KeyFAC.GeneratePrivate (Prikeyspec);
} Catch (invalidKeyspecexception ex) {
Throw new encryptException (ex.getMessage ());
}
}
/ **
* Encryption
* @Param Key encrypted key
* @PARAM DATA to be encrypted
* @Return encrypted data
* @Throws EncryptException
* /
Public static Byte [] encrypt (key key, byte [] data) throws encryptException {
Try {
Cipher cipher = copher.getinstance ("RSA", New Org.bouncecastle.jce.Provider.bouncycastleProvider ());
Cipher.init (cipher.encrypt_mode, key);
INT blocksize = copher.getblocksize (); // Get encryption block size, such as: encrypted data is 128 Byte, and key_size = 1024 encryption block is 127 byte, 128 BYTE after encryption; therefore has 2 plug-in blocks , The first 127 byte second is 1 Byte
INT outputsize = copher.getOutputSize (data.length); // Get the size of the block 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);
// This DoupDate method is not available. After checking the source code, it is found that there is no practical action after each DoupDate in addition to the Byte [] in ByteArrayoutputStream, and the last DOFINAL will encrypt all the Byte [], but it is At this point, the encryption block size is likely to be exceeded OutputSize so you have to use the DOFINAL method.
i ;
}
Return RAW;
} Catch (exception e) {
Throw new encryptexception (E.getMessage ());
}
}
/ **
* Decryption
* @Param Key Decryption key
* @Param Raw has encrypted data
* @Return decryption plain text
* @Throws EncryptException
* /
Public static byte [] decrypt (key key, byte [] raw) throws encryptexception {
Try {
Cipher cipher = copher.getinstance ("RSA", New Org.bouncecastle.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 [1024];
INT count = 0; while (count = in.read (tmpbuf))! = -1) {
Bout.write (TmpBuf, 0, count);
TMPBUF = New byte [1024];
}
In.Close ();
Byte [] orgdata = bout.tobytearray ();
Keypair Keypair = rsautil.generateKeyPair ();
RsapublicKey Pubkey = (RSAPublicKey) Keypair.getPublic ();
RsaprivateKey PriKey = (RSAPRIVATEKEY) 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.generetesapublicKey (PubmodBytes, PubPubexpbytes);
RsaprivateKey RecoveryPrikey = rsautil.GeneretesAprivateKey (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 ();
}
}
Encryption can use the public key to decrypt the private key; or encrypt the private key. Usually, asymmetric encryption is very resource, it can be symmetrically encrypted with big data, such as: DES (specific code can be seen before I have previously sent it), and the symmetric key is asymmetrical, so that data is guaranteed Safety, but also guarantee efficiency.