java中的 DES 加密与解密

java中的 DES 加密与解密

问题描述:

DES类

package dao;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class DES {

public static String ALGORITHM_DES="DES";       //加密算法的名称 
public static KeyGenerator keygen;          //密钥生成器 
public static SecretKey secretKey;      //密钥 
public static Cipher cipher;        //密码器
public byte[] bytes;

static{
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    try{
        keygen=KeyGenerator.getInstance(ALGORITHM_DES);
        secretKey=keygen.generateKey();
        cipher=Cipher.getInstance(ALGORITHM_DES);
    }catch(Exception e){
        e.printStackTrace();
    }
}

//加密
public byte[] encryptor(String str){
    try {
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);    //初始化密码器,用密钥 secretKey 进入加密模式
        bytes=cipher.doFinal(str.getBytes());   //加密
    } catch (Exception e) {
        e.printStackTrace();
    }

    return bytes;
}

//解密
public String decryptor(byte[] buff){
    try {
        cipher.init(Cipher.DECRYPT_MODE, secretKey);    //初始化密码器,用密钥 secretKey 进入解密模式
        bytes=cipher.doFinal(buff);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (new String(bytes));
}

}

index.jsp

index.jsp

%>

我的问题:在 index.jsp 页面里提交的超链接 Demo 提交到 Action ,但是一点击,后台就报错:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:750)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at dao.DES.decryptor(DES.java:44)
at filter.MyFilter.doFilter(MyFilter.java:36)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
at java.lang.String.(Unknown Source)
at dao.DES.decryptor(DES.java:48)
at filter.MyFilter.doFilter(MyFilter.java:36)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
解密前:product_id=[B@3242ef

是哪里写的不对,请高手指点,我的目的是从 index.jsp 把值(product_id)进行加密,在 Action 里面取出 加密后的字符串,进行解密,但解密那一块有问题,可能是 DES 类写的有问题,请高手帮忙在原有的代码基础上修改。成分感激!!

久等了

 *
 * author: hyb1996 (CSDN)
 * 说明:密匙key的长度必须是8的倍数
 */

package encryption;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.crypto.*;
import javax.crypto.spec.*;

public class DES {

    // 默认密匙
    private static String key = "19491001";
    // 缓冲区大小
    private static final int BufferSize = 1024 * 1024 * 10;

    // 加密解密测试测试
    public static void test() {
        String text = "111测试asdY^&*NN!__s some plaintext!";
        System.out.println("加密前的明文:" + text);

        String cryperText = "";
        try {
            cryperText = toHexString(encrypt(text));
            System.out.println("加密后的明文:" + cryperText);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            System.out.println("解密后的明文:"
                    + new String(decrypt(convertHexString(cryperText), key),
                            "UTF-8"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            System.in.read();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 设置默认密匙
    public static void setKey(String k) {
        key = k;
    }

    // 用指定密匙对密文message解密并返回解密后byte[]
    public static byte[] decrypt(String message, String key) throws Exception {
        return decrypt(message.getBytes("UTF-8"), key);
    }

    // 用默认密匙对密文message解密并返回解密后byte[]
    public static byte[] decrypt(String message) throws Exception {
        return decrypt(message, key);
    }

    // 用指定密匙对密文数据data解密并返回解密后byte[]
    public static byte[] decrypt(byte[] data, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        return cipher.doFinal(data);
    }

    // 用指定密匙对密文data从offset开始长度为len的数据解密并返回解密后byte[]
    public static byte[] decrypt(byte[] data, int offset, int len, String key)
            throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        return cipher.doFinal(data, offset, len);
    }

    // 用指定密匙对字符串message加密并返回加密后byte[]
    public static byte[] encrypt(String message, String key) throws Exception {
        return encrypt(message.getBytes("UTF-8"), key);
    }

    // 用默认密匙对字符串message加密并返回加密后byte[]
    public static byte[] encrypt(String message) throws Exception {
        return encrypt(message, key);
    }

    // 用指定密匙对数据data加密并返回加密后byte[]
    public static byte[] encrypt(byte[] data, String key) throws Exception {
        return encrypt(data, 0, data.length, key);
    }

    // 用指定密匙对密文data从offset开始长度为len的数据加密并返回加密后byte[]
    public static byte[] encrypt(byte[] data, int offset, int len, String key)
            throws Exception {
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        return cipher.doFinal(data, offset, len);
    }


    public static byte[] convertHexString(String ss) {
        byte digest[] = new byte[ss.length() / 2];
        for (int i = 0; i < digest.length; i++) {
            String byteString = ss.substring(2 * i, 2 * i + 2);
            int byteValue = Integer.parseInt(byteString, 16);
            digest[i] = (byte) byteValue;
        }

        return digest;
    }

    public static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }

        return hexString.toString();
    }

    //用指定密匙key对路径为path的文件加密并写入路径为out的文件中 
    public static void fileEncrypt(String path, String out, String key)
            throws Exception {
        File file = new File(path);
        FileInputStream in = new FileInputStream(file);
        file = new File(out);
        if (file.exists())
            file.delete();
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[BufferSize];
        byte[] outbuf;
        int size = in.available();
        int done = 0;
        while (in.available() > 0) {
            int len = in.read(buffer);
            outbuf = DES.encrypt(buffer, 0, len, key);
            fos.write(outbuf, 0, outbuf.length);
            done += len;
            System.out.print(100 * (long) done / size);
            System.out.println('%');

        }
        fos.close();
        in.close();
    }

    //用指定密匙key对路径为path的文件加密并写入路径为out的文件中,而且不使用缓冲区
    public static void $fileEncrypt(String path, String out, String key)
            throws Exception {
        File file = new File(path);
        FileInputStream in = new FileInputStream(file);
        file = new File(out);
        if (file.exists())
            file.delete();
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[in.available()];
        in.read(buffer);
        buffer = DES.encrypt(buffer, key);
        fos.write(buffer, 0, buffer.length);
        fos.close();
        in.close();
    }

    //用指定密匙key将字符串message加密并写入路劲为out的文件中
    public static void StringEncryptIntoFile(String message, String out,
            String key) throws Exception {
        File file = new File(out);
        if (file.exists())
            file.delete();
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        byte[] data = encrypt(message, key);
        fos.write(data);
        fos.close();
    }

    //用指定密匙key对路径为path的密文文件解密并写入路径为out的文件中 
    public static void fileDecrypt(String path, String out, String key)
            throws Exception {
        File file = new File(path);
        FileInputStream in = new FileInputStream(file);
        file = new File(out);
        if (file.exists())
            file.delete();
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[BufferSize + 8];
        byte[] outbuf;
        int size = in.available();
        int done = 0;
        while (in.available() > 0) {
            int len = in.read(buffer);
            outbuf = DES.decrypt(buffer, 0, len, key);
            fos.write(outbuf, 0, outbuf.length);
            done += len;
            System.out.print(100 * (long) done / size);
            System.out.println('%');
        }
        fos.close();
        in.close();
    }

    //用指定密匙key对路径为path的密文文件解密并写入路径为out的文件中 ,且不使用缓冲区
    public static void $fileDecrypt(String path, String out, String key)
            throws Exception {
        File file = new File(path);
        FileInputStream in = new FileInputStream(file);
        file = new File(out);
        if (file.exists())
            file.delete();
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buffer = new byte[in.available()];
        in.read(buffer);
        buffer = DES.decrypt(buffer, key);
        fos.write(buffer, 0, buffer.length);
        fos.close();
        in.close();
    }

    //用指定密匙key对路径为path的密文文件解密得到明文字符串并返回
    public static String fileDecrypt(String path, String key) throws Exception {
        File file = new File(path);
        FileInputStream in = new FileInputStream(file);
        byte[] buffer = new byte[BufferSize + 8];
        StringBuffer sb = new StringBuffer();
        int size = in.available();
        int done = 0;
        byte[] outbuf;
        while (in.available() > 0) {
            int len = in.read(buffer);
            outbuf = DES.decrypt(buffer, 0, len, key);
            sb.append(new String(outbuf, 0, outbuf.length, "UTF-8"));
            done += len;
            System.out.print(100 * (long) done / size);
            System.out.println('%');
        }
        in.close();
        return sb.toString();
    }

我之前做个类似项目,自己有写一个DES加密解密的类,等我吃饱把代码贴给你。

CSDN是怎么回事?发布的全部代码,还有部分没有显示,真头疼,这让回答的朋友看不全呀。

说明一下,可以这样使用:
byte[] miwen = DES.encrypt("1",key);
String mingwen = new String(DES.decrypt(miwen,key));
System.out.println(mingwen);


                index.jsp文件:
                String test="100";
                System.out.println("加密:"+DES3.encrypt(test,"20160223"));
                System.out.println("解密:"+new String(DES3.decrypt(DES3.encrypt(test,"20160223"),"20160223")));
                通过一个超链接:<a href="productAction-query?product_id=<%=DES3.encrypt(test,"20160223") %>">Demo</a>

                Action 文件:
                String product_id=request.getParameter("product_id");
                System.out.println("解密前:product_id="+product_id);
                System.out.println("解密后:product_id="+new String(DES3.decrypt(product_id,"20160223")));

                提交之后后台报错:
                加密:[B@44c5d3

解密:100

解密前:product_id=[B@117b032
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:750)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:314)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at dao.DES3.decrypt(DES3.java:67)

hyb1996,再帮忙看一下呗,非常感谢!
我个人感觉:System.out.println("解密后:product_id="+new String(DES3.decrypt(product_id,"20160223")));这行有问题,因为 product_id 在index.jsp里面是byte[]类型了,而在 Action类里面 request.getParameter 都是字符串String类型了,应该怎么解决这个问题呢?

已经搞明白了,DES3.toHexString(DES3.encrypt(test,"20160223"),这样发送才行。
另外一个问题想请教一下:你的这个定义 private static String key = "19491001"; 是加密时用的吧?那 我的这个:DES3.encrypt(test,"20160223") 这里面的"20160223"是不是就不需要了?如果我自己定义个8位数的字符串key,就改一下你那里面的 key 初始值就行了吧?