DES加密解密---可执行完整版------(附2个版本RSA加密解密)

来源:互联网 发布:中国软件服务市场 编辑:程序博客网 时间:2024/05/21 17:56

因为作业不会写,大中午的难过得大哭了一场。后来没放弃·~用了2个下午的时间,终于实现了完整的DES加密解密。

        算法看明白后还有实现,也是比较简单,做下去之后,发现常用的很多都不会,一边重新学一边做。

       写程序,不是在和什么做斗争,是时时刻刻都要面对焦虑、无人可求助、总是觉得无能为力的自己,只是需要一点耐心和一点平常心,慢慢做,总会解决的。


期间参考了这几个地方:

http://www.cnblogs.com/langtianya/p/3715975.html
DES加密C
http://blog.csdn.net/xumaojun/article/details/17675905   
RSA加密
http://blog.sina.com.cn/s/blog_4f51dac40100u0tf.html
RSA java加密
http://blog.csdn.net/centralperk/article/details/8558678




------------------------------DES加密解密---------------------------(写得比较复杂,但是比较容易理解,import没贴上,可执行,数据表事先准备好)----------------------------------------

//DES加密 main

public class TestJia {  

    public static void main(String[] args) {  

        showHomwork showHomwork = new showHomwork();

        ArrayList<homwork> list = showHomwork.getAllStus();

        for(homwork s: list){  //遍历集合数据  

   System.out.println("原数据:"+s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

        }  

        

        ArrayList<homwork> listMi = showHomwork.setIntoDESAll(list);//加密

        System.out.println("加密成功");

    }

}  

 

 

//DES解密 main

public class TestJie {  

    public static void main(String[] args) {  

        showHomwork showHomwork = new showHomwork();

        ArrayList<homwork> list = showHomwork.getAllStus();

        for(homwork s: list){  //遍历集合数据  

            System.out.println("原数据:"+s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

          }  

        ArrayList<homwork> listJie = showHomwork.setOutDESAll(list);//解密

        System.out.println("解密成功");        

    }

}  

 

 

 

 

 

 

 

 

 

 

//测试加解密

public class DesUtil {  

    private final static String DES = "DES";  

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

        String data = "hello <xml > 测试!";  

        String key = "!@#$%qqqqqqwwww";  

        System.out.println(encrypt(data, key));  

        System.out.println(decrypt(encrypt(data, key), key));  

    }  

       

    /**  

     * Description 根据键值进行加密  

     * @param data   

     * @param key  加密键byte数组  

     * @return  

     * @throws Exception  

     */  

    public static String encrypt(String data, String key) throws Exception {  

        byte[] bt = encrypt(data.getBytes(), key.getBytes());  

        String strs = new BASE64Encoder().encode(bt);  

        return strs;  

    }  

   

    /**  

     * Description 根据键值进行解密  

     * @param data  

     * @param key  加密键byte数组  

     * @return  

     * @throws IOException  

     * @throws Exception  

     */  

    public static String decrypt(String data, String key) throws IOException,  

            Exception {  

        if (data == null)  

            return null;  

        BASE64Decoder decoder = new BASE64Decoder();  

        byte[] buf = decoder.decodeBuffer(data);  

        byte[] bt = decrypt(buf,key.getBytes());  

        return new String(bt);  

    }  

   

    /**  

     * Description 根据键值进行加密  

     * @param data  

     * @param key  加密键byte数组  

     * @return  

     * @throws Exception  

     */  

    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {  

        // 生成一个可信任的随机数源  

        SecureRandom sr = new SecureRandom();  

        // 从原始密钥数据创建DESKeySpec对象  

        DESKeySpec dks = new DESKeySpec(key);  

        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象  

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);  

        SecretKey securekey = keyFactory.generateSecret(dks);  

        // Cipher对象实际完成加密操作  

        Cipher cipher = Cipher.getInstance(DES);  

        // 用密钥初始化Cipher对象  

        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);  

        return cipher.doFinal(data);  

    }  

       

       

    /**  

     * Description 根据键值进行解密  

     * @param data  

     * @param key  加密键byte数组  

     * @return  

     * @throws Exception  

     */  

    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {  

        // 生成一个可信任的随机数源  

        SecureRandom sr = new SecureRandom();  

        // 从原始密钥数据创建DESKeySpec对象  

        DESKeySpec dks = new DESKeySpec(key);  

        // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象  

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);  

        SecretKey securekey = keyFactory.generateSecret(dks);  

        // Cipher对象实际完成解密操作  

        Cipher cipher = Cipher.getInstance(DES);  

        // 用密钥初始化Cipher对象  

        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);  

        return cipher.doFinal(data);  

    }  

}

 

 

//连接数据库 查询修改

public class showHomwork {

 public static void main(String[] args) {  

        ArrayList<homwork> list = getAllStus();  

        if(list.size() == 0){  

            System.out.println("暂无数据");  

        }else{  

     for(homwork s: list){  //遍历集合数据     System.out.println(s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

            }  

        }  

  

    }  

      

    //采用集合的方法,返回数据集合,查询  

    public static ArrayList<homwork> getAllStus(){  

        ArrayList<homwork> stulist = new ArrayList<homwork>();    

        String url = "com.mysql.jdbc.Driver"; //加载驱动包  

        String connectSql = "jdbc:mysql://localhost:3306/demo"; //链接MySQL数据库  

        String sqlUser = "root"; //数据库账号  

        String sqlPasswd = "x5"; //你的数据库密码  

        Connection con = null;  

        PreparedStatement psm = null;  

        ResultSet rs = null;  

          

        System.out.println("连接数据库成功!");

        try {  

            //加载驱动包  

            Class.forName(url);  

            //连接MYSQL  

            con = DriverManager.getConnection(connectSql,sqlUser,sqlPasswd);  

            //执行MYSQL语句  

            psm = con.prepareStatement("select * from homwork");  

            rs = psm.executeQuery();  

            System.out.println("姓名"+"\t"+"身份证号码"+"\t"+"出生日期"+"\t"+"薪资");  

            while(rs.next()){  

             homwork s = new homwork();  

                s.setName(rs.getString(3));

                s.setIdCardNo(rs.getString(2));

                s.setBirthday(rs.getString(5));

                s.setPay(rs.getString(7));

                stulist.add(s);   

            }  

              

            //关闭数据库连接  

            rs.close();  

            psm.close();  

            con.close();  

              

        } catch (Exception e) {  

            System.out.println("显示所有数据报错,原因:"+e.getMessage());  

        }  

        return stulist;   

    }  

      

    

  //采用集合的方法,修改数据内容,DES加密

    public  ArrayList<homwork>  setIntoDESAll(ArrayList<homwork> homworklist){  

        

        String url = "com.mysql.jdbc.Driver"; //加载驱动包  

       String connectSql = "jdbc:mysql://localhost:3306/demo"; //链接MySQL

        String sqlUser = "root"; //数据库账号  

        String sqlPasswd = "x5"; //你的数据库密码  

          

        Connection con = null;  

        PreparedStatement psm = null;  

        ResultSet rs = null;  

          

        System.out.println("连接数据库成功!");

        try {  

            //加载驱动包  

            Class.forName(url);  

            //连接MYSQL  

          con = DriverManager.getConnection(connectSql,sqlUser,sqlPasswd);  

            //执行MYSQL语句  

            psm = con.prepareStatement("select * from homwork");  

            rs = psm.executeQuery();  

 

            if(homworklist.size() == 0){  

             return (ArrayList<homwork>) homworklist;

            }    

            String key = "我是加密秘钥";  

            for(homwork s: (ArrayList<homwork>)homworklist){  //遍历集合数据  

                DesUtil des = new DesUtil();

                String birthdaykey = null;

                String paykey = null;

     try {

     birthdaykey = des.encrypt(s.getBirthday(), key);

     paykey = des.encrypt(s.getPay(), key);

     } catch (Exception e) {

     e.printStackTrace();

     }

 

     String updateNamesql = "UPDATE homwork  SET birthday=REPLACE(birthday,'"+s.getBirthday() +"','"+birthdaykey+"'); ";

     String updatePaysql = "UPDATE homwork  SET pay=REPLACE(pay,'"+s.getPay() +"','"+paykey+"'); ";

    

PreparedStatement stmt = con.prepareStatement(updateNamesql);

PreparedStatement stmt2 = con.prepareStatement(updatePaysql);

            stmt.executeUpdate();

            stmt2.executeUpdate();

                System.out.println("加密生日成功!加密生日为:"+birthdaykey+ "加密工资成功!加密工资为:"+paykey);

            }  

            

            //关闭数据库连接  

            rs.close();  

            psm.close();  

            con.close();  

              

        } catch (Exception e) {  

            System.out.println("显示所有数据报错,原因:"+e.getMessage());  

        }     

        return  homworklist;   

    }  

    

    //采用集合的方法,修改数据内容,DES解密

public  ArrayList<homwork>  setOutDESAll(ArrayList<homwork> homworklist){  

        

        String url = "com.mysql.jdbc.Driver"; //加载驱动包  

     String connectSql = "jdbc:mysql://localhost:3306/demo"; //链接MySQL         String sqlUser = "root"; //数据库账号  

        String sqlPasswd = "x5"; //你的数据库密码  

          

        Connection con = null;  

        PreparedStatement psm = null;  

        ResultSet rs = null;  

          

        System.out.println("连接数据库成功!");

        try {  

            //加载驱动包  

            Class.forName(url);  

            //连接MYSQL  

         con = DriverManager.getConnection(connectSql,sqlUser,sqlPasswd);  

            //执行MYSQL语句  

            psm = con.prepareStatement("select * from homwork");  

            rs = psm.executeQuery();  

 

            if(homworklist.size() == 0){  

             return (ArrayList<homwork>) homworklist;

            }    

            String key = "我是加密秘钥";  

            for(homwork s: (ArrayList<homwork>)homworklist){  //遍历集合数据         

                DesUtil des = new DesUtil();

                String birthdaykey = null;

                String paykey = null;

     try {

     birthdaykey = des.decrypt(s.getBirthday(), key);

     paykey =  des.decrypt(s.getPay(), key);

     } catch (Exception e) {

     e.printStackTrace();

     }

 

     String updatesql = "UPDATE homwork  SET birthday=REPLACE(birthday,'"+s.getBirthday() +"','"+birthdaykey+"'); ";

     String updatesql2 = "UPDATE homwork  SET pay=REPLACE(pay,'"+s.getPay() +"','"+paykey+"'); ";

    

     PreparedStatement stmt = con.prepareStatement(updatesql);

    PreparedStatement stmt2 = con.prepareStatement(updatesql2);

            stmt.executeUpdate();

            stmt2.executeUpdate();

System.out.println("解密生日成功!解密生日为:"+birthdaykey);

System.out.println("解密工资成功!解密工资为:"+paykey);

            }  

            

            //关闭数据库连接  

            rs.close();  

            psm.close();  

            con.close();  

              

        } catch (Exception e) {  

 System.out.println("显示所有数据报错,原因:"+e.getMessage());  

        }     

        return  homworklist;   

    }  

    

}


//实体类

public class homwork {

private int Id;

private String idCardNo;

private String name;

private String gender;

private String birthday;

private String workday;

private String pay;

public int getId() {

return Id;

}

public void setId(int id) {

Id = id;

}

public String getIdCardNo() {

return idCardNo;

}

public void setIdCardNo(StringidCardNo) {

this.idCardNo =idCardNo;

}

public String getName() {

return name;

}

public void setName(Stringname) {

this.name =name;

}

public String getGender() {

return gender;

}

public void setGender(Stringgender) {

this.gender =gender;

}

public String getBirthday() {

return birthday;

}

public void setBirthday(Stringbirthday) {

this.birthday =birthday;

}

public String getWorkday() {

return workday;

}

public void setWorkday(Stringworkday) {

this.workday =workday;

}

public String getPay() {

return pay;

}

public void setPay(Stringpay) {

this.pay =pay;

}

public homwork(){

}

public homwork(int Id,StringidCardNo,String name,String gender, String birthday,String workday,String pay) {  

        this.Id =Id;

        this.idCardNo =idCardNo;

        this.name =name;

        this.gender =gender;

        this.birthday =birthday;

        this.workday =workday;

        this.pay =pay;

    }  

}

 

----------------------------------------------------------------------------结束----------------(结果就不贴了)--------------------------------------------------------------------------------

-------------------------------------------------------------------RSA加密解密------------(加密可执行,解密出了点小问题,没来得及调整)---------------------------------------------------------


RSA加密

 

public class main {

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

        

todoRSA todoRSA = new todoRSA();

        ArrayList<homwork> list = todoRSA.getAllStus();

        for(homwork s: list){  //遍历集合数据  

            System.out.println("原数据:"+s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

        }

        

        ArrayList<homwork> miRSA = todoRSA.setIntoRASAll(list);

        System.out.println("加密成功");

        for(homwork s: miRSA){  //遍历集合数据  

            System.out.println("加密后数据:"+s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

        }          

    }  

}

 

RSA解密

 public class mainJie {

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

        

        

todoRSA todoRSA = new todoRSA();

        ArrayList<homwork> list = todoRSA.getAllStus();

        for(homwork s: list){  //遍历集合数据  

            System.out.println("原数据:"+s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

        }

        

        ArrayList<homwork> jieRSA = todoRSA.setOutRSA(list);

        System.out.println("解密成功");

        for(homwork s: jieRSA){  //遍历集合数据  

            System.out.println("解密后数据:"+s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

        }  

 

    }  

}

 

public class RSAUtils {

 /**

     * 生成公钥和私钥

     * @throws NoSuchAlgorithmException  

     *

     */  

    public static HashMap<String, Object> getKeys()throws NoSuchAlgorithmException{  

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

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

        keyPairGen.initialize(1024);  

        KeyPair keyPair = keyPairGen.generateKeyPair();  

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

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

        map.put("public",publicKey);  

        map.put("private",privateKey);  

        return map;  

    }  

    /**

     * 使用模和指数生成RSA公钥

     * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA

     * /None/NoPadding】

     *  

     * @param modulus

     *            模

     * @param exponent

     *            指数

     * @return 

     */  

    public static RSAPublicKey getPublicKey(Stringmodulus, String exponent) {  

        try {  

            BigInteger b1 = new BigInteger(modulus);  

            BigInteger b2 = new BigInteger(exponent);  

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

            RSAPublicKeySpec keySpec =new RSAPublicKeySpec(b1,b2);  

            return (RSAPublicKey)keyFactory.generatePublic(keySpec);  

        } catch (Exceptione) {  

            e.printStackTrace();  

            return null;  

        }  

    }  

  

    /**

     * 使用模和指数生成RSA私钥

     * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA

     * /None/NoPadding】

     *  

     * @param modulus

     *            模

     * @param exponent

     *            指数

     * @return 

     */  

    public static RSAPrivateKey getPrivateKey(Stringmodulus, String exponent) {  

        try {  

            BigInteger b1 = new BigInteger(modulus);  

            BigInteger b2 = new BigInteger(exponent);  

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

            RSAPrivateKeySpec keySpec =new RSAPrivateKeySpec(b1,b2);  

            return (RSAPrivateKey)keyFactory.generatePrivate(keySpec);  

        } catch (Exceptione) {  

            e.printStackTrace();  

            return null;  

        }  

    }  

  

    /**

     * 公钥加密

     *  

     * @param data

     * @param publicKey

     * @return 

     * @throws Exception

     */  

    public static String encryptByPublicKey(Stringdata, RSAPublicKey publicKey)  

            throws Exception {  

        Cipher cipher = Cipher.getInstance("RSA");  

        cipher.init(Cipher.ENCRYPT_MODE,publicKey);  

        // 模长  

        int key_len =publicKey.getModulus().bitLength() / 8;  

        // 加密数据长度 <= 模长-11  

        String[] datas = splitString(data,key_len - 11);  

        String mi = "";  

        //如果明文长度大于模长-11则要分组加密  

        for (String s : datas) {  

            mi += bcd2Str(cipher.doFinal(s.getBytes()));  

        }  

        return mi;  

    }  

  

    /**

     * 私钥解密

     *  

     * @param data

     * @param privateKey

     * @return 

     * @throws Exception

     */  

    public static String decryptByPrivateKey(Stringdata, RSAPrivateKey privateKey)  

            throws Exception {  

        Cipher cipher = Cipher.getInstance("RSA");  

        cipher.init(Cipher.DECRYPT_MODE,privateKey);  

        //模长  

        int key_len =privateKey.getModulus().bitLength() / 8;  

        byte[] bytes = data.getBytes();  

        byte[] bcd = ASCII_To_BCD(bytes,bytes.length);  

        System.err.println(bcd.length);  

        //如果密文长度大于模长则要分组解密  

        String ming = "";  

        byte[][] arrays = splitArray(bcd,key_len);  

        for(byte[]arr : arrays){  

            ming += new String(cipher.doFinal(arr));  

        }  

        return ming;  

    }  

    /**

     * ASCII码转BCD码

     *  

     */  

    public static byte[] ASCII_To_BCD(byte[]ascii, int asc_len) {  

        byte[] bcd = new byte[asc_len / 2];  

        int j = 0;  

        for (int i = 0;i < (asc_len + 1) / 2;i++) {  

            bcd[i] =asc_to_bcd(ascii[j++]);  

            bcd[i] = (byte) (((j >=asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));  

        }  

        return bcd;  

    }  

    public static byte asc_to_bcd(byte asc) {  

        byte bcd;  

  

        if ((asc >='0') && (asc <='9'))  

            bcd = (byte) (asc -'0');  

        else if ((asc >='A') && (asc <='F'))  

            bcd = (byte) (asc -'A' + 10);  

        else if ((asc >='a') && (asc <='f'))  

            bcd = (byte) (asc -'a' + 10);  

        else  

            bcd = (byte) (asc - 48);  

        return bcd;  

    }  

    /**

     * BCD转字符串

     */  

    public static String bcd2Str(byte[]bytes) {  

        char temp[] =new char[bytes.length * 2],val;  

  

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

            val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);  

            temp[i * 2] = (char) (val > 9 ?val + 'A' - 10 : val + '0');  

  

            val = (char) (bytes[i] & 0x0f);  

            temp[i * 2 + 1] = (char) (val > 9 ?val + 'A' - 10 : val + '0');  

        }  

        return new String(temp);  

    }  

    /**

     * 拆分字符串

     */  

    public static String[] splitString(Stringstring, int len) {  

        int x =string.length() / len;  

        int y =string.length() % len;  

        int z = 0;  

        if (y != 0) {  

            z = 1;  

        }  

        String[] strings = new String[x +z];  

        String str = "";  

        for (int i=0;i<x+z;i++) {  

            if (i==x+z-1 &&y!=0) {  

                str = string.substring(i*len,i*len+y);  

            }else{  

                str = string.substring(i*len,i*len+len);  

            }  

            strings[i] =str;  

        }  

        return strings;  

    }  

    /**

     *拆分数组  

     */  

    public static byte[][] splitArray(byte[]data,int len){  

        int x =data.length /len;  

        int y =data.length %len;  

        int z = 0;  

        if(y!=0){  

            z = 1;  

        }  

        byte[][] arrays = new byte[x+z][];  

        byte[] arr;  

        for(int i=0;i<x+z;i++){  

            arr = new byte[len];  

            if(i==x+z-1 &&y!=0){  

                System.arraycopy(data,i*len,arr, 0, y);  

            }else{  

                System.arraycopy(data,i*len,arr, 0, len);  

            }  

            arrays[i] =arr;  

        }  

        return arrays;  

    }  

}

 

 

public class todoRSA {

 public static void main(String[]args) {  

        ArrayList<homwork> list = getAllStus();  

          

        if(list.size() == 0){  

            System.out.println("暂无数据");  

        }else{  

            for(homworks: list){  //遍历集合数据  

                System.out.println(s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

            }  

        }  

  

    }  

      

    //采用集合的方法,返回数据集合,查询  

    public static ArrayList<homwork> getAllStus(){  

        ArrayList<homwork> stulist =new ArrayList<homwork>();  

          

        String url = "com.mysql.jdbc.Driver"; //加载驱动包  

        String connectSql = "jdbc:mysql://localhost:3306/demo"; //链接MySQL数据库  

        String sqlUser = "root"; //数据库账号  

        String sqlPasswd = "x5"; //你的数据库密码  

          

        Connection con = null;  

        PreparedStatement psm = null;  

        ResultSet rs = null;  

          

        System.out.println("连接数据库成功!");

        try {  

            //加载驱动包  

            Class.forName(url);  

            //连接MYSQL  

            con = DriverManager.getConnection(connectSql,sqlUser,sqlPasswd);  

            //执行MYSQL语句  

            psm = con.prepareStatement("select * from homwork");  

            rs = psm.executeQuery();  

            System.out.println("姓名"+"\t"+"身份证号码"+"\t"+"出生日期"+"\t"+"薪资");  

            while(rs.next()){  

             homwork s = new homwork();  

                s.setName(rs.getString(3));

                s.setIdCardNo(rs.getString(2));

                s.setBirthday(rs.getString(5));

                s.setPay(rs.getString(7));

                stulist.add(s);   

            }  

              

            //关闭数据库连接  

            rs.close();  

            psm.close();  

            con.close();  

              

        } catch (Exceptione) {  

            System.out.println("显示所有数据报错,原因:"+e.getMessage());  

        }  

        return stulist;   

    }  

      

    

  //采用集合的方法,修改数据内容,RAS加密

    public  ArrayList<homwork>  setIntoRASAll(ArrayList<homwork>homworklist){  

        

        String url = "com.mysql.jdbc.Driver"; //加载驱动包  

        String connectSql = "jdbc:mysql://localhost:3306/demo"; //链接MySQL数据库  

        String sqlUser = "root"; //数据库账号  

        String sqlPasswd = "x5"; //你的数据库密码  

          

        Connection con = null;  

        PreparedStatement psm = null;  

        ResultSet rs = null;  

          

        System.out.println("连接数据库成功!");

        try {  

            //加载驱动包  

            Class.forName(url);  

            //连接MYSQL  

            con = DriverManager.getConnection(connectSql,sqlUser,sqlPasswd);  

            //执行MYSQL语句  

            psm = con.prepareStatement("select * from homwork");  

            rs = psm.executeQuery();  

 

            if(homworklist.size() == 0){  

             return (ArrayList<homwork>)homworklist;

            }    

 

            HashMap<String, Object> map = RSAUtils.getKeys();  

            //生成公钥和私钥  

            RSAPublicKey publicKey = (RSAPublicKey)map.get("public");  

            //模  

            String modulus = publicKey.getModulus().toString();  

            //公钥指数  

            String public_exponent =publicKey.getPublicExponent().toString();  

            

            for(homworks: (ArrayList<homwork>)homworklist){  //遍历集合数据  

              //明文  

            String mingBirth = s.getBirthday();  

                    String mingPay =s.getPay();

            //使用模和指数生成公钥和私钥  

            RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus,public_exponent);  

 

            //加密后的密文  

            String miBirth = RSAUtils.encryptByPublicKey(mingBirth,pubKey);  

            String miPay = RSAUtils.encryptByPublicKey(mingPay,pubKey);  

            

             //数据库执行

     String updateNamesql = "UPDATE homwork  SET birthday=REPLACE(birthday,'"+s.getBirthday() +"','"+miBirth+"'); ";

     String updatePaysql = "UPDATE homwork  SET pay=REPLACE(pay,'"+s.getPay() +"','"+miPay+"'); ";

    

            PreparedStatement stmt =con.prepareStatement(updateNamesql);

            PreparedStatement stmt2 =con.prepareStatement(updatePaysql);

            stmt.executeUpdate();

            stmt2.executeUpdate();

                System.out.println("加密生日成功!加密生日为:"+miBirth+"加密工资成功!加密工资为:"+miPay);

            }  

            

            //关闭数据库连接  

            rs.close();  

            psm.close();  

            con.close();  

              

        } catch (Exceptione) {  

            System.out.println("显示所有数据报错,原因:"+e.getMessage());  

        }     

        return  homworklist;   

    }  

    

    

  //采用集合的方法,修改数据内容,RSA解密

    public  ArrayList<homwork>  setOutRSA(ArrayList<homwork>homworklist){  

        

        String url = "com.mysql.jdbc.Driver"; //加载驱动包  

        String connectSql = "jdbc:mysql://localhost:3306/demo"; //链接MySQL数据库  

        String sqlUser = "root"; //数据库账号  

        String sqlPasswd = "x5"; //你的数据库密码  

          

        Connection con = null;  

        PreparedStatement psm = null;  

        ResultSet rs = null;  

 

        System.out.println("连接数据库成功!");

        try {  

            //加载驱动包  

            Class.forName(url);  

            //连接MYSQL  

            con = DriverManager.getConnection(connectSql,sqlUser,sqlPasswd);  

            //执行MYSQL语句  

            psm = con.prepareStatement("select * from homwork");  

            rs = psm.executeQuery();  

 

            if(homworklist.size() == 0){  

             return (ArrayList<homwork>)homworklist;

            }    

            

            for(homworks: (ArrayList<homwork>)homworklist){  //遍历集合数据         

              HashMap<String, Object> map = RSAUtils.getKeys();  

              //生成公钥和私钥  

              RSAPublicKey publicKey = (RSAPublicKey)map.get("public");  

              RSAPrivateKey privateKey = (RSAPrivateKey)map.get("private");  

              //模  

              String modulus = publicKey.getModulus().toString();

              //私钥指数  

              String private_exponent =privateKey.getPrivateExponent().toString();  

              //使用模和指数生成私钥  

              RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus,private_exponent);  

              

              String miBirth=s.getBirthday();

              String miPay=s.getPay();

 

            //解密后的明文  

            String jieBirth = RSAUtils.decryptByPrivateKey(miBirth,priKey);  

            String jiePay = RSAUtils.decryptByPrivateKey(miPay,priKey);  

            

     String updatesql = "UPDATE homwork  SET birthday=REPLACE(birthday,'"+s.getBirthday() +"','"+jieBirth+"'); ";

     String updatesql2 = "UPDATE homwork  SET pay=REPLACE(pay,'"+s.getPay() +"','"+jiePay+"'); ";

    

            PreparedStatement stmt =con.prepareStatement(updatesql);

            PreparedStatement stmt2 =con.prepareStatement(updatesql2);

            

            stmt.executeUpdate();

            stmt2.executeUpdate();

            

                System.out.println("解密生日成功!解密生日为:"+jieBirth);

                System.out.println("解密工资成功!解密工资为:"+jiePay);

            }  

            

            //关闭数据库连接  

            rs.close();  

            psm.close();  

            con.close();  

              

        } catch (Exceptione) {  

            System.out.println("显示所有数据报错,原因:"+e.getMessage());  

        }     

        return  homworklist;   

    }  

    

    

    public  ArrayList  Key(StringMing, String Mi) throws Exception{

      HashMap<String, Object> map;

try {

map = RSAUtils.getKeys();

//生成公钥和私钥  

        RSAPublicKey publicKey = (RSAPublicKey)map.get("public");  

        RSAPrivateKey privateKey = (RSAPrivateKey)map.get("private");

        //模  

        String modulus = publicKey.getModulus().toString();  

        //公钥指数  

        String public_exponent = publicKey.getPublicExponent().toString();  

        //私钥指数  

        String private_exponent = privateKey.getPrivateExponent().toString();  

        //使用模和指数生成公钥和私钥  

        RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus,public_exponent);  

        RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus,private_exponent);

        //加密后的密文  

        String jiaMi = RSAUtils.encryptByPublicKey(Ming,pubKey);

        //解密后的明文  

        String jieMing = RSAUtils.decryptByPrivateKey(Mi,priKey);  

        ArrayList keyList= new ArrayList();

        keyList.add(jiaMi);

        keyList.add(jieMing);

        return keyList;

} catch (NoSuchAlgorithmExceptione) {

e.printStackTrace();

}

return null;  

    }     

}

 

----------------------------------------------------------------RSA加密解密,结束---------------------------------------------------------------------



--------------------------------------------------------RSA 加密解密,另一种写法,没仔细尝试----------------------------------------------------

RSA加密

public class testRSAmainJiami {

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

        ArrayList<homwork> list = homeworkQuery.getAllStus();  

        keyofRSA testInOutRSA= new keyofRSA();  

 

        if(list.size() == 0){  

            System.out.println("暂无数据");  

            return;

        }  

        

        for(homwork s: list){  //遍历集合数据  

            System.out.println(s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

          //加密String

            String birth = testInOutRSA.stringInRSA(s.getBirthday());

            String pay = testInOutRSA.stringInRSA(s.getPay());

            s.setBirthday(birth);

            s.setPay(pay);

            savehomwork.saveHomwork(s);

        }  

 

    }  

}

 

RSA解密

public class testRSAJiemi {

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

        ArrayList<homwork> list = homeworkQuery.getAllStus();  

        keyofRSA testInOutRSA= new keyofRSA();  

 

        if(list.size() == 0){  

            System.out.println("暂无数据");  

            return;

        }  

        

        for(homwork s: list){  //遍历集合数据  

            System.out.println(s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

          //加密String

            String birth = testInOutRSA.stringOutRSA(s.getBirthday());

            String pay = testInOutRSA.stringOutRSA(s.getPay());

            s.setBirthday(birth);

            s.setPay(pay);

            savehomwork.saveHomwork(s);

        }  

 

    }  

}

 

查找

public class homeworkQuery {

 public static void main(String[] args) {  

        ArrayList<homwork> list = getAllStus();  

          

        if(list.size() == 0){  

            System.out.println("暂无数据");  

        }else{  

            for(homwork s: list){  //遍历集合数据  

                System.out.println(s.getName()+"\t"+s.getIdCardNo()+"\t"+s.getBirthday()+"\t"+s.getPay());  

            }  

        }  

  

    }  

 public static ArrayList<homwork> getAllStus(){

 ArrayList<homwork> stulist = new ArrayList<homwork>();  

         

        String url = "com.mysql.jdbc.Driver"; //加载驱动包  

        String connectSql = "jdbc:mysql://localhost:3306/demo"; //链接MySQL数据库  

        String sqlUser = "root"; //数据库账号  

        String sqlPasswd = "x5"; //你的数据库密码  

          

        Connection con = null;  

        PreparedStatement psm = null;  

        ResultSet rs = null;  

          

        System.out.println("连接数据库成功!");

        try {  

            //加载驱动包  

            Class.forName(url);  

            //连接MYSQL  

            con = DriverManager.getConnection(connectSql,sqlUser,sqlPasswd);  

            //执行MYSQL语句  

            psm = con.prepareStatement("select * from homwork");  

            rs = psm.executeQuery();  

            System.out.println("姓名"+"\t"+"身份证号码"+"\t"+"出生日期"+"\t"+"薪资");  

            while(rs.next()){  

             homwork s = new homwork();  

                s.setName(rs.getString(3));

                s.setIdCardNo(rs.getString(2));

                s.setBirthday(rs.getString(5));

                s.setPay(rs.getString(7));

                stulist.add(s);   

            }  

           

            //修改数据的代码

            String sql="update homwork set pay=100 where Id=1 ";//生成一条mysql语句

            Statement stmt=con.createStatement();//创建一个Statement对象

            stmt.executeUpdate(sql);//执行SQL语句

            System.out.println("修改数据库成功!!!");

           

            //关闭数据库连接  

            rs.close();  

            psm.close();  

            con.close();  

            

        } catch (Exception e) {  

            System.out.println("显示所有数据报错,原因:"+e.getMessage());  

        }       

        return stulist;   

    }

}

 

public class keyofRSA {

public RSAPublicKey publicKey() throws NoSuchAlgorithmException{            //创建公钥KEY

HashMap<String, Object> map = RSAUtils.getKeys();  

    //生成公钥

    RSAPublicKey publicKey = (RSAPublicKey) map.get("public");  

    return publicKey;

    }

public RSAPrivateKey privateKey() throws NoSuchAlgorithmException{            //创建私钥KEY

HashMap<String, Object> map = RSAUtils.getKeys();  

    //生成私钥

    RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");

    return privateKey;

    }

     

    //加密String

    public String stringInRSA(String stringIn) throws Exception{  

        System.out.println("明文为:"+stringIn);//明文

        RSAPublicKey publicKey =  publicKey();

        String modulus = publicKey.getModulus().toString();  //模  

        String public_exponent = publicKey.getPublicExponent().toString();   //公钥指数     

        RSAPublicKey pubKey = RSAUtils.getPublicKey(modulus, public_exponent);  //使用模和指数生成公钥和私钥

        String mi = RSAUtils.encryptByPublicKey(stringIn, pubKey);   //加密后的密文  

        System.err.println("加密后的密文:"+mi);  

        return mi;

    }

    

    //解密String

    public String stringOutRSA(String stringMi) throws Exception{  

     RSAPrivateKey privateKey =  privateKey();

     String modulus = privateKey.getModulus().toString();  //模  

     //私钥指数  

        String private_exponent = privateKey.getPrivateExponent().toString();

        //使用模和指数生成公钥和私钥  

        RSAPrivateKey priKey = RSAUtils.getPrivateKey(modulus, private_exponent);

        String ming = RSAUtils.decryptByPrivateKey(stringMi, priKey);  

        System.err.println("解密后的密文:"+ming);  

        return ming;

    }

 

}

 

 

//保存

public class savehomwork {

public static ArrayList<homwork> saveHomwork(homwork homwork){

 ArrayList<homwork> stulist = new ArrayList<homwork>();  

        

        String url = "com.mysql.jdbc.Driver"; //加载驱动包  

        String connectSql = "jdbc:mysql://localhost:3306/demo"; //链接MySQL数据库  

        String sqlUser = "root"; //数据库账号  

        String sqlPasswd = "x5"; //你的数据库密码  

          

        Connection con = null;  

        PreparedStatement psm = null;  

        ResultSet rs = null;  

          

        System.out.println("连接数据库成功!");

        try {  

            //加载驱动包  

            Class.forName(url);  

            //连接MYSQL  

            con = DriverManager.getConnection(connectSql,sqlUser,sqlPasswd);  

 

            System.out.println("修改数据库成功!!!");

            

            String updateNamesql = "UPDATE homwork  SET birthday="+homwork.getBirthday() +"; ";

     String updatePaysql = "UPDATE homwork  SET pay="+homwork.getPay() +"; ";

    

            PreparedStatement stmt = con.prepareStatement(updateNamesql);

            PreparedStatement stmt2 = con.prepareStatement(updatePaysql);

            stmt.executeUpdate();

            stmt2.executeUpdate();

 

            //关闭数据库连接  

            rs.close();  

            psm.close();  

            con.close();  

            

        } catch (Exception e) {  

            System.out.println("显示所有数据报错,原因:"+e.getMessage());  

        }       

        return stulist;   

    }

}

 

--------------------------------------------------RSA加密解密结束---------------------------------------------------------------------


原创粉丝点击