j2se 1.4 中提供了加解密库。javax.crypto

解决方案 »

  1.   

    原理类似
    x^=y; y^=x; x^=y;
      

  2.   

    http://java.sun.com/features/2002/09/pword_mask.html
      

  3.   

    基于密码的加密
    import java.security.*;
    import java.security.cert.X509Certificate;
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class Encrypt
    {
      private String password;  public Encrypt(String password)
      {
        this.password=password;
      }  public String encode(String info)
      {
        if(info==null)
          return "";
        try
        {
          PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
          SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
          SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);      byte[] salt = {
          (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
          (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
          };      int count = 2;      // 生成pbe算法所需的参数对象,两个参数详见 RSA的 PKCS #5 标准
          PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);      // 生成一个加密器
          Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");      // 初始化加密器
          pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);      // 明文
          byte[] cleartext = info.getBytes();      // 加密
          byte[] ciphertext = pbeCipher.doFinal(cleartext);      //返回密文
          return new String(ciphertext);
        }
        catch (Exception e)
        {
          System.out.println(e);
        };
        return "";
      }  public String decode(String info)
      {
        if(info==null)
          return "";
        try
        {
          PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
          SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
          SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);      byte[] salt = {
          (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
          (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
          };      int count = 20;      // 生成pbe算法所需的参数对象,两个参数详见 RSA的 PKCS #5 标准
          PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);      // 生成一个加密器
          Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");      // 初始化加密器
          pbeCipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);      // 密文
          byte[] ciphertext = info.getBytes();      // 解密
          byte[] cleartext = pbeCipher.doFinal(ciphertext);      //返回明文
          return new String(ciphertext);
        }
        catch (Exception e)
        {
          System.out.println(e);
        };
        return "";
      }
    }
      

  4.   

    怎么在解密的时候有错误:javax.crypto.BadPaddingException: Given final block not properly padded
      

  5.   

    把public String encode(String info)
    改为public byte[] encode(byte[] info)
    还有public byte[] decode(byte[] info)也要改。