public class Encrypt { public static void main(String[] args) { //base64编码/解码 String string="hello word"; String base64= Base64.encodeToString(string.getBytes());//加密 System.out.println(base64); String string2=Base64.decodeToString(base64);//解密 System.out.println(string2); Assert.assertEquals(string,string2); //16进制编码/解码 String str="hello word"; String base16= Hex.encodeToString(str.getBytes()); System.out.println(base16); String str2=new String(Hex.decode(base16.getBytes())); System.out.println(str2); Assert.assertEquals(str,str2); //散列算法加密 String saltstr="hello word"; String salt="55555"; String md5=new Md5Hash(saltstr,salt).toString(); System.out.println(md5); //散列两次 String md52=new Md5Hash(saltstr,salt,2).toString(); System.out.println(md52); //shiro simpleHash String shirostr="hello word"; String salt2="55555"; String simpltHash=new SimpleHash("SHA-1",shirostr,salt2).toString(); System.out.println(simpltHash); //shiro 提供的DefaulthashService DefaultHashService hashService=new DefaultHashService(); hashService.setHashAlgorithmName("SHA-521");//设置加密方式 hashService.setPrivateSalt(new SimpleByteSource("555555"));//设置私有盐 hashService.setGeneratePublicSalt(true);//生成公盐 默认false hashService.setRandomNumberGenerator(new SecureRandomNumberGenerator());//生成公盐 hashService.setHashIterations(1);//设置散列迭代次数 HashRequest request=new HashRequest.Builder() .setAlgorithmName("MD5") .setSource(ByteSource.Util.bytes("hello word")) .setSalt(ByteSource.Util.bytes("55555")) .setIterations(2).build(); String hex=hashService.computeHash(request).toHex(); System.out.println(hex); //AES算法 AesCipherService aesCipherService=new AesCipherService(); aesCipherService.setKeySize(128); //生成key Key key=aesCipherService.generateNewKey(); String text="hello word"; //加密 String encryptText=aesCipherService.encrypt(text.getBytes(),key.getEncoded()).toHex(); //解密 String text2=new String(aesCipherService.decrypt(Hex.decode(encryptText),key.getEncoded()).getBytes()); Assert.assertEquals(text,text2); }
Encrypt 加密练习
最新推荐文章于 2024-06-06 10:00:18 发布