java encrypt

package encryption.algorithm.base;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;



import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class RSAFileUtility {


private static final String ORIGIN_FILE_PATH = "c:/plainText.txt";
   private static final String ENCRYPTED_FILE_PATH = "c:/cipherText.txt";
   private static final String DECRYPTED_FILE_PATH = "c:/decryptedText.txt";

/*
* cryptographic algorithm
*/
private static final String ALGORITHM = "RSA";
// private static final String ALGORITHM = "RSA/ECB/PKCS1Padding";


/*
* signature algorithm
*/
//    public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; 
    public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
   
    /*
     * message digest algorithm
     */
//    public static final String MESSAGE_DIGEST_ALGORITHM = "MD5";
    public static final String MESSAGE_DIGEST_ALGORITHM = "SHA";
   
private static final String PUBLICKEY = "PublicKey";
private static final String PRIVATEKEY = "PrivateKey";


/**
* Generate keyMap that include public key and private key
* @return
* @throws Exception
*/
public static Map<String, String> initKey() throws Exception {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publickey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

Map<String,String> keyMap = new HashMap<String, String>();
keyMap.put(PUBLICKEY, encryptByBase64(publickey));
keyMap.put(PRIVATEKEY, encryptByBase64(privateKey));
return keyMap;

}

/**
* Encrypt key by Base64
* @param key
* @return
*/
public static String encryptByBase64(Key key){
return new BASE64Encoder().encodeBuffer(key.getEncoded());
}

/**
* Decrypt key by Base64
* @param key
* @return
* @throws IOException
*/
public static byte[] decryptByBase64(String key) throws IOException{
return new BASE64Decoder().decodeBuffer(key);
}

/**
* Sign
* @param text
* @param key
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static byte[] sign(String text,PrivateKey key) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException{
byte[] textByte = text.getBytes();
Signature signInstance = Signature.getInstance(SIGNATURE_ALGORITHM);
signInstance.initSign(key);
signInstance.update(textByte);
byte[] signText = signInstance.sign();
return signText;
}


public static byte[] sign(byte[] text,PrivateKey key) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException{
Signature signInstance = Signature.getInstance(SIGNATURE_ALGORITHM);
signInstance.initSign(key);
signInstance.update(text);
byte[] signText = signInstance.sign();
return signText;
}



    /**
     * Encrypt a text using public key.
     * @param text The original unencrypted text
     * @param key The public key
     * @return Encrypted text
     * @throws java.lang.Exception
     */
    public static byte[] encrypt(byte[] text, PublicKey key) throws Exception
    {
        byte[] cipherText = null;
        try
        {
            // get an RSA cipher object and print the provider
            Cipher cipher = Cipher.getInstance("RSA");

            // encrypt the plaintext using the public key
            cipher.init(Cipher.ENCRYPT_MODE, key);
            cipherText = cipher.doFinal(text);
        }
        catch (Exception e)
        {
         
            throw e;
        }
        return cipherText;
    }

    /**
     * Decrypt text using private key
     * @param text The encrypted text
     * @param key The private key
     * @return The unencrypted text
     * @throws java.lang.Exception
     */
    public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception
    {
        byte[] dectyptedText = null;
        try
        {
            // decrypt the text using the private key
            Cipher cipher = Cipher.getInstance("RSA");
          
            cipher.init(Cipher.DECRYPT_MODE, key);
            dectyptedText = cipher.doFinal(text);
        }
        catch (Exception e)
        {
         
            throw e;
        }
        return dectyptedText;

    }

/**
* Verify signature
* @param text
* @param key
* @param signature
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
*/
public static boolean verifySign(byte[] text, PublicKey key, byte[] signature) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException{
Signature sign = Signature.getInstance(SIGNATURE_ALGORITHM);
sign.initVerify(key);
sign.update(text);
boolean verifyResult = sign.verify(signature);
return verifyResult;
}

  public static void encryptDecryptFile(String srcFileName, String destFileName, Key key, int cipherMode) throws Exception
    {
        OutputStream outputWriter = null;
        InputStream inputReader = null;
        try
        {
            Cipher cipher = Cipher.getInstance("RSA");
            String textLine = null;
            //RSA encryption data size limitations are slightly less than the key modulus size,
            //depending on the actual padding scheme used (e.g. with 1024 bit (128 byte) RSA key,
            //the size limit is 117 bytes for PKCS#1 v 1.5 padding. (http://www.jensign.com/JavaScience/dotnet/RSAEncrypt/)
            byte[] buf = cipherMode == Cipher.ENCRYPT_MODE? new byte[100] : new byte[128];
            int bufl;
            // init the Cipher object for Encryption...
            cipher.init(cipherMode, key);

            // start FileIO
            outputWriter = new FileOutputStream(destFileName);
            inputReader = new FileInputStream(srcFileName);
            while ( (bufl = inputReader.read(buf)) != -1)
            {
                byte[] encText = null;
                if (cipherMode == Cipher.ENCRYPT_MODE)
                {
                      encText = encrypt(copyBytes(buf,bufl),(PublicKey)key);
                }
                else
                {
          
//                        System.out.println("buf = " + new BASE64Encoder().encode(buf));
                 
                    encText = decrypt(copyBytes(buf,bufl),(PrivateKey)key);
                }
                outputWriter.write(encText);
         
//                     System.out.println("encText = " + new BASE64Encoder().encode(encText));
          
            }
            outputWriter.flush();

        }
        catch (Exception e)
        {
          
            throw e;
        }
        finally
        {
            try
            {
                if (outputWriter != null)
                {
                    outputWriter.close();
                }
                if (inputReader != null)
                {
                    inputReader.close();
                }
            }
            catch (Exception e)
            {
                // do nothing...
            } // end of inner try, catch (Exception)...
        }
    }

    public static byte[] copyBytes(byte[] arr, int length)
    {
        byte[] newArr = null;
        if (arr.length == length)
        {
            newArr = arr;
        }
        else
        {
            newArr = new byte[length];
            for (int i = 0; i < length; i++)
            {
                newArr[i] = (byte) arr[i];
            }
        }
        return newArr;
    }

/**
* Generate MessageDigest
* @param text
* @return
* @throws NoSuchAlgorithmException
*/
public static byte[] generateMessageDigest(String fileName) throws Exception{
FileInputStream fi = new FileInputStream(fileName);
byte[] bufferArray = new byte[100];
int bufferSize = 0;
byte[] digest = null;
while((bufferSize=fi.read(bufferArray)) != -1){
MessageDigest md = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM);
md.update(copyBytes(bufferArray, bufferSize));
digest = md.digest();
}

return digest;
}


public static String readFile(String fileName) throws Exception{
BufferedReader bf = new BufferedReader(new FileReader(fileName));
String s = "";
String plainText = "";
while((s=bf.readLine()) != null){
plainText = plainText + s;
}
return plainText;
}


public static String inputFile(String fileName) throws Exception{
FileInputStream fi = new FileInputStream(fileName);
byte[] bufferArray = new byte[100];
int bufferSize = 0;
String text="";

while((bufferSize=fi.read(bufferArray)) !=  -1){
String s = new BASE64Encoder().encode(copyBytes(bufferArray, bufferSize));
text = text + s;
}
return text;
}

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {



System.out.println("plainText:\n" + readFile(ORIGIN_FILE_PATH));

//A Generate public key and private key
Map<String, String> aKeyMap = RSAFileUtility.initKey();
String aPublickey = (String)aKeyMap.get(PUBLICKEY);
String aPrivateKey = (String)aKeyMap.get(PRIVATEKEY);
        System.err.println("Mr A Public key:\n" + aPublickey);  
        System.err.println("Mr A Private key:\n" + aPrivateKey);  
       
    //B Generate public key and private key
Map<String, String> bKeyMap = RSAFileUtility.initKey();
String bPublickey = (String)bKeyMap.get(PUBLICKEY);
String bPrivateKey = (String)bKeyMap.get(PRIVATEKEY);
        System.err.println("Mr B Public key:\n" + bPublickey);  
        System.err.println("Mr B Private key:\n" + bPrivateKey);  
       
        // A send A public key to B
        // B send B public key to A
       

//Generate message digest
byte[] messageDigest = RSAFileUtility.generateMessageDigest(ORIGIN_FILE_PATH);
       
       
        //A get private key
        PKCS8EncodedKeySpec aPrivateKeySpec = new PKCS8EncodedKeySpec(decryptByBase64(aPrivateKey));
        KeyFactory facInstance = KeyFactory.getInstance(ALGORITHM);
        PrivateKey aPrivateKeyCopy = facInstance.generatePrivate(aPrivateKeySpec);
       
        //A get public key
        X509EncodedKeySpec bPublicKeySpec = new X509EncodedKeySpec(decryptByBase64(bPublickey));
        PublicKey bPublicKeyCopy = facInstance.generatePublic(bPublicKeySpec);
       

        //encrypt by B public key
        RSAFileUtility.encryptDecryptFile(ORIGIN_FILE_PATH, ENCRYPTED_FILE_PATH, bPublicKeyCopy, Cipher.ENCRYPT_MODE);
   
       
        //sign by A private key
        byte[] signText = RSAFileUtility.sign(messageDigest, aPrivateKeyCopy);
  
       
        System.out.println("encryptText:\n" + inputFile(ENCRYPTED_FILE_PATH));
     

       
        //A send cipherText and signText to B

       
        //B get private key
        PKCS8EncodedKeySpec bPrivateKeySpec = new PKCS8EncodedKeySpec(decryptByBase64(bPrivateKey));
        PrivateKey bPrivateKeyCopy = facInstance.generatePrivate(bPrivateKeySpec);
       
        //B get public key
        X509EncodedKeySpec aPublicKeySpec = new X509EncodedKeySpec(decryptByBase64(aPublickey));
        PublicKey aPublicKeyCopy = facInstance.generatePublic(aPublicKeySpec);
       
        boolean verifySign = RSAFileUtility.verifySign(messageDigest, aPublicKeyCopy, signText);
        if(verifySign){
        System.err.println("Signature is right!");
        RSAFileUtility.encryptDecryptFile(ENCRYPTED_FILE_PATH, DECRYPTED_FILE_PATH, bPrivateKeyCopy, Cipher.DECRYPT_MODE);
        System.out.println("decryptedText:\n" + readFile(DECRYPTED_FILE_PATH));
       
        }
       





     
       

    
    
       
       

       


}

}

你可能感兴趣的:(java,C++,c,Security,Scheme)