DES的java实现小记

package com.des;

import java.security.SecureRandom;

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

public class DES {
	
	
	 public static byte[] encrypto(byte input[], byte key[])
     throws Exception{
		 byte plainData[];
	     int len = (input.length / 8 + (input.length % 8 != 0 ? 1 : 0)) * 8;
	     plainData = new byte[len];
	     System.arraycopy(input, 0, plainData, 0, input.length);
	     SecureRandom sr;
	     DESKeySpec dks;
	     SecretKeyFactory keyFactory;
	     sr = new SecureRandom();
	     dks = new DESKeySpec(key);
	     keyFactory = SecretKeyFactory.getInstance("DES");
	     SecretKey secretKey  = keyFactory.generateSecret(dks);
	     Cipher cipher = null;
	     cipher = Cipher.getInstance("DES/ECB/NoPadding");
	     cipher.init(1, secretKey, sr);
	     
	     byte encryptedData[];
	     encryptedData = cipher.doFinal(plainData);
	        
	     return encryptedData;
	 }

	 
	 public static byte[] decrypto(byte input[], byte key[])
     throws Exception
 {
		 	SecretKeyFactory keyFactory = null;
	        keyFactory = SecretKeyFactory.getInstance("DES");
	        javax.crypto.SecretKey secretKey = null;
	        secretKey = keyFactory.generateSecret(new DESKeySpec(key));
	        Cipher cipher = null;
	        cipher = Cipher.getInstance("DES/ECB/NoPadding");
	        cipher.init(2, secretKey);
	        byte decryptedData[];
	        decryptedData = cipher.doFinal(input);
	        return decryptedData;
}
	 
	 public static void main(String... args) throws Exception{
		 String key="0808080808080808";
		 byte[] realkey=fromHex(key);
		 byte[] afterDes=encrypto("aaaaaaaaaa".getBytes(),realkey);
		 System.out.println(toHex(afterDes));
		 
		 byte[] desBack=decrypto(afterDes,realkey);
		 System.out.println(new String(desBack));
	 }
	 
	 
	 
	 
	 
	 
	 
	 
	 
	 public static final byte[] fromHex(String b)
	    {
	        char data[] = b.toCharArray();
	        int l = data.length;
	        byte out[] = new byte[l >> 1];
	        int i = 0;
	        for(int j = 0; j < l;)
	        {
	            int f = Character.digit(data[j++], 16) << 4;
	            f |= Character.digit(data[j++], 16);
	            out[i] = (byte)(f & 0xff);
	            i++;
	        }

	        return out;
	    }

	    public static final String toHex(byte b[])
	    {
	        char buf[] = new char[b.length * 2];
	        int j;
	        for(int i = j = 0; i < b.length; i++)
	        {
	            int k = b[i];
	            buf[j++] = hex[k >>> 4 & 0xf];
	            buf[j++] = hex[k & 0xf];
	        }

	        return new String(buf);
	    }
	    
	    private static final char hex[] = {
	        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
	        'A', 'B', 'C', 'D', 'E', 'F'
	    };

}

你可能感兴趣的:(java,c,F#,Security,J#)