A session key program developed in JAVA

Source: Internet
Author: User
A session key program developed in JAVA-general Linux technology-Linux programming and kernel information. The following is a detailed description. /*
To run this program, you need to download JCE, Bouncy Castle's JCE with Provider and Lightweight API
Web site is http://www.bouncycastle.org
The configuration is as follows:
In WINDOWS, you need to copy the downloaded bcprov-jdk14-119.jar file to two places:
In the JDK directory you installed, for example, my C: \ j2sdk1.4.0-rc \ jre \ lib \ ext
In your JDK running environment
C: \ Program Files \ Java \ j2re1.4.0-rc \ lib \ ext;
In addition, you must modify two java. security statements:
In C: \ j2sdk1.4.0-rc \ jre \ lib \ security \ java. security;
C: \ Program Files \ Java \ j2re1.4.0-rc \ lib \ security \ java. security;
Add security. provider.6 = org. bouncycastle. jce. provider. BouncyCastleProvider to java. security.
If everything goes well, you can run the program.

This program can encrypt and decrypt your files. You need to specify the data. The interface has been provided in the program.
For example, if you specify the file name to be encrypted "4.txt" and the encrypted file storage location" 6.txt ",
There is also a password such as "liufeng", and then run this program, then "6.txt" will be the ciphertext of" 4.txt.
Note that the password is the decryption key. Do not forget it.
For other decryption processes, refer.

This program uses session key encryption to provide many interfaces. If you need an encryption process in your project, you can make some improvements for your use.
*/
Import java. security .*;
Import java. security. spec .*;
Import javax. crypto .*;
Import javax. crypto. spec .*;
Import java. io .*;
Import java. util .*;


Public class FileEncryptorRSA {


Private static final int ITERATIONS = 1000; // count, used in salt adding
Private static byte [] publicKeyBytes; // Public Key
Private static byte [] privateKeyBytes; // private Key
Private static String SessionKey; // session key
Public static String ENCRYPT_PRIVATEKEY_FILE = "1.txt"; // place the encrypted private key in the file.
Private static String TEXT_FILE = "4.txt"; // the file to be encrypted
Private static String ENCRPTOR_TEXT_FILE = "5.txt"; // encrypted file
Private static String DENCRYPTOR_TEXT_FILE = "6.txt"; // decrypted file
Private static String password = "liufeng"; // The password is used to encrypt the private key.


Public void setTEXT_FILE (String fileName ){
TEXT_FILE = fileName;
}
Public void setENCRYPT_PRIVATEKEY_FILE (String fileName ){
ENCRYPT_PRIVATEKEY_FILE = fileName;
}
Public String getENCRYPT_PRIVATEKEY_FILE (){
Return ENCRYPT_PRIVATEKEY_FILE;
}

Public void setENCRPTOR_TEXT_FILE (String fileName ){
ENCRPTOR_TEXT_FILE = fileName;
}
Public String getENCRPTOR_TEXT_FILE (){
Return ENCRPTOR_TEXT_FILE;
}
Public void setDENCRYPTOR_TEXT_FILE (String fileName ){
DENCRYPTOR_TEXT_FILE = fileName;
}
Public String getDENCRYPTOR_TEXT_FILE (){
Return DENCRYPTOR_TEXT_FILE;
}
Public void setPassword (String password ){
This. password = password;
}


// Create a RSA secretKey
Public static void createKey () throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator. getInstance ("RSA ");
KeyPairGenerator. initialize (1024 );
KeyPair keyPair = keyPairGenerator. genKeyPair ();
// Obtain the byte array of the Public Key
PublicKeyBytes = keyPair. getPublic (). getEncoded ();
// Obtain the Private Key
Byte [] privateKeyBytes = keyPair. getPrivate (). getEncoded ();
Byte [] encrytedPrivatekey = passwordEncrypt (password. toCharArray (), privateKeyBytes );
FileOutputStream fos = new FileOutputStream (ENCRYPT_PRIVATEKEY_FILE );
Fos. write (encrytedPrivatekey );
Fos. close ();
}



// Encrypt the private key with the given password
Private static byte [] passwordEncrypt (char [] password, byte [] privateKeyBytes)
Throws Exception {
// Create 8 byte salt
Byte [] salt = new byte [8];
Random random = new Random ();
Random. nextBytes (salt );
// Create a PBE key and cipher
PBEKeySpec keySpec = new PBEKeySpec (password );
SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("PBEWithSHAAndTwofish-CBC ");
SecretKey key = keyFactory. generateSecret (keySpec );
PBEParameterSpec paramSpec = new PBEParameterSpec (salt, ITERATIONS );
Cipher cipher = Cipher. getInstance ("PBEWithSHAAndTwofish-CBC ");
Cipher. init (Cipher. ENCRYPT_MODE, key, paramSpec );
// Encrypt the byte []
Byte [] cipherPriKey = cipher. doFinal (privateKeyBytes );
// Write out salt, and then the cipherPriKey
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
Baos. write (salt );
Baos. write (cipherPriKey );
Return baos. toByteArray ();
}



// Encrypt the given file with the session key, then encrypt the session key with the public key, and save it to the file
// The last encrypted file consists of the Key Length + Encrypted Key (session key) + ciphertext
Public static void encrypt () throws Exception {

// Convert to an RSA key
X509EncodedKeySpec keySpec = new X509EncodedKeySpec (publicKeyBytes );
KeyFactory keyFactory = KeyFactory. getInstance ("RSA ");
PublicKey publickey = keyFactory. generatePublic (keySpec );
// Open the file storing the ciphertext
DataOutputStream output = new DataOutputStream (new FileOutputStream (ENCRPTOR_TEXT_FILE ));
// Create the RSA CIpher
Cipher rsaCipher = Cipher. getInstance ("RSA/ECB/PKCS1Padding ");
RsaCipher. init (Cipher. ENCRYPT_MODE, publickey );
// Create a session key (Rijndael)
KeyGenerator rijndaelKeyGenerator = KeyGenerator. getInstance ("Rijndael ");
Rijdaelkeygenerator. init (256 );
Key rijndaelKey = rijndaelKeyGenerator. generateKey ();
// Public key encryption session key
Byte [] encodedKeyBytes = rsaCipher. doFinal (rijndaelKey. getEncoded ());
Output. writeInt (encodedKeyBytes. length );
Output. write (encodedKeyBytes );
// Generate an IV Vector
SecureRandom random = new SecureRandom ();
Byte [] iv = new byte [16];
Random. nextBytes (iv );
Output. write (iv );

// Encrypt the body
IvParameterSpec spec = new IvParameterSpec (iv );
Cipher extends riccipher = Cipher. getInstance ("Rijndael/CBC/PKCS5Padding ");
SymmetricCipher. init (Cipher. ENCRYPT_MODE, rijndaelKey, spec );
CipherOutputStream cos = new CipherOutputStream (output, symmetricCipher );
FileInputStream input = new FileInputStream (TEXT_FILE );

Int theByte = 0;
While (theByte = input. read ())! =-1 ){
Cos. write (theByte );
}
Input. close ();
Cos. close ();
Return;
}



// Obtain the Private Key
Private static byte [] passwordDecrypt (char [] password, byte [] ciphertext)
Throws Exception {
Byte [] salt = new byte [8];
ByteArrayInputStream bais = new ByteArrayInputStream (ciphertext );
Bais. read (salt, 0, 8 );
Byte [] remainingCiphertext = new byte [ciphertext. length-8];
Bais. read (remainingCiphertext, 0, ciphertext. length-8 );
PBEKeySpec keySpec = new PBEKeySpec (password );
SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("PBEWithSHAAndTwofish-CBC ");
SecretKey key = keyFactory. generateSecret (keySpec );
PBEParameterSpec paramSpec = new PBEParameterSpec (salt, ITERATIONS );
Cipher cipher = Cipher. getInstance ("PBEWithSHAAndTwofish-CBC ");
Cipher. init (Cipher. DECRYPT_MODE, key, paramSpec );
Return cipher. doFinal (remainingCiphertext );
}


// Decrypt the encrypted file
Public static void decrypt ()
Throws Exception {
FileInputStream FCM = new FileInputStream (ENCRYPT_PRIVATEKEY_FILE );
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
Int theByte = 0;
While (theByte = Fi. read ())! =-1 ){
Baos. write (theByte );
}
FCM. close ();
// Obtain the encrypted Private Key
Byte [] keyBytes = baos. toByteArray ();
Baos. close ();
// Obtain the Private Key
Byte [] sKey = passwordDecrypt (password. toCharArray (), keyBytes );
// Generate the RSA private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec (sKey );
KeyFactory keyFactory = KeyFactory. getInstance ("RSA ");
PrivateKey privateKey = keyFactory. generatePrivate (keySpec );
Cipher rsaCipher = Cipher. getInstance ("RSA/ECB/PKCS1Padding ");

DataInputStream dis = new DataInputStream (new FileInputStream (ENCRPTOR_TEXT_FILE ));
// Read Password Length and password
Byte [] encryptedKeyBytes = new byte [dis. readInt ()];
Dis. readFully (encryptedKeyBytes );
RsaCipher. init (Cipher. DECRYPT_MODE, privateKey );
Byte [] rijdaelKeyBytes = rsaCipher. doFinal (encryptedKeyBytes );
// Obtain the session key
SecretKey rijndaelKey = new SecretKeySpec (rijdaelKeyBytes, "Rijndael ");
Byte [] iv = new byte [16];
Dis. read (iv );
IvParameterSpec spec = new IvParameterSpec (iv );
// Decrypt the body with the session key
Cipher cipher = Cipher. getInstance ("Rijndael/CBC/PKCS5Padding ");
Cipher. init (Cipher. DECRYPT_MODE, rijndaelKey, spec );

CipherInputStream cis = new CipherInputStream (dis, cipher );
FileOutputStream fos = new FileOutputStream (DENCRYPTOR_TEXT_FILE );

TheByte = 0;
While (theByte = cis. read ())! =-1 ){
Fos. write (theByte );
}
Cis. close ();
Fos. close ();
Return;
}
Public static void main (String [] args) throws Exception {
CreateKey ();
Encrypt ();
Decrypt ();
}
}
Related Article

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.