数字签名与加密的区别
数字签名更多是用来校验信息有没有被修改过,而加密可以彻底杜绝防止别人看到信息内容
SHA-1 和 MD5算法
严格说来它们不算是加密算法,只能说是摘要算法。
SHA-1算法:Security Hash Algorithm 安全哈希算法, 它可以把长度不超过2的64次方位的信息转换成160位(20字节)长的散列值
MD5算法:Message Digest 信息摘要算法, 散列长度是128位,16个字节。它对输入以512位分组,输出是4个32位字的级联。
CRC算法:循环冗余校验,碰撞几率比较高
加密技术可以分为对称与非对称两种.
对称加密,解密,即加密与解密用的是同一把秘钥,常用的对称加密技术有DES,AES等
而非对称技术,加密与解密用的是不同的秘钥,常用的非对称加密技术有RSA等
例如DES对称加密代码:
/** * 给用户id和设备id进行加密,添加时间属性 * * @param userId * @return */ public static String encode(Long userId, Long deviceId) { try { Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 16; i++) { sb.append(values[random.nextInt(values.length - 1)]); } String randomCode = sb.toString(); SecretKey deskey = new SecretKeySpec((randomCode + KEYPREFIX).getBytes("utf-8"), "DESede"); // 加密 Cipher c1 = Cipher.getInstance("DESede"); c1.init(Cipher.ENCRYPT_MODE, deskey); String str = ""; String time=new SimpleDateFormat("yyyyMM").format(new Date()); if (deviceId != null && deviceId > 0) { str = Tf8Base64.base32Encode(c1.doFinal(String.valueOf(userId + SEP + deviceId+SEP+Long.valueOf(time)).getBytes("utf-8"))); } else { str = Tf8Base64.base32Encode(c1.doFinal(String.valueOf(userId).getBytes("utf-8"))); } return URLEncoder.encode(UNDERLINE + str + randomCode, "utf-8"); } catch (Exception e) { log.error("error happens when encode userId for " + userId + ",error info is " + e.getMessage(), e); } return ""; }
DES 解密
/** * @param code * @return */ public static String decode(String code) { try { code = URLDecoder.decode(code, "utf-8"); String userId = code.substring(0, code.length() - 16); String randomCode = code.substring(code.length() - 16); SecretKey deskey = new SecretKeySpec((randomCode + KEYPREFIX).getBytes("utf-8"), "DESede"); // 解密 Cipher c1 = Cipher.getInstance("DESede"); c1.init(Cipher.DECRYPT_MODE, deskey); return new String(c1.doFinal(Tf8Base64.base32Decode(userId))); } catch (Exception e) { log.error("error happens when decode code for " + code + ",error info is " + e.getMessage(), e); } return ""; }
相关推荐
xuyoucheng00 2020-09-26
igogo00 2020-07-19
sunjunior 2020-06-16
燕哥带你学算法 2020-06-11
natloc 2020-06-10
Tips 2020-05-17
bluewelkin 2020-05-16
NickLinYuan 2020-05-13
RememberMePlease 2020-04-11
Terminator0 2020-04-10
hqulyc 2020-04-08
dushine00 2020-02-03
yedaoxiaodi 2019-12-29
wuxiaosi0 2020-01-03
82374197 2019-07-09
Happyunlimited 2019-12-09
luohui 2019-11-10
xingzhaozhong 2011-08-15
natloc 2014-09-12