如何使用Java代码保护敏感信息呢?
下文笔者讲述使用java代码保护敏感信息的方法分享,如下所示
使用加密算法PBEWithMD5AndTripleDES
保护敏感信息的方法
保护敏感信息的方法: 对信息进行加密,然后再解密,达到关键性信息的脱敏操作 具体实现方法,如下所示 使用Jasypt这个jar包中的一些方法,即可快速处理此类问题例: Maven引用jar包
<dependency> <groupId>org.jasypt</groupId> <artifactId>jasypt</artifactId> <version>1.9.3</version> <scope>compile</scope> </dependency>
简单文本加密
如:通讯信息,交易流水、账号信息等敏感信息,可使用以下加密方法BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); //设置加密密钥 textEncryptor.setPassword("MySalt"); //加密信息 String encryptedText = textEncryptor.encrypt("This is a secret message."); System.out.println("encryptedText:" + encryptedText); //解密 String decryptedText = textEncryptor.decrypt(encryptedText); System.out.println("decryptedText:" + decryptedText);
单向密码加密
如:密码---加密后不可解密BasicPasswordEncryptor encryptor = new BasicPasswordEncryptor(); //加密密码 String encryptedPassword = encryptor.encryptPassword("MyPassword"); //检查密码:正确 System.out.println(encryptor.checkPassword("MyPassword", encryptedPassword)); //检查密码:错误 System.out.println(encryptor.checkPassword("myPassword", encryptedPassword));
自定义加密算法
Jasypt为我们提供的灵活的加密/解密操作 可自定义地使用不同的算法进行加密解密例:
使用加密算法PBEWithMD5AndTripleDES
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); //设置密钥 encryptor.setPassword("MySalt"); //设置加密算法 encryptor.setAlgorithm("PBEWithMD5AndTripleDES"); //加密信息 String encryptedText = encryptor.encrypt("My secret message."); System.out.println("encryptedText:" + encryptedText); //解密 String decryptedText = encryptor.decrypt(encryptedText); System.out.println("decryptedText:" + decryptedText);
多线程解密
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor(); //设置线程数为6 encryptor.setPoolSize(6); //设置密钥 encryptor.setPassword("MySalt"); //设置算法 encryptor.setAlgorithm("PBEWithMD5AndTripleDES"); //加密 String encryptedText = encryptor.encrypt("My secret message."); System.out.println("encryptedText:" + encryptedText); //解密 String decryptedText = encryptor.decrypt(encryptedText); System.out.println("decryptedText:" + decryptedText);
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。