jca des加密简单例子

jca des加密简单例子

import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

public class JcaTest {
 public static void main(String args[]) throws Exception {
  SecureRandom sr = new SecureRandom();
  KeyGenerator kg = KeyGenerator.getInstance("DES");
  kg.init(sr);
  SecretKey key = kg.generateKey();
  // 获得密匙数据
  byte rawKeyData[] = key.getEncoded();
  Cipher cipher = Cipher.getInstance("DES");
  cipher.init(Cipher.ENCRYPT_MODE, key, sr);

  String src = "你好吗测试加密";
  byte[] dest = cipher.doFinal(src.getBytes());
  System.out.println("加密后的数据:"+new String(dest));

  // 解密 从原始密匙数据创建一个DESKeySpec对象
  sr = new SecureRandom();
  DESKeySpec dks = new DESKeySpec(rawKeyData);
  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  SecretKey keys = keyFactory.generateSecret(dks);
  Cipher ciphers = Cipher.getInstance("DES");
  ciphers.init(   Cipher.DECRYPT_MODE,keys,sr);  
  byte[] srcs = ciphers.doFinal(dest);
  System.out.println("解密后的数据:"+new String(srcs));
 }
}



</script>

你可能感兴趣的:(jca des加密简单例子)