java经典密码算法,浅析五种最常用的Java加密算法,以后可以直接拿来用了

一)关于加密算法

信息加密是现在几乎所有项目都需要用到的技术,身份认证、单点登陆、信息通讯、支付交易等场景中经常会需要用到加密算法,所谓加密算法,就是将原本的明文通过一系列算法操作变成密文。接下来就介绍一下目前比较常用的一些加密算法,本期不涉及算法底层,以应用介绍和代码展示为主。

如果只想了解原理,可跳过代码部分,代码可直接拿来使用。

(二)MD5算法

准确来讲,MD5不是一种加密算法,而是一种摘要算法,MD5能将明文输出为128bits的字符串,这个字符串是无法再被转换成明文的。网上一些MD5解密网站也只是保存了一些字符串对应的md5串,通过已经记录的md5串来找出原文。

我做过的几个项目中经常见到MD5用在加密上的场景。比如对密码的加密,生成一个密码后,使用MD5生成一个128位字符串保存在数据库中,用户输入密码后也先生成MD5串,再去数据库里比较。因此我们在找回密码时是无法得到原来的密码的,因为明文密码根本不会被保存。

public class MD5 { /** * 生成MD5 * @param str * @return */ public String encode(String str) { byte[] result = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes("UTF-8")); result = md.digest(); } catch (Exception e) { e.printStackTrace(); return null; } return parseByte2HexStr(result); } /** * 将二进制转换成十六进制 * * @param buf * @return */ private String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } public static void main(String[] args) { MD5 md5=new MD5(); String content = "测试test"; System.out.println(md5.encode(content)); }}复制代码

(三)SHA1算法

SHA1也是和MD5类似的信息摘要算法,但是它比MD5更加安全。

public class SHA1 { public String encode(String str) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes("utf-8")); byte[] digest = md.digest(); return byteToHexString(digest); } catch (Exception e) { e.printStackTrace(); return null; } } public static String byteToHexString(byte[] bytes) { return String.valueOf(Hex.encodeHex(bytes)); } public static void main(String[] args) { SHA1 sha1 = new SHA1(); String content = "测试test"; System.out.println(sha1.encode(content)); }}复制代码

(四)AES算法

AES是很常见的对称加密算法,所谓对称加密,就是通过密钥加密后可以再通过密钥解密。我接触过的某个国企现在内部就是采用AES的方式实现集成登陆。第三方系统提供一个接收用户信息的接口,该国企将用户信息AES加密后通过这个接口传递给第三方系统,第三方系统自行实现登陆操作。这里需要注意的是密钥十分重要,如果密钥丢失,就有信息泄漏的风险。

public class AES { /** * 将传入的明文转换为密文 * @param str * @param pwd * @return */ public String encode(String str,String pwd) { byte[] result = null; try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(pwd.getBytes()); kgen.init(128, random); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); // 创建密码器 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] byteContent = str.getBytes(); result = cipher.doFinal(byteContent); } catch (Exception e) { return null; } return parseByte2HexStr(result); } /** * 将传入的密文转换为明文 * @param str * @param pwd * @return */ public String decode(String str,String pwd) { byte[] result = null; byte[] content = parseHexStr2Byte(str); try { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(pwd.getBytes()); kgen.init(128, random); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); // 创建密码器 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); result = cipher.doFinal(content); } catch (Exception e) { e.printStackTrace(); return null; } return new String(result); } /** * 将二进制转换成十六进制 * * @param buf * @return */ private String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } /** * 将十六进制转换为二进制 * * @param hexStr * @return */ private byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } public static void main(String[] args) { AES aes = new AES(); String content = "测试加密"; // AES的密钥长度最好是16位(不是必须) String pwd = "javayznbjavayznb"; // 加密 System.out.println("加密前:" + content); String encodeResultStr = aes.encode(content,pwd); System.out.println("加密后:" + encodeResultStr); // 解密 String decodeResultStr = aes.decode(encodeResultStr,pwd); System.out.println("解密后:" + decodeResultStr); }}复制代码

(五)DES

DES也是一种对称加密算法,但是在安全性、效率和灵活性上比AES略差,但是也能保证安全,DES也需要通过密钥进行加密,通过密钥进行解密,因此密钥很重要:

public class DES { /** * 将传入的明文转换为密文 * @param str * @param pwd * @return */ public String encode(String str,String pwd) { byte[] result = null; try { DESKeySpec keySpec = new DESKeySpec(pwd.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] byteContent = str.getBytes(); result = cipher.doFinal(byteContent); } catch (Exception e) { e.printStackTrace(); return null; } return parseByte2HexStr(result); } /** * 将传入的密文转换为明文 * @param str * @param pwd * @return */ public String decode(String str,String pwd) { byte[] result = null; byte[] content = parseHexStr2Byte(str); try { DESKeySpec keySpec = new DESKeySpec(pwd.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(keySpec); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); result = cipher.doFinal(content); } catch (Exception e) { e.printStackTrace(); return null; } return new String(result); } /** * 将二进制转换成十六进制 * * @param buf * @return */ private String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] &.........

package cn.edu.hbue.ghp; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class tainjia { public static void main(String[] args) { // TODO Auto-generated method stub java.sql.Connection connection = null; PreparedStatement preStmt = null; try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/grade?user=root&"+"password=ghp"; connection = DriverManager.getConnection(url); if(connection != null){ System.out.println("连接成功"); } String sql = "insert into book(author,publisher,isbn,pubDate,price,categoryId)"+"values(?,?,?,?,?,?)"; preStmt = connection.prepareStatement(sql); preStmt.setString(1, "EDA技术"); preStmt.setString(2, "清华大学"); preStmt.setString(3, "1"); preStmt.setString(4, "2017-1-1"); preStmt.setDouble(5, 66); preStmt.setInt(6, 2); preStmt.executeUpdate(); preStmt.setString(1, "你要去相信,没有到不了的明天"); preStmt.setString(2, "湖南出版时"); preStmt.setString(3, "2"); preStmt.setString(4, "2014-11-13"); preStmt.setDouble(5, 32.8); preStmt.setInt(6, 1); preStmt.executeUpdate(); System.out.println("添加数据的行为数为"+preStmt.getUpdateCount()); }catch(ClassNotFoundException e){ System.out.println("JDBC driver error"); }catch(SQLException e){ System.out.println("JDBC operation error"); }finally{ try{ if(preStmt != null){ preStmt.close(); } }catch(SQLException e){ System.out.println("PreparedStatement close error"); } try{ if( connection != null){ connection.close(); } }catch(SQLException e){ System.out.println("PreparedStatement close error"); } } } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值