java 加密算法 DES 实现代码

java 加密算法 DES 实现代码
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/

你可能感兴趣的:(java 加密算法 DES 实现代码)