天行健,君子以自强不息

BlogJava 首页 新随笔 联系 聚合 管理
  12 Posts :: 0 Stories :: 2 Comments :: 0 Trackbacks
package com.yill;

import java.security.SecureRandom;

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

public class YillDES
{
    
private static final byte[] key = "HelloWorld".getBytes();

    
public static void main(String[] args)
    
{
        String myInfo 
= "http://www.blogjava.net/yill/";

        System.out.println(
"MyInfo is " + myInfo);

        
byte[] encrypted = encrypt(myInfo.getBytes());

        System.out.println(
"Encrypted myInfo is " + new String(encrypted));

        System.out.println(
"Decrypted myInfo is "
                
+ new String(decrypt(encrypted)));
    }


    
public static byte[] encrypt(byte[] origin)
    
{
        
byte[] encrypted = null;
        
try
        
{
            
// 生成密钥
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey 
= factory.generateSecret(new DESKeySpec(key));

            
// 初始化加密工具cipher
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, 
new SecureRandom());
            encrypted 
= cipher.doFinal(origin);
        }

        
catch (Exception e)
        
{
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }


        
return encrypted;
    }


    
public static byte[] decrypt(byte[] encrypted)
    
{
        
byte[] decrypted = null;
        
try
        
{
            
// 生成密钥
            SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey 
= factory.generateSecret(new DESKeySpec(key));

            
// 初始化加密工具cipher
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, 
new SecureRandom());
            decrypted 
= cipher.doFinal(encrypted);
        }

        
catch (Exception e)
        
{
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }


        
return decrypted;
    }

}



运行结果:
MyInfo is http://www.blogjava.net/yill/
Encrypted myInfo is X耾%
孑塖籫ㄎn勯錍雴?:啌狒>堷z
Decrypted myInfo is http://www.blogjava.net/yill/
posted on 2008-03-16 13:58 yill 阅读(462) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: