Implement RSR file encryption in Java

Source: Internet
Author: User

Instructions bcprov-ext-jdk16-141.jar package to download on http://www.bouncycastle.org/

 

/*
* To change this template, choose Tools | Templates
* And open the template in the editor.
*/

Package rsa;

Import java. io. FileOutputStream;
Import java. io. ObjectOutputStream;
Import java. security. KeyPair;
Import java. security. KeyPairGenerator;
Import java. security. PrivateKey;
Import java. security. PublicKey;
Import java. util. logging. Level;
Import java. util. logging. Logger;

/**
*
* @ Author Administrator
*/
Public class GenKey {
Public static void main (String [] args) {// create a key
Try {
// Create a key pair Generator
KeyPairGenerator KPG = KeyPairGenerator. getInstance ("RSA ");
// Initialize the key generator
KPG. initialize (1024 );
// Generate a key pair
KeyPair KP = KPG. genKeyPair ();
// Obtain the public key and key
PublicKey pbKey = KP. getPublic ();
PrivateKey prKey = KP. getPrivate ();
// Save the public key to the file
FileOutputStream out = new FileOutputStream ("RSAPublic. dat ");
ObjectOutputStream fileOut = new ObjectOutputStream (out );
FileOut. writeObject (pbKey );
// Save the key to the file
FileOutputStream outPrivate = new FileOutputStream ("rs1_vate. dat ");
ObjectOutputStream privateOut = new ObjectOutputStream (outPrivate );
Privateout. writeobject (prkey );
} Catch (exception ex ){
Logger. getlogger (genkey. Class. getname (). Log (level. Severe, null, ex );
}

}

}

 

 

/*
* To change this template, choose tools | templates
* And open the template in the editor.
*/
Package rsatest;

Import cipherinputstream. encryptanddecrypt;
Import java. Io. fileinputstream;
Import java. Io. fileoutputstream;
Import java. Io. objectinputstream;
Import java. Security. Key;
Import java. util. logging. Level;
Import java. util. logging. Logger;
Import javax. crypto. Cipher;
Import org. bouncycastle. jce. provider. BouncyCastleProvider;

/**
*
* @ Author Administrator
*/
Public class RRSSA {

Public static void main (String [] args ){
// Name of the file to be encrypted or decrypted
String dataFileName = args [0];
// Whether encryption or decryption is performed, encryption is encrypt, and decryption is decrypt
String opMode = args [1];
String keyFileName = null;
// Name of the key file
If (opMode. inclusignorecase ("encrypt ")){
KeyFileName = "RSAPublic. dat ";
} Else {
KeyFileName = "rs1_vate. dat ";
}

Try {
// Generate the key
FileInputStream keyfcm = new FileInputStream (keyFileName );
ObjectInputStream OIS = new ObjectInputStream (keyfs );
Key key = (Key) OIS. readObject ();

// Create and initialize the secret
Cipher cp = Cipher. getInstance ("RSA", new BouncyCastleProvider (); // no less
// BouncyCastLeProvider class in bcprov-ext-jdk16-141.jar
If (opMode. inclusignorecase ("encrypt ")){

Cp. init (Cipher. ENCRYPT_MODE, key );
} Else if (opMode. inclusignorecase ("decrypt ")){
Cp. init (Cipher. DECRYPT_MODE, key );
} Else {
Return;
}

FileInputStream dataFIS = new FileInputStream (dataFileName );
// Obtain the data to be encrypted
Int size = dataFIS. available ();
Byte [] encryptByte = new byte [size];
DataFIS. read (encryptByte );

// For encryption operations
If (opMode. inclusignorecase ("encrypt ")){
// Create a file output stream
FileOutputStream FOS = new FileOutputStream ("mi.txt ");
// The RSA algorithm must adopt block encryption.
// Obtain the size of the RSA encrypted Block
Int blockSize = cp. getBlockSize ();
// Return the length of the output buffer (in bytes) required to save the next update or doFinal operation result based on the given input length inputLen (in bytes ).
Int outputBlockSize = cp. getOutputSize (encryptByte. length );

// Determine the number of times (number of encrypted blocks)
Int leavedSize = encryptByte. length % blockSize;
Int blocksNum = leavedSize = 0? EncryptByte. length/blockSize
: EncryptByte. length/blockSize + 1;

Byte [] cipherData = new byte [blocksNum * outputBlockSize];

// Encrypt each data block separately
For (int I = 0; I <blocksNum; I ++ ){

If (encryptByte. length-I * blockSize)> blockSize ){
Cp. doFinal (encryptByte, I * blockSize, blockSize, cipherData, I * outputBlockSize );
} Else {
CP. dofinal (encryptbyte, I * blocksize, encryptbyte. Length-I * blocksize, cipherdata, I * outputblocksize );
}

}

FOS. Write (cipherdata );

FOS. Close ();

} Else {// for decryption

Fileoutputstream Fos = new fileoutputstream ("jiemi.txt ");
Int blocksize = CP. getblocksize ();
Int J = 0;

// Decrypt each block of data separately
While (encryptbyte. Length-J * blocksize)> 0 ){
FOS. write (cp. doFinal (encryptByte, j * blockSize, blockSize ));
J ++;
}

FOS. close ();

}
} Catch (Exception ex ){
Logger. getLogger (EncryptAndDecrypt. class. getName (). log (Level. SEVERE, null, ex );
}
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.