DES加密--不安全加密

package test;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

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

public class DESCoder {

        //加密算法
        public static final String KEY_ALGORITHM= "DES";
       
        //加密/解密算法 /工作模式/填充模式
        public static final String CIPHER_ALGORITHM= "DES/ECB/PKCS5Padding";
       
        //还原密钥
        private static Key toKey(byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, Exception{
               //实例化DES密钥材料
              DESKeySpec dks= new DESKeySpec(key);
               //实例化密钥工厂
              SecretKeyFactory keyFactory=SecretKeyFactory.getInstance( KEY_ALGORITHM);
               //生成密钥
              SecretKey secretKey= keyFactory.generateSecret(dks);
               return  secretKey;
       }
       
        //解密
        public static byte[] decrpt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException, Exception{
               //还原密钥
              Key k= toKey(key);
               //实例化
              Cipher cipher=Cipher. getInstance(CIPHER_ALGORITHM);
               //初始化
              cipher.init(Cipher. DECRYPT_MODE,k);
               return cipher.doFinal(data);
       }
       
        //加密
        public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
               //还原密钥
              Key k= toKey(key);
              Cipher cipher=Cipher. getInstance(CIPHER_ALGORITHM);
              cipher.init(Cipher. ENCRYPT_MODE, k);
               return cipher.doFinal(data);
       }
       
        //获取密钥,二进制形式
        public static byte[] initKey() throws Exception{
              KeyGenerator kg=KeyGenerator. getInstance(KEY_ALGORITHM);
               //初始化密钥生成器
              kg.init(56); //kg.init(64),kg.init(new SecureRandom());
               //生成密钥
              SecretKey secretKey=kg.generateKey();
               //获取密钥的二进制形式
               return secretKey.getEncoded();
       }
}

多重DES

加密算法 KEY_ALGORITHM ="DESede"

CIPHER_ALGORITHM ="DESede/ECB/PKCS5Padding

密钥规范 DEedeSKeySpec dks=new DESedeKeySpec(key)

密钥长度也要修改 kg.init(168);


posted @ 2014-08-30 11:19  徐小鱼  阅读(1402)  评论(0编辑  收藏  举报