java 中的 加密

MD5加密(不能解密)

[java] view plain copy
  1. public class Encrypter  
  2. //   default algorithm is MD5  
  3.     public static String encrypt(String message) throws Exception  
  4.         return encrypt(message, "MD5");  
  5.      
  6.   
  7.     // algorithm: MD5 or SHA-1  
  8.     // return string length: 32 if algorithm MD5, or 40 if algorithm SHA-1  
  9.     public static String encrypt(String message, String algorithm)  
  10.             throws Exception  
  11.         if (message == null)  
  12. //          throw new Exception("message is null.");  
  13.             message "";  
  14.          
  15.         if (!"MD5".equals(algorithm) && !"SHA-1".equals(algorithm))  
  16.             throw new Exception("algorithm must be MD5 or SHA-1.");  
  17.          
  18.         byte[] buffer message.getBytes();  
  19.   
  20.         // The SHA algorithm results in 20-byte digest, while MD5 is 16 bytes  
  21.         // long.  
  22.         MessageDigest md MessageDigest.getInstance(algorithm);  
  23.   
  24.         // Ensure the digest's buffer is empty. This isn't necessary the first  
  25.         // time used.  
  26.         // However, it is good practice to always empty the buffer out in case  
  27.         // you later reuse it.  
  28.         md.reset();  
  29.   
  30.         // Fill the digest's buffer with data to compute message digest from.  
  31.         md.update(buffer);  
  32.   
  33.         // Generate the digest. This does any necessary padding required by the  
  34.         // algorithm.  
  35.         byte[] digest md.digest();  
  36.   
  37.         // Save or print digest bytes. Integer.toHexString() doesn't print  
  38.         // leading zeros.  
  39.         StringBuffer hexString new StringBuffer();  
  40.         String sHexBit null;  
  41.         for (int 0; digest.length; i++)  
  42.             sHexBit Integer.toHexString(0xFF digest[i]);  
  43.             if (sHexBit.length() == 1)  
  44.                 sHexBit "0" sHexBit;  
  45.              
  46.             hexString.append(sHexBit);  
  47.          
  48.         return hexString.toString();  
  49.      
  50.   
  51.     public static void main(String[] args) throws Exception  
  52.         System.out.println(Encrypter.encrypt("123456"));  
  53.           
  54.      


DES加密

[java] view plain copy
  1. public class CryptUtil  
  2.   
  3.     private static final String PASSWORD_CRYPT_KEY "__jDlog_";  
  4.   
  5.     private static final String DES "DES";  
  6.   
  7.     public byte[] encrypt(byte[] src, byte[] key) throws Exception  
  8.         SecureRandom sr new SecureRandom();  
  9.         DESKeySpec dks new DESKeySpec(key);  
  10.         SecretKeyFactory keyFactory SecretKeyFactory.getInstance(DES);  
  11.         SecretKey securekey keyFactory.generateSecret(dks);  
  12.         Cipher cipher Cipher.getInstance(DES);  
  13.         cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);  
  14.         return cipher.doFinal(src);  
  15.      
  16.   
  17.     public byte[] decrypt(byte[] src, byte[] key) throws Exception  
  18.         SecureRandom sr new SecureRandom();  
  19.         DESKeySpec dks new DESKeySpec(key);  
  20.         SecretKeyFactory keyFactory SecretKeyFactory.getInstance(DES);  
  21.         SecretKey securekey keyFactory.generateSecret(dks);  
  22.         Cipher cipher Cipher.getInstance(DES);  
  23.         cipher.init(Cipher.DECRYPT_MODE, securekey, sr);  
  24.         return cipher.doFinal(src);  
  25.      
  26.   
  27.       
  28.     public final String decrypt(String data)  
  29.         try  
  30.             return new String(decrypt(hex2byte(data.getBytes()),  
  31.                     PASSWORD_CRYPT_KEY.getBytes()));  
  32.         catch (Exception e)  
  33.          
  34.         return null;  
  35.      
  36.   
  37.       
  38.     public final String encrypt(String password)  
  39.         try  
  40.             return byte2hex(encrypt(password.getBytes(), PASSWORD_CRYPT_KEY  
  41.                     .getBytes()));  
  42.         catch (Exception e)  
  43.          
  44.         return null;  
  45.      
  46.   
  47.     public String byte2hex(byte[] b)  
  48.         StringBuffer hs new StringBuffer();  
  49.         String stmp "";  
  50.         for (int 0; b.length; n++)  
  51.             stmp (java.lang.Integer.toHexString(b[n] 0XFF));  
  52.             if (stmp.length() == 1)  
  53.                 hs.append("0").append(stmp);  
  54.             else  
  55.                 hs.append(stmp);  
  56.          
  57.         return hs.toString().toUpperCase();  
  58.      
  59.   
  60.     public byte[] hex2byte(byte[] b)  
  61.         if ((b.length 2) != 0)  
  62.             throw new IllegalArgumentException("The length is not an even.");  
  63.         byte[] b2 new byte[b.length 2];  
  64.         for (int 0; b.length; += 2)  
  65.             String item new String(b, n, 2);  
  66.             b2[n 2] (byte) Integer.parseInt(item, 16);  
  67.          
  68.         return b2;  
  69.      
  70.     public static void main(String[] args)  
  71.         String pwd="123456";  
  72.         CryptUtil u=new CryptUtil();  
  73.         System.out.println(u.encrypt(pwd));  
  74.         System.out.println(u.decrypt("619034920555A7F3"));  
  75.      
  76. }
create database mydatabase; use mydatabase; create table account(name varchar(20) primary key,password varchar(50) not null); insert into account(name,password) values(&#39;南京交通&#39;,&#39;njjt&#39;) ; select*from account; update account set password =md5(password); select*from account; package myPackage.examJavaBean; import java.sql.*; public class DatabaseConn { private static Connection conn =null; public static Connection getConnection(String url,String username,String password) { try { Class.forName("com.mysql.jdbc.Driver"); conn =DriverManager.getConnection(url,username,password); }catch(ClassNotFoundException e) { System.out.println(e); }catch(SQLException e){ System.out.println(e); } return conn; } public static void getClose(Connection conn,Statement ps,ResultSet rs){ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); if(conn!=null) conn.close(); }catch(SQLException e){ System.out.println(e); } } } <%@ page language="java" contentType="text/html; charset=GB18030"%> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <script src="/myPro/jQuery/jquery-3.6.4.min.js"></script> <script type="text/javascript"> if($("#user").focus()){ var veriUser=function(){ var user=$("#user").val(); if(user==null||user=="") $("#userMsg").html("输入用户名"); else $("#userMsg").html(""); }; } if($("#pwd").focus()){ var veriPwd=function(){ var pwd=$("#pwd").val(); if(pwd==null||pwd=="") $("#pwdMsg").html("输入登录密码"); else $("#pwdMsg").html(""); }; } $(function(){ $("#btn").bind("click",function(){ var user =$("#user").val(); var pwd=$("#pwd").val(); if(user==null||user==""||pwd==null||pwd=="") return false; }); }); </script> <body> <form id="form" name="form" method="post" action="/myPro/servlet/Servletexam"> <p>用户名:<input type="text" name="user" id="user" maxlength="12" onblur="veriUser()"/><em id="userMsg"></em></p> <p>密 &nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password"name="pwd"id="pwd"maxlength="12"onblur="veriPwd()"/><em id="pwdMsg"></em></p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="submit"name="button"id="btn" value="提交"/>&nbsp;&nbsp; <input type="reset"name="button" value="取消"/></p></form> </body> </html> <%@ page language="java" contentType="text/html; charset=GB18030"%> <html> <head> <title>NewFile.jsp</title> </head> <style type="text/css"> h2{text-align:center} p{text-align:center;color:red} </style> <body> <h2>登录结果</h2> <p> 登录成功!</p> <p>欢迎你,<%=session.getAttribute("name")%></p> </body> </html> package myPackage.examServlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.codec.digest.DigestUtils; import myPackage.examJavaBean.DatabaseConn; @WebServlet("/servlet/Servletexam") public class Servletexam extends HttpServlet{ private static final long serialVersionUID=1L; public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ doPost(request,response); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ request.setCharacterEncoding("GB18030"); String name=request.getParameter("user"); String password=request.getParameter("pwd"); response.setContentType("text/html;charset=GB18030"); HttpSession session =request.getSession(); PrintWriter out =response.getWriter(); Connection conn =DatabaseConn.getConnection("jdbc:mysql://localhost:3306/myDatabase","root","mysql"); try{ PreparedStatement ps=conn.prepareStatement("select password from account where name =?"); ps.setString(1,name); ResultSet rs=ps.executeQuery(); if(rs. next()) { if(DigestUtils.md5Hex(password).equals(rs.getString(1))){ session.setAttribute("name", name); response.sendRedirect("/myPro/exam/success.jsp"); }else out. print("<script type=text/javascript>alert(&#39; 密码错误!重新登录&#39;); location=&#39;/myPro/exam/login.jsp&#39;</script>"); }else out. print("<script type=text/javascript>alert(&#39; 用户名错误!重新登录&#39;); location=&#39;/myPro/exam/login.jsp&#39;</script>"); DatabaseConn.getClose(conn,ps,rs); } catch(SQLException e){ System.out.println(e); } } } <%@ page language="java" contentType="text/html; charset=GB18030"%> <html> <body> <% out.print("这是一场考试"); %> </body> </html> <%@ page language="java" contentType="text/html; charset=GB18030"%> <html> <body> <% int sum=0; for( int i=1;i<=50;i++) sum +=i; %> <p>50以内正整数的和为<%=sum %></p> </body> </html>
07-02
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值