本示例向您展示如何使用Jasypt API编写简单的代码来进行字符串加密和解密。在此示例中,我们将使用BasicTextEncryptor使用该PBEWithMD5AndDES算法的类。此类是TextEncryoptor接口的实现。
您可以从他们的网站下载该库,该库已经包含在Jasypt所需的依赖库中,例如commons-codec和commons-lang。
package org.nhooo.example.jasypt; import org.jasypt.util.text.BasicTextEncryptor; public class TextEncryptorDemo { public static void main(String[] args) { String text = "The quick brown fox jumps over the lazy dog"; System.out.println("Text = " + text); BasicTextEncryptor bte = new BasicTextEncryptor(); bte.setPassword("HelloWorld"); String encrypted = bte.encrypt(text); System.out.println("Encrypted = " + encrypted); String original = bte.decrypt(encrypted); System.out.println("Original = " + original); } }
上面的代码产生的结果:
Text = The quick brown fox jumps over the lazy dog Encrypted = blke1B2qZJyeqOy07En7yAu3vFTFKIiJ3F3gAHb+2rOs/eBPqbvB6HK4j9LwG/E7VETRvQK3VIs= Original = The quick brown fox jumps over the lazy dog