想把一个字符串加密后存储在文本文件中,还想从文文中读取出该字符串进行解密,使用JDK中自带的包,如何能够实现?请指教。

解决方案 »

  1.   

    此回复为自动发出,仅用于显示而已,并无任何其他特殊作用
    楼主【raine13】截止到2008-06-27 09:00:52的历史汇总数据(不包括此帖):
    发帖数:12                 发帖分:240                
    结贴数:11                 结贴分:220                
    未结数:1                  未结分:20                 
    结贴率:91.67 %            结分率:91.67 %            
    值得尊敬
      

  2.   

    应该采用 base64 编码。
      

  3.   

    用Java实现DES、RC2或者Rijndael用javax.crypto.Cipher
    http://gceclub.sun.com.cn/Java_Docs/jdk6/html/zh_CN/api/index.html给你个例子:import javax.crypto.*;
    import javax.crypto.spec.*;
    import sun.misc.*;
    import java.security.*;
    import com.sun.crypto.provider.*;public class MyDESTest{    public static String doEncrypt(String key,String plainText) throws Exception{
            Provider sunJce = new com.sun.crypto.provider.SunJCE();
            Security.addProvider(sunJce);        Cipher c = Cipher.getInstance("DES");
            SecretKeyFactory keyFac = SecretKeyFactory.getInstance("DES");
            DESKeySpec keySpec = new DESKeySpec(key.getBytes());
            SecretKey secKey = keyFac.generateSecret(keySpec);        c.init(Cipher.ENCRYPT_MODE,secKey);
            byte[] b = c.doFinal(plainText.getBytes());
            return new sun.misc.BASE64Encoder().encode(b);
        }    public static String doDecrypt(String key,String cipherText) throws Exception{        Provider sunJce = new com.sun.crypto.provider.SunJCE();
            Security.addProvider(sunJce);        Cipher c = Cipher.getInstance("DES");
            SecretKeyFactory keyFac = SecretKeyFactory.getInstance("DES");
            DESKeySpec keySpec = new DESKeySpec(key.getBytes());
            SecretKey secKey = keyFac.generateSecret(keySpec);        byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(cipherText);
            c.init(Cipher.DECRYPT_MODE,secKey);
            return new String(c.doFinal(b));
        }    public static void main(String[] args){        String key = "abcd1234";
            String source = "1234567812345678";
            String destination = null;        try {
                System.out.println( "source: " + source );            destination = doEncrypt(key, source);
                System.out.println( "destination: " + destination );            String decrypted = doDecrypt(key, destination);
                System.out.println( "decrypted: " + decrypted );
            }
            catch(Exception e){}    }
    }
    执行结果:
    [code=BatchFile]MyHost:/cygdrive/d/temp> java -cp .  MyDESTest
    source: 1234567812345678
    destination: Su2cgmLhJjFK7ZyCYuEmMS0ZxLNK7pNJ
    decrypted: 1234567812345678[/code]