您的位置:首页 > 编程语言 > Java开发

加密解密java

2015-11-16 16:49 399 查看
package com.company.item.util;

    import java.security.SecureRandom;

    import java.security.Security;

    import javax.crypto.Cipher;

    import javax.crypto.SecretKey;

    import javax.crypto.SecretKeyFactory;

    import javax.crypto.spec.DESKeySpec;

    import sun.misc.BASE64Decoder;

    import sun.misc.BASE64Encoder;

    public class Corpy22 {

    public String decryptMessage(String encryptedText) {

    // TODO Auto-generated method stub

    String passwordString = encryptedText.substring(0, 12);//截取传入的字符串前12位取出秘钥,秘钥为24字节

    String cipherString = encryptedText.substring(12, encryptedText//截取出秘钥后面的需要解密的信息段

    .length());

    System.out.println(cipherString.toString()+"需要解密的信息部分");

    BASE64Decoder decoder = new BASE64Decoder();

    try {

    /**将秘钥和解密部分进行base64处理*/

    byte[] password = decoder.decodeBuffer(passwordString);

    byte[] cipherText = decoder.decodeBuffer(cipherString);

    //秘钥配置

    Security.addProvider(new com.sun.crypto.provider.SunJCE());

    //创建加密后数据对应的秘钥,得到对应的解密钥匙key

    DESKeySpec keySpec = new DESKeySpec(password);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

    SecretKey key = keyFactory.generateSecret(keySpec);

    //解密配置参数

    byte[] iv = new sun.misc.BASE64Decoder().decodeBuffer("t4JPbY+rXgk=");

    javax.crypto.spec.IvParameterSpec ips = new javax.crypto.spec.IvParameterSpec(

    iv);

    //定义解密器

    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

    cipher.init(Cipher.DECRYPT_MODE, key,ips);

    

    return new String(cipher.doFinal(cipherText));

    

    } catch (Exception e) {

    e.printStackTrace();

    return null;

    }

    }

    public String encryptMessage(String plainText) {

    // TODO Auto-generated method stub

    try {

    byte[] password = new byte[8];

    SecureRandom random = new SecureRandom();

    random.nextBytes(password);//随机生成一个对应的秘钥

    

    Security.addProvider(new com.sun.crypto.provider.SunJCE());

    DESKeySpec keySpec = new DESKeySpec(password);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

    SecretKey key = keyFactory.generateSecret(keySpec);

    

    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

    //iv在解密的时候必须要这个,加密器参数

    byte[] iv = new sun.misc.BASE64Decoder().decodeBuffer("t4JPbY+rXgk=");

    javax.crypto.spec.IvParameterSpec ips = new javax.crypto.spec.IvParameterSpec(

    iv);

    System.out.println();

    cipher.init(Cipher.ENCRYPT_MODE, key,ips);

    byte[] cipherText = cipher.doFinal(plainText.getBytes());

    BASE64Encoder encoder = new BASE64Encoder();

   return encoder.encode(password).concat(encoder.encode(cipherText));

 

    } catch (Exception e) {

    e.printStackTrace();

    return null;

    }

    }

    public static void main(String[] args) {

    Corpy22 test1 = new Corpy22();

    //String cipher = test1.encryptMessage("555he142我们啊的他们");

       // System.out.println(cipher+"**加密过后的字符串");

  //  String cipher ="0/P5Nm69/aI=bJbQmQr7r9kYwPs5OGhyruo6XU4qdyEV";

      //  String cipher = "O0Ewf68H60A=aVq4PajiEFskyEUJO7IcyTivWOcCl9OlfwTDsJSQxzk=";

       // String cipher = "O0Ewf68H60A=aVq4PajiEFskyEUJO7IcyTivWOcCl9OlfwTDsJSQxzk=";

        String cipher ="O0Ewf68H60A=aVq4PajiEFskyEUJO7IcyTivWOcCl9OlfwTDsJSQxzk=";

   String cipher1 = test1.decryptMessage(cipher);

   System.out.println(cipher1+"**解密后的字符串");

    }
    }

/**********************************************2******************************/

package com.company.item.util;

    import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.security.Key;

import java.security.Security;

import javax.crypto.Cipher;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

    public class Decode2{

     private static BASE64Encoder encoder = new BASE64Encoder();

     private static BASE64Decoder decoder = new BASE64Decoder();

     static String strDefaultKey = "initkey";

     static Cipher encryptCipher = null;

     static Cipher decryptCipher = null;

     

     static {

         Security.addProvider(new com.sun.crypto.provider.SunJCE());

         Key key = null;

        try {

          key = getKey(strDefaultKey.getBytes());

          encryptCipher = Cipher.getInstance("DES");

          encryptCipher.init(Cipher.ENCRYPT_MODE, key);

          decryptCipher = Cipher.getInstance("DES");

          decryptCipher.init(Cipher.DECRYPT_MODE, key);

        }catch(Exception e){

            e.printStackTrace();

            }

        }

     public Decode2(String strDefauKey){

       Security.addProvider(new com.sun.crypto.provider.SunJCE());

             Key key = null;

            try {

              key = getKey(strDefaultKey.getBytes());

              encryptCipher = Cipher.getInstance("DES");

              encryptCipher.init(Cipher.ENCRYPT_MODE, key);

              decryptCipher = Cipher.getInstance("DES");

              decryptCipher.init(Cipher.DECRYPT_MODE, key);

            }catch(Exception e){

                e.printStackTrace();

                }

            }

     

     public static byte[] encrypt(byte[] arrB) throws Exception {

      return encryptCipher.doFinal(arrB);

     }

     public static byte[] decrypt(byte[] arrB) throws Exception {

      return decryptCipher.doFinal(arrB);

     }

     private static  Key getKey(byte[] arrBTmp) throws Exception {

      byte[] arrB = new byte[8];

      for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {

       arrB[i] = arrBTmp[i];

      }

      Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");

      return key;

     }

     

     public static void main(String[] args) {

     Decode2 d2 = new Decode2(strDefaultKey);

     String str = "啊ta他们是ddd584";

     try {

         String str1 = encoder.encode(d2.encrypt(str.getBytes("utf-8")));

        System.out.println(str1+"加密后的字符串");

        

    } catch (UnsupportedEncodingException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (Exception e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

     String str2 = "UT62+Vxd7IeX2CDEEJvRR70iG33HiEbu";

    try {

       String str3 = new String(d2.decrypt(decoder.decodeBuffer(str2)));

       System.out.println("解密后的数据:"+str3);

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (Exception e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

    }

     

    }

///////////////////////////////******************公钥私钥的控制******************///////////////////////////////////////////

package com.company.item.util;

    import java.io.BufferedReader;

    import java.io.BufferedWriter;

    import java.io.FileReader;

    import java.io.FileWriter;

    import java.io.IOException;

    import java.security.InvalidKeyException;

    import java.security.Key;

    import java.security.KeyFactory;

    import java.security.KeyPair;

    import java.security.KeyPairGenerator;

    import java.security.NoSuchAlgorithmException;

    import java.security.PrivateKey;

    import java.security.PublicKey;

    import java.security.interfaces.RSAPrivateKey;

    import java.security.interfaces.RSAPublicKey;

    import java.security.spec.PKCS8EncodedKeySpec;

    import java.security.spec.X509EncodedKeySpec;

    import java.util.HashMap;

    import java.util.Map;

    import javax.crypto.BadPaddingException;

    import javax.crypto.Cipher;

    import javax.crypto.IllegalBlockSizeException;

    import javax.crypto.NoSuchPaddingException;

    import sun.misc.BASE64Decoder;

    import sun.misc.BASE64Encoder;

    /**

     * RSA算法,实现数据的加密解密。

     * @author ShaoJiang

     *

     */

    class RSAUtil {

       

        private static Cipher cipher;

        

        static{

            try {

                cipher = Cipher.getInstance("RSA"); // RSA/ECB/NoPadding

            } catch (NoSuchAlgorithmException e) {

                e.printStackTrace();

            } catch (NoSuchPaddingException e) {

                e.printStackTrace();

            }

        }

        

    

        /**

         * 生成密钥对

         * @param filePath 生成密钥的路径

         * @return

         */

        public static Map<String,String> generateKeyPair(String filePath){

            try {

                KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

                // 密钥位数

                keyPairGen.initialize(1024);

                // 密钥对

                KeyPair keyPair = keyPairGen.generateKeyPair();

                // 公钥

                PublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

                // 私钥

                PrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

                

                //得到公钥字符串

                String publicKeyString = getKeyString(publicKey);

                //得到私钥字符串

                String privateKeyString = getKeyString(privateKey);

                //将密钥对写入到文件

                FileWriter pubfw = new FileWriter(filePath+"/publicKey.keystore");

                FileWriter prifw = new FileWriter(filePath+"/privateKey.keystore");

                BufferedWriter pubbw = new BufferedWriter(pubfw);

                BufferedWriter pribw = new BufferedWriter(prifw);

                pubbw.write(publicKeyString);

                pribw.write(privateKeyString);

                pubbw.flush();

                pubbw.close();

                pubfw.close();

                pribw.flush();

                pribw.close();

                prifw.close();

                //将生成的密钥对返回

                Map<String,String> map = new HashMap<String,String>();

                map.put("publicKey",publicKeyString);

                map.put("privateKey",privateKeyString);

                return map;

            } catch (Exception e) {

                e.printStackTrace();

            }

            return null;

        }

        

        /**

         * 得到公钥方法,并对公钥进行base64处理

         *

         * @param key

         *            密钥字符串(经过base64编码)

         * @throws Exception

         */

        public static PublicKey getPublicKey(String key) throws Exception {

            byte[] keyBytes;

            keyBytes = (new BASE64Decoder()).decodeBuffer(key);

            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            PublicKey publicKey = keyFactory.generatePublic(keySpec);

            return publicKey;

        }

        

        /**

         * 得到私钥

         *

         * @param key

         *            密钥字符串(经过base64编码)

         * @throws Exception

         */

        public static PrivateKey getPrivateKey(String key) throws Exception {

            byte[] keyBytes;

            keyBytes = (new BASE64Decoder()).decodeBuffer(key);

            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

            return privateKey;

        }

        /**

         * 得到密钥字符串(经过base64编码)

         *

         * @return

         */

        public static String getKeyString(Key key) throws Exception {

            byte[] keyBytes = key.getEncoded();

            String s = (new BASE64Encoder()).encode(keyBytes);

            return s;

        }       

        

        /**

         * 使用公钥对明文进行加密,返回BASE64编码的字符串

         * @param publicKey

         * @param plainText

         * @return

         */

        public static String encrypt(PublicKey publicKey,String plainText){

            try {            

                cipher.init(Cipher.ENCRYPT_MODE, publicKey);

                byte[] enBytes = cipher.doFinal(plainText.getBytes());            

                return (new BASE64Encoder()).encode(enBytes);

            } catch (InvalidKeyException e) {

                e.printStackTrace();

            } catch (IllegalBlockSizeException e) {

                e.printStackTrace();

            } catch (BadPaddingException e) {

                e.printStackTrace();

            }

            return null;

        }

        

        /**

         * 使用keystore对明文进行加密

         * @param publicKeystore 公钥文件路径

         * @param plainText      明文

         * @return

         */

        public static String encrypt(String publicKeystore,String plainText){

            try {        

                

                FileReader fr = new FileReader(publicKeystore);

                BufferedReader br = new BufferedReader(fr);

                String publicKeyString="";

                String str;

                while((str=br.readLine())!=null){

                    publicKeyString+=str;

                }

                br.close();

                fr.close();

                System.out.println(publicKeyString.toString()+"***公钥");

                cipher.init(Cipher.ENCRYPT_MODE,getPublicKey(publicKeyString));

                byte[] enBytes = cipher.doFinal(plainText.getBytes());            

                return (new BASE64Encoder()).encode(enBytes);

            } catch (InvalidKeyException e) {

                e.printStackTrace();

            } catch (IllegalBlockSizeException e) {

                e.printStackTrace();

            } catch (BadPaddingException e) {

                e.printStackTrace();

            } catch (Exception e) {

                e.printStackTrace();

            }

            return null;

        }    

        

        /**

         * 使用私钥对明文密文进行解密

         * @param privateKey

         * @param enStr

         * @return

         */

        public static String decrypt(PrivateKey privateKey,String enStr){

            try {

                cipher.init(Cipher.DECRYPT_MODE, privateKey);

                byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));

                return new String(deBytes);

            } catch (InvalidKeyException e) {

                e.printStackTrace();

            } catch (IllegalBlockSizeException e) {

                e.printStackTrace();

            } catch (BadPaddingException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return null;

        }

        

        /**

         * 使用keystore对密文进行解密

         * @param privateKeystore  私钥路径

         * @param enStr                                         密文

         * @return

         */

        public static String decrypt(String privateKeystore,String enStr){

            try {

                FileReader fr = new FileReader(privateKeystore);

                BufferedReader br = new BufferedReader(fr);

                String privateKeyString="";

                String str;

                while((str=br.readLine())!=null){

                    privateKeyString+=str;

                }

                br.close();

                fr.close();            

                cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyString));

                byte[] deBytes = cipher.doFinal((new BASE64Decoder()).decodeBuffer(enStr));

                return new String(deBytes);

            } catch (InvalidKeyException e) {

                e.printStackTrace();

            } catch (IllegalBlockSizeException e) {

                e.printStackTrace();

            } catch (BadPaddingException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            } catch (Exception e) {

                e.printStackTrace();

            }

            return null;

        }

    }

    public class JavaToC {

        // 将 s 进行 BASE64 编码

        public static String getBASE64(String s) {

            if (s == null) return null;

            return (new sun.misc.BASE64Encoder()).encode( s.getBytes() );

        }

        // 将 BASE64 编码的字符串 s 进行解码

        public static String getFromBASE64(String s) {

            if (s == null) return null;

            BASE64Decoder decoder = new BASE64Decoder();

            try {

            byte[] b = decoder.decodeBuffer(s);

            return new String(b);

            } catch (Exception e) {

            return null;

            }

        }

        

        public static void testBASE64()

        {                   //  12345678876543211234567887654321123456788765432112345678876543211234567887654321

            //String s = "1234567887654321123456788765432112345678876543211234567887654321123456788765432112345678876543211234567887654321123456788765432112345678876543211234567887654321";

            String s = "java加密后的数据29875";

            System.out.println("length=" + s.length());

            String ans = getBASE64(s);

            System.out.println("length=" + ans.length());

            System.out.println(ans+"64编码数据");

            //String temp = "MTIzNDU2Nzg4NzY1NDMyMTEyMzQ1Njc4ODc2NTQzMjExMjM0NTY3ODg3NjU0MzIxMTIzNDU2Nzg4NzY1NDMyMTEyMzQ1Njc4ODc2NTQzMjE=";

            //String res = getFromBASE64(temp);

            String res = getFromBASE64(ans);

            System.out.println(res+"64解码后的数据");

            System.out.println("----------------------------------------");

        }

/*************************************加盐值随机数的加密解密**************************************************/

1加密方法:

package com.company.item.util;

import java.io.FileOutputStream;

import java.util.*;

import java.security.*;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.PBEKeySpec;

import javax.crypto.spec.PBEParameterSpec;

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

public class DEcode {

    private static BASE64Encoder encoder = new BASE64Encoder();

    private static BASE64Decoder decoder = new BASE64Decoder();

    public static void main(String[] args) throws Exception {

     String s="welcome to java";

        String str = "123456";//加密口令

        char[] passwd = str.toCharArray();

        PBEKeySpec pbks = new PBEKeySpec(passwd);

        SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

        SecretKey k = kf.generateSecret(pbks);//生成秘钥

        

        byte[] salt = new byte[8];//生成随机数 盐:必须是8个元素的字节数组

        Random ran = new Random();

         ran.nextBytes(salt);

         

         Cipher cp = Cipher.getInstance("PBEWithMD5AndDES");//创建并初始化密码器

         

        PBEParameterSpec ps = new PBEParameterSpec(salt,1000);//为了提高破解难度,增加盐的迭代次数 1000次

        

        cp.init(Cipher.ENCRYPT_MODE, k,ps);//初始化加密器

        byte[] ptext = s.getBytes("utf-8");//获取要加密的字符串,转为字节形式,并指定字符集

        byte[] ctext = cp.doFinal(ptext);//调用doFinal方法对传入的文本进行加密

       

       FileOutputStream fos = new FileOutputStream("PBEEnc.dat");

       fos.write(salt);

       fos.write(ctext);//将盐和加密有的文本写入PBEEnc.dat文件中

   

       for(int i=0;i<salt.length;i++){

           System.out.println(salt[i]+",");

       }

        System.out.println("");

        for(int i=0;i<ctext.length;i++){

        System.out.println(ctext[i]+",");

        }

        

    }

   

}

2**************解密方法:

package com.company.item.util;

import java.io.FileInputStream;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.PBEKeySpec;

import javax.crypto.spec.PBEParameterSpec;

public class EDcode {

    public static void main(String args[]) throws Exception {

    

    String str = "123456";//解密口令与加密口令一

    char[] passwd = str.toCharArray();

    PBEKeySpec pbks = new PBEKeySpec(passwd);

    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

    SecretKey k = kf.generateSecret(pbks);

    byte[] salt = new byte[8];

    FileInputStream f = new FileInputStream("PBEEnc.dat");

    f.read(salt);

    int num = f.available();

    byte[] ctext = new byte[num];

    f.read(ctext);

    Cipher cp = Cipher.getInstance("PBEWithMD5AndDES");

    PBEParameterSpec ps = new PBEParameterSpec(salt, 1000);

    cp.init(Cipher.DECRYPT_MODE, k,ps);

    byte[] ptext = cp.doFinal(ctext);

    System.out.println(new String(ptext));

    }

}

      

        public static void main(String[] args)

        {

            RSAUtil util = new RSAUtil();

             util.generateKeyPair("key");

            //String cp = "M04d2l9MyDiUUfAQ32FdphesAQJHZUk0dEsYQcU06IJo/RCF311GtJXBK1FhapITIvjkpsiz9NR25AGEFPdz4bs2o5/F0QIj5yFA+biLxgcFrDpd5gSWI1F8V7wbsl06tNLNOVihFfzl8xWbHMVqPhY3tj8Vu/QHEPPnx7mvHlc="; // cp保存的是由openssl加密后的结果(包括了对密文的base64编码)

            String cipher = util.encrypt("D:/WorkSpaces/CSTSystem/key/publicKey.keystore", "hello world");//公钥加密

            //privateKey

            JavaToC.testBASE64();

            String recover = util.decrypt("D:/WorkSpaces/CSTSystem/key/privateKey.keystore", cipher);//私钥解密

            System.out.println("加密后cipher=" + cipher);

            System.out.println("解密后recover=" + recover);        

        }

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java加密解密