java中的 DES 加密与解密-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

java中的 DES 加密与解密

2016-06-01 14:54:36 2290 1

DES类

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
screenshot
我的问题:在 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 类写的有问题,请高手帮忙在原有的代码基础上修改。

取消 提交回答
全部回答(1)
  • 蛮大人123
    2019-07-17 19:23:21
    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();
        }
    0 0
相关问答

40

回答

[@徐雷frank][¥20]什么是JAVA的平台无关性

大河人家 2018-10-29 23:55:20 144725浏览量 回答数 40

162

回答

惊喜翻倍:免费ECS+免费环境配置~!(ECS免费体验6个月活动3月31日结束)

豆妹 2014-10-29 17:52:21 226148浏览量 回答数 162

145

回答

【新手入门】云服务器linux使用手册

fanyue88888 2012-11-26 17:14:18 157698浏览量 回答数 145

8

回答

OceanBase 使用动画(持续更新)

mq4096 2019-02-20 17:16:36 337014浏览量 回答数 8

110

回答

OSS存储服务-客户端工具

newegg11 2012-05-17 15:37:18 295551浏览量 回答数 110

22

回答

爬虫数据管理【问答合集】

我是管理员 2018-08-10 16:37:41 147239浏览量 回答数 22

18

回答

阿里云开放端口权限

xcxx 2016-07-20 15:03:33 646790浏览量 回答数 18

31

回答

[@倚贤][¥20]刚学完html/css/js的新手学习servlet、jsp需要注意哪些问题?

弗洛伊德6 2018-10-27 21:52:43 146040浏览量 回答数 31

33

回答

Win Server 2003-2016 加密勒索事件必打补丁合集

妙正灰 2017-05-15 10:44:38 280391浏览量 回答数 33

1

回答

foxmail 关联企业邮箱提示邮箱地址或者密码错误

2017-12-30 21:50:39 151106浏览量 回答数 1
+关注
蛮大人123
我说我不帅他们就打我,还说我虚伪
0
文章
7733
问答
问答排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载