1、SHA-1加密
SHA-1标准加密://SHA-1public static String getSha1(String str){if(str == null || str.length() == 0){return null;}char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};try {MessageDigest mdTemp = MessageDigest.getInstance("SHA1");mdTemp.update(str.getBytes("UTF-8"));byte[] md = mdTemp.digest();int j = md.length;char buf[] = new char[j*2];int k = 0;for(int i =0;i<j;i++){byte byteO = md[i];buf[k++] = hexDigits[byteO >>> 4 & 0xf];buf[k++] = hexDigits[byteO & 0xf];}return new String(buf);} catch (NoSuchAlgorithmException e) {return null;} catch (UnsupportedEncodingException e) {return null;}}
SHA-1的160位算法
public static String getSHA(String spara) {String sRtn = null;try {byte[] plainText = spara.getBytes("UTF8");// 使用getInstance("算法")来获得消息摘要,这里使用SHA-1的160位算法MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");// 开始使用算法messageDigest.update(plainText);// 输出算法运算结果sRtn = new BASE64Encoder().encode(messageDigest.digest());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return sRtn;}
明文:111111
测试结果: 3d4f2bf07dc1be38b20cd6e46949a1071f9d0e3d
PU8r8H3BvjiyDNbkaUmhBx+dDj0=
2.DES加密解密
//获取秘钥public static SecretKey readKey(){try {String skey = "XXXXXXXXXXXXXXX";byte[] bs = skey.getBytes("UTF8");//创建DESKeySpec对象DESKeySpec dks = new DESKeySpec(bs);//转换DESKeySpec为SecretKey对象SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");SecretKey key = keyFactory.generateSecret(dks);return key;} catch (Exception e) {e.printStackTrace();}return null;}// 加密密码public static String enPass(String password){try {SecretKey key = readKey();Cipher cip = Cipher.getInstance("DES");cip.init(Cipher.ENCRYPT_MODE, key);byte[] cipBytes = cip.doFinal(password.getBytes());String sblob = new BASE64Encoder().encode(cipBytes);return sblob;} catch (Exception e) {e.printStackTrace();}return null;}//解密密码public static String dePass(String password){try {byte[] keyBuffer = new BASE64Decoder().decodeBuffer(password);SecretKey key = readKey();Cipher cip = Cipher.getInstance("DES");cip.init(Cipher.DECRYPT_MODE, key);String stmp = new String(cip.doFinal(keyBuffer),"UTF8");return stmp;} catch (Exception e) {e.printStackTrace();}return null;}
如果觉得《JAVA SHA-1加密及DES加解密》对你有帮助,请点赞、收藏,并留下你的观点哦!