程序:
package ufo; import java.security.Key; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.PBEParameterSpec; import org.apache.commons.codec.binary.Base64; public class PBEWITHMD5andDES_Test { public static void main(String... args) { String original="Let’s Build a Giant Airship 青海长云暗雪山"; System.out.println("原文= "+original); try { // 生产密钥 String password="haha168";// 口令 PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory factory=SecretKeyFactory.getInstance("PBEWITHMD5andDES"); Key key =factory.generateSecret(pbeKeySpec);// 密钥,下面加密解密都要用到 System.out.println("密钥= "+Base64.encodeBase64String(key.getEncoded())); // 初始化盐 SecureRandom random=new SecureRandom(); byte [] salt=random.generateSeed(8); PBEParameterSpec pbeParameterSpec=new PBEParameterSpec(salt, 100); // 加密 Cipher cipher =Cipher.getInstance("PBEWITHMD5andDES"); cipher.init(Cipher.ENCRYPT_MODE,key, pbeParameterSpec); byte[] bytes = cipher.doFinal(original.getBytes()); System.out.println("密文= "+Base64.encodeBase64String(bytes)); // 解密 cipher.init(Cipher.DECRYPT_MODE,key,pbeParameterSpec); bytes=cipher.doFinal(bytes); System.out.println("解密后= "+new String(bytes)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
输出:
原文= Let’s Build a Giant Airship 青海长云暗雪山 密钥= aGFoYTE2OA== 密文= fgYLsGkeyJCzYkp7W5FgsxoIjtVCjd4yiYUOoiE4tdx0CV3Xx7EcbwsRoIMSaEIy 解密后= Let’s Build a Giant Airship 青海长云暗雪山
END
最新评论