精华内容
下载资源
问答
  • 名称:Post Encryption And Decryption 版本: 1.1 作者:Ludou 更新:2010-05-17 功能:帮助您快速加密解密某个分类或某个标签下的所有的文章。加密为给你的文章添加密码,其他人必须知道密码才能阅读你加密的文章...
  • 分类文章加密插件post-encryption-and-decryption  今天介绍一款加密文章的插件post-encryption-and-decryption,这款插件使用简单,加密后的文章要输入正确的密码才能看见,很实用!下面有两张装好插件的图,请...
  • 为您提供Synology Cloud Sync Decryption Tool下载,Synology Cloud Sync Decryption Tool是群晖推出的Cloud sync解密工具,Cloud Sync集成了公共云和私有的优势,使您能够将您的Synology NAS轻松连接到公共云服务,...
  • FDR_Decryption_v2.3-源码

    2021-04-19 21:02:37
    FDR_Decryption_v2.3
  • 对于文本文件的每个字节(char),转置最高有效位并将其附加到最低有效位,然后取字节的补码(非)。 原始字节 10011010 换位后 00110101 补后 11001010 要解密文本,请反转加密步骤。 要求 ...
  • encryption&decryption;.cpp

    2019-09-29 16:42:21
    密码学单表代换移位代码,可实现文件的加密和解密。可搭配资源区古典密码.doc
  • Content Decryption Module Interface Specification,
  • 使用Python进行Hill加密 加密 加密时; 首先,将文本字符划分为二进制块,逐个块分隔并对其进行加密。 使用给定的键矩阵,文本中的字符会根据其在字母表中的对应值相乘。 将乘法结果相加,并根据字母中的字符数采用...
  • wireshark-ssl-decryption.pdf

    2018-08-22 13:44:22
    从网上收集来的pdf, 将在wireshark中解密ssl流量的方法。
  • ECC encryption 和decryption

    2015-10-19 07:17:23
    ECC encryption 和decryption 只需要输入曲线数据和点数据就可加密和解密
  • 使用 MATLAB 指南,该程序将使用凯撒密码加密和解密字母用户必须输入密钥大小,然后输入 texy,然后单击加密解密也遵循类似的方法
  • Java解压RAR文件,压缩包内包含Jar包、依赖包
  • 加密解密 一个简单的菜单使用户可以选择是否要从文件加密或解密。 随机生成的偏移量可用于实现此目的。 使用的编程语言 作为高中项目的一部分,这是在python中完成的(基本且效率不高)
  • 140269447632640:error:1408F119:SSL routines:ssl3_get_record:decryption failed or bad record mac:ssl/record/ssl3_record.c:677: 这个错误的原因是openssl 在对收到的包做完整性校验时发现收到的报数据不对。...

    代码

    books

    Unix-Netzwerkprogrammierung mit Threads, Sockets und SSL
    Network Security with OpenSSL
    The Definitive Guide to Linux Network Programming

    宏定义

    如果消息里出现content-type 是21:
    SSL3_RT_ALERT 21
    如果content type是alert,alert消息也会被加密,需要decode tls 消息看看alert是什么
    怎么解密 TLS,需要使用对应的key文件才能解压,在编辑-配置选项里,找到TLS协议,添加RSA key list;
    添加一行,IP地址选择any,填上 port端口,然后解压出来之后还是明文的数据,需要点右键decode as 选项相应的协议。

    https://wiki.wireshark.org/TLS#Using_the_.28Pre.29-Master-Secret
    https://sharkfesteurope.wireshark.org/assets/presentations16eu/07.pdf
    https://packetpushers.net/using-wireshark-to-decode-ssltls-packets/

    错误分析

    do_SSL_read(): Failure return (err 1) from SSL_read() on socket 91.
    140269447632640:error:1408F119:SSL routines:ssl3_get_record:decryption failed or bad record mac:ssl/record/ssl3_record.c:677:

    这个错误的原因是openssl 在对收到的包做完整性校验时发现收到的报数据不对。调查时需要从两端同时抓取wireshrk包分析,看到底哪里将数据破坏掉了。

    举例

    包里的数据时:
    a7e4cb25e1e1ec0d5c09ec235be678383431064b9835ec98f39ca4a98d19bb4e802834f3e8eb14fd0ec4204fd5e7c7382ac6b84e4b7857c536c73f44bc653d6e89c262cdad9f95820cb970aa5b40bb
    d81f5c62ea4f664ae0ce6e7fb353c7d3b036cb89da0e4aafd831c3500c85e0c25f0d2b985c3cd5ce3b93283980a16ff37c4ba6328892bec7356876becc864162c52822a3c49c2da5d5868cb6d0bc82c
    11794903968f7e83004554008e966c2600b3259e0a7c08ba1b662ec4ee8d4e10b6eaf3f80f4c9f61127081495e0a941b5ad242bdef689d7c53fc1434e6b6eca426bf3fabcbef3331ef609a3917a867a
    b29c174425ca0767203dc00dbbae536458d2d8edb3d9a92e069f6f31226a6f2ed29fc1815f4c51fe197cbd63c7c8b378c66aae0b8d1c967379aa7cc9bb36f6329d97b3173af983deb7d555b969730d
    3f9b2eefa9df9c1029736011f15129c03c7f090a7b03eeedebfc422427f5f445daba89698a05255f8e67b95b7b0d036fa50f64c14b2b40358473c5f8785ee4783ff68e46e8f1ab9d5dd30267001ef192
    6f4a843c8a58a7bb95c04320d82382fa89451ea2ec83936754f51363851332a2f0f339195e23ce071f11b2d71debf2036b4a79e904156bef8503baf9a24b28b66dedfa1768300450532e196a351307
    5425a9bed0767abfa354773ad035c22f75066fc2d1db79cfc7e1930c519911e5b4200e42f242f3629acead0402e48d44be895870290c07dd40d3cfd9531b77fdb1b3b46b2c4e87b63f8a2f36060452
    bcd45258ead4d58c48b5f2aa3d6bee6e4dbeb217933c510937349c2b3669bd5f09eaa7110981ff7028ce7333e550b514426b49bea0b1c4
    17030302e0   //这里时 record layer的头:0x17-> 23, application data 数据类型,0303是tls1.2协议
    
    长度: 2e0 = 736
    25564d8391292b6d06e3faefd0f122de48ba1ce3a95e9f215294dbafb00194ead8ad45ee1305960e879a21ef571365e74512694b2d895e0968c1e8ab9df125a22a2a311237bcfc31324e625edc6f7babd71b50d0636ffb8c8716dc7c2e0e6bda3ce44f1e476687d0e81b210471b6401f2034154f8c90eaf86bbf3dbf0ae5883b4dd150b96ea215736a5499a41f5c71e142307445c64aa882565bd887488b03348bb5c18c29b2d6dcea5c0d54e8e5960b141d336475cc6d05f8cd00b8ebc1fe323bee3444e99e16653927c56ed8b675a33676ccfd999396ef391a564c5b10b1b3071c381830c1458a12b93a68910b047d819a0e95784d93063864bae8e55d010829b14afee269af861a900951f1ba5ebe4de53b1cb76a06595208203dadea3803a2556d1994188a69e1949329974e85a13992d738abd5e28f84048449ccf3396309e44597b10a8ea2f0ae1c005b8d76cbe4bb8cb8f3c8f972422bcb40929ae79a2134a34201ae746cccf1ac1197dd24284738577601a14b6d57374dfa2a0e2074e7255d9dc3f3baa3dd95d8181d1322ee03022aa75e425ffefcbd0d47c1790245bd6a2684353a79f93280e076370448a856de8279bcdf70bfdb47bf3f98e9f73981ffd8cba547a6bedc323056f57d65ee2a0c6c1cb0a828c9775003ba16f251c4f6b1c9fad701ad4cf049678e848f36c3849540a8ce5b349696a148d09d36bb81d49111d6f8c8a115bb4a8a261f57fb1364025e71947ae4d6893daa3e2f018e821e516e8d0d664a35b36e61ec55e24adeaf52fc1829f3d9bf353c61ef3c49a34e0f9da67e97eb5e8d048c2c973547f681368055a42959e7bb9e203ef166d83d28017a5565ba8ea429ec67e9e741759a80e8
    但是剩下的数据长度只有600多个字节,少于头里指定的736个字节;
    
    Frame 253710: 598 bytes on wire (4784 bits), 598 bytes captured (4784 bits)
    Ethernet II, Src: Vmware_08:9c:78 (00:0c:29:08:9c:78), Dst: Alcatel-_c8:f4:c8 (e8:e7:32:c8:f4:c8)
    Internet Protocol Version 6, Src: 2620:0:62:13::17b:0, Dst: 2620:0:62:22a::1
    Transmission Control Protocol, Src Port: 53780, Dst Port: 8888, Seq: 32671116, Ack: 41058290, Len: 524
        Source Port: 53780
        Destination Port: 8888
        [Stream index: 5]
        [TCP Segment Len: 524]
        Sequence number: 32671116    (relative sequence number)
        [Next sequence number: 32671640    (relative sequence number)]
        Acknowledgment number: 41058290    (relative ack number)
        0101 .... = Header Length: 20 bytes (5)
        Flags: 0x018 (PSH, ACK)
        Window size value: 218
        [Calculated window size: 27904]
        [Window size scaling factor: 128]
        Checksum: 0x52e3 [unverified]
        [Checksum Status: Unverified]
        Urgent pointer: 0
        [SEQ/ACK analysis]
        [Timestamps]
        TCP payload (524 bytes)
    Transport Layer Security
        TLSv1.2 Record Layer: Handshake Protocol: Encrypted Handshake Message
        TLSv1.2 Record Layer: Alert (Level: Fatal, Description: Unexpected Message)
            Content Type: Alert (21)
            Version: TLS 1.2 (0x0303)
            Length: 2
            Alert Message
                Level: Fatal (2)
                Description: Unexpected Message (10)
    
    

    消息样例

    Encrypted Alert

    需要做decode,才能看出alert消息是什么
    在这里插入图片描述

    展开全文
  • 出参这一块的解密就报javax.crypto.BadPaddingException: Decryption error这个错误。 这是入参时候的处理,这边aes-key是正常解密出来了的。 ![图片说明]...
  • Error while sending TLS Alert (Fatal:InternalError): System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: Unable to read data from the transport ...
  • 前言 进行接口调试时RSA加解密中的...javax.crypto.BadPaddingException: Decryption error at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380) ~[na:1.8.0_131] at sun.security.rsa.RSAPadding.unp...

    前言

    进行接口调试时RSA加解密中的解密操作时报错,下面是详细的报错:

    javax.crypto.BadPaddingException: Decryption error
    	at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380) ~[na:1.8.0_131]
    	at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291) ~[na:1.8.0_131]
    	at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363) ~[sunjce_provider.jar:1.8.0_112]
    	at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389) ~[sunjce_provider.jar:1.8.0_112]
    	at javax.crypto.Cipher.doFinal(Cipher.java:2165) ~[na:1.8.0_121]
    	at XXXXX.util.RSACipherUtil.decrypt(RSACipherUtil.java:96) ~[classes/:na]
    	at XXXXX.config.InitApiContextInterceptor.preHandle(InitApiContextInterceptor.java:97) ~[classes/:na]
    	at org.springframework.web.servlet.HandlerExecutionChain.applyPreHandle(HandlerExecutionChain.java:136) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:986) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851) ~[spring-webmvc-5.0.6.RELEASE.jar:5.0.6.RELEASE]
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:728) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:472) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:316) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:395) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.StandardHostValve.status(StandardHostValve.java:254) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:349) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:175) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1468) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_131]
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_131]
    	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.31.jar:8.5.31]
    	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_131]
    

    通过端点调试发现是这段代码报错:

    在这里插入图片描述

    针对上面的问题,我们要首先明白一点,RSA加解密是怎么工作的才能知道我们错误点在哪里?

    RSA 简介:

    通过百度可以知道RSA加密是一种非对称加密。可以在不直接传递密钥的情况下,完成解密。这能够确保信息的安全性,避免了直接传递密钥所造成的被破解的风险。是由一对密钥来进行加解密的过程,分别称为公钥和私钥。两者之间有数学相关,该加密算法的原理就是对一极大整数做因数分解的困难性来保证安全性。通常个人保存私钥,公钥是公开的。
     RSA加密对明文的长度有所限制,规定需加密的明文最大长度=密钥长度-11(单位是字节,即byte),所以我们项目开发时在加密和解密的过程中需要分块进行,要知道密钥默认是1024位,即1024位/8位-11=128-11=117字节。所以默认加密前的明文最大长度117字节,解密密文最大长度为128字。那么为啥两者相差11字节呢?是因为RSA加密使用到了填充模式(padding),即内容不足117字节时会自动填满,用到填充模式自然会占用一定的字节,而且这部分字节也是参与加密的。

    密钥长度的设置就是上面例子的第32行。可自行调整,当然非对称加密随着密钥变长,安全性上升的同时性能也会有所下降。
       
       
    解决办法:

    package com.zcw.rsa;
    
    import java.io.ByteArrayOutputStream;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Signature;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import javax.crypto.Cipher;
    import org.apache.commons.codec.binary.Base64;
    
    /**
     * @ClassName : TestRSA
     * @Description : 进行RSA加解密练习
     * @Author : Zhaocunwei
     * @Date: 2020-04-24 10:50
     */
    public class TestRSA {
        /**
         * RSA最大加密明文大小
        */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    
        /**
         * RSA最大解密密文大小
         */
        private static final int MAX_DECRYPT_BLOCK = 128;
    
        /**
         * 获取密钥对
         *
         * @return 密钥对
         */
        public static KeyPair getKeyPair() throws Exception {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(1024);
            return generator.generateKeyPair();
        }
    
        /**
         * 获取私钥
         *
         * @param privateKey 私钥字符串
         * @return
         */
        public static PrivateKey getPrivateKey(String privateKey) throws Exception {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
            return keyFactory.generatePrivate(keySpec);
        }
    
        /**
         * 获取公钥
         *
         * @param publicKey 公钥字符串
         * @return
         */
        public static PublicKey getPublicKey(String publicKey) throws Exception {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
            return keyFactory.generatePublic(keySpec);
        }
    
        /**
         * RSA加密
         *
         * @param data 待加密数据
         * @param publicKey 公钥
         * @return
         */
        public static String encrypt(String data, PublicKey publicKey) throws Exception {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            int inputLen = data.getBytes().length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offset = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offset > 0) {
                if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
                }
                out.write(cache, 0, cache.length);
                i++;
                offset = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
            // 加密后的字符串
            return new String(Base64.encodeBase64String(encryptedData));
        }
    
        /**
         * RSA解密
         *
         * @param data 待解密数据
         * @param privateKey 私钥
         * @return
         */
        public static String decrypt(String data, PrivateKey privateKey) throws Exception {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] dataBytes = Base64.decodeBase64(data);
            int inputLen = dataBytes.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offset = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offset > 0) {
                if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
                }
                out.write(cache, 0, cache.length);
                i++;
                offset = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            // 解密后的内容
            return new String(decryptedData, "UTF-8");
        }
    
        /**
         * 签名
         *
         * @param data 待签名数据
         * @param privateKey 私钥
         * @return 签名
         */
        public static String sign(String data, PrivateKey privateKey) throws Exception {
            byte[] keyBytes = privateKey.getEncoded();
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey key = keyFactory.generatePrivate(keySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initSign(key);
            signature.update(data.getBytes());
            return new String(Base64.encodeBase64(signature.sign()));
        }
    
        /**
         * 验签
         *
         * @param srcData 原始字符串
         * @param publicKey 公钥
         * @param sign 签名
         * @return 是否验签通过
         */
        public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
            byte[] keyBytes = publicKey.getEncoded();
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey key = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance("MD5withRSA");
            signature.initVerify(key);
            signature.update(srcData.getBytes());
            return signature.verify(Base64.decodeBase64(sign.getBytes()));
        }
    
        public static void main(String[] args) {
            try {
                // 生成密钥对
                KeyPair keyPair = getKeyPair();
                String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
                String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
                System.out.println("私钥:" + privateKey);
                System.out.println("公钥:" + publicKey);
                // RSA加密
                String data = "需要加密的内容";
                String encryptData = encrypt(data, getPublicKey(publicKey));
                System.out.println("加密后内容:" + encryptData);
                // RSA解密
                String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
                System.out.println("解密后内容:" + decryptData);
    
                // RSA签名
                String sign = sign(data, getPrivateKey(privateKey));
                // RSA验签
                boolean result = verify(data, getPublicKey(publicKey), sign);
                System.out.print("验签结果:" + result);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.print("加解密异常");
            }
        }
    }
    

    运行结果:

    在这里插入图片描述

    展开全文
  • RSA加密/解密 Decryption error异常解决

    千次阅读 2019-09-29 22:02:33
    RSA加密/解密 Decryption error异常解决 import java.io.ByteArrayOutputStream; import java.security.Key; import java.s...

    RSA加密/解密 Decryption error异常解决

    import java.io.ByteArrayOutputStream;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.crypto.Cipher;
    
    import org.apache.commons.codec.binary.Base64;
    
    public class RSATest {
    
        private static final String ALGORITHM = "RSA";
        private static final String PUBLICK_EY = "PUBLICK_EY";
        private static final String PRIVATE_KEY = "PRIVATE_KEY";
        /**
         * 加密算法
         */
        private static final String CIPHER_DE = "RSA";
        /**
         * 解密算法
         */
        private static final String CIPHER_EN = "RSA";
        /**
         * 密钥长度
         */
        private static final Integer KEY_LENGTH = 1024;
    
        /**
         * RSA最大加密明文大小
         */
        private static final int MAX_ENCRYPT_BLOCK = 117;
        /**
         * RSA最大解密密文大小
         */
        private static final int MAX_DECRYPT_BLOCK = 128;
    
        /**
         * 生成秘钥对,公钥和私钥
         *
         * @return
         * @throws NoSuchAlgorithmException
         */
        public static Map<String, Object> genKeyPair() throws NoSuchAlgorithmException {
            Map<String, Object> keyMap = new HashMap<String, Object>();
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
            keyPairGenerator.initialize(KEY_LENGTH); // 秘钥字节数
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            keyMap.put(PUBLICK_EY, publicKey);
            keyMap.put(PRIVATE_KEY, privateKey);
            return keyMap;
        }
    
        /**
         * 公钥加密
         *
         * @param data
         * @param publicKey
         * @return
         * @throws InvalidKeySpecException
         */
        public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
            // 得到公钥
            byte[] keyBytes = Base64.decodeBase64(publicKey.getBytes());
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            Key key = keyFactory.generatePublic(x509EncodedKeySpec);
            // 加密数据,分段加密  
            Cipher cipher = Cipher.getInstance(CIPHER_EN);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            int inputLength = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offset = 0;
            byte[] cache;
            int i = 0;
            while (inputLength - offset > 0) {
                if (inputLength - offset > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offset, inputLength - offset);
                }
                out.write(cache, 0, cache.length);
                i++;
                offset = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;
        }
    
        /**
         * 私钥解密
         *
         * @param data
         * @param privateKey
         * @return
         * @throws Exception
         */
        public static byte[] decryptByPrivateKey(byte[] data, String privateKey) throws Exception {
            // 得到私钥  
            byte[] keyBytes = Base64.decodeBase64(privateKey.getBytes());
            PKCS8EncodedKeySpec pKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
            Key key = keyFactory.generatePrivate(pKCS8EncodedKeySpec);
            // 解密数据,分段解密
            Cipher cipher = Cipher.getInstance(CIPHER_DE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            int inputLength = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offset = 0;
            byte[] cache;
            int i = 0;
            byte[] tmp;
            while (inputLength - offset > 0) {
                if (inputLength - offset > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offset, inputLength - offset);
                }
    //            out.write(cache, 0, cache.length);
                out.write(cache);
                i++;
                offset = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            return decryptedData;
        }
    
        /**
         * 获取公钥
         *
         * @param keyMap
         * @return
         */
        public static String getPublicKey(Map<String, Object> keyMap) {
            Key key = (Key) keyMap.get(PUBLICK_EY);
            String str = new String(Base64.encodeBase64(key.getEncoded()));
            return str;
        }
    
        /**
         * 获取私钥
         *
         * @param keyMap
         * @return
         */
        public static String getPrivateKey(Map<String, Object> keyMap) {
            Key key = (Key) keyMap.get(PRIVATE_KEY);
            String str = new String(Base64.encodeBase64(key.getEncoded()));
            return str;
        }
    
        public static void main(String[] args) throws Exception {
            Map<String, Object> keyMap = RSATest.genKeyPair();
            String publicKey = RSATest.getPublicKey(keyMap);
            String privateKey = RSATest.getPrivateKey(keyMap);
            System.out.println("公钥:" + publicKey);
            System.out.println("私钥:" + privateKey);
            // 公钥加密  
            String sourceStr = "<REQ><HEAD><ReqCode>WDIS</ReqCode><MsgNo>500</MsgNo><MsgId>20171113123408</MsgId><MsgRef>20171113123408</MsgRef><Teller>00000951</Teller><BchCde>800000000</BchCde><WorkDate>20171113</WorkDate><WorkTime>123408</WorkTime></HEAD><MSG><ApplSeq>1666645</ApplSeq><AppAdvice>同意</AppAdvice><AppConclusion>10</AppConclusion><ApptList><Result><ApptTyp>01</ApptTyp><CustName>林羽凡</CustName><IdTyp>20</IdTyp><IdNo>350521196211216597</IdNo><ApptStartDate>1962-11-21</ApptStartDate><ApptAge>55</ApptAge><CrtBch>800000001</CrtBch><CrtDt>2017-11-13</CrtDt><IndivInfo><IndivSex>10</IndivSex><IndivMarital>20</IndivMarital><IndivEdu>10</IndivEdu><IndivDegree>4</IndivDegree><RegProvince>110000</RegProvince><RegCity>110100</RegCity><LiveInfo>10</LiveInfo><LiveProvince>110000</LiveProvince><LiveCity>110100</LiveCity><LiveArea>110105</LiveArea><LiveAddr>北京市市辖区朝阳区xxxxxxx</LiveAddr><LiveZip>100000</LiveZip><LiveMj>299.66</LiveMj><LocalResid>10</LocalResid><IndivMobile>13522015858</IndivMobile><PositionOpt>10</PositionOpt><IndivEmpName>山东科技有限公司</IndivEmpName><IndivEmpTyp>Z</IndivEmpTyp><IndivMthInc>500000.0</IndivMthInc><MailOpt>A</MailOpt><MailProvince>110000</MailProvince><MailCity>110100</MailCity><MailArea>110105</MailArea><MailAddr>北京市市辖区朝阳区xxxxxxx</MailAddr><IndivProfsn>00</IndivProfsn><IndivIndtryPaper>Q</IndivIndtryPaper><IndivPro>1</IndivPro><PptyLive>Y</PptyLive></IndivInfo><ExtInfo><SpouseName>黄海涛</SpouseName><SpouseIdTyp>20</SpouseIdTyp><SpouseIdNo>110105198310200112</SpouseIdNo><SpouseMobile>13589565487</SpouseMobile></ExtInfo><RelList><Result><RelName>黄海涛</RelName><RelMobile>13589565487</RelMobile><RelRelation>06</RelRelation></Result><Result/></RelList></Result><Result><ApptRelation>06</ApptRelation><ApptTyp>02</ApptTyp><CustName>黄海涛</CustName><IdTyp>20</IdTyp><IdNo>110105198310200112</IdNo><ApptStartDate>1983-10-20</ApptStartDate><ApptAge>34</ApptAge><CrtBch>800000001</CrtBch><CrtDt>2017-11-13</CrtDt><IndivInfo><IndivSex>20</IndivSex><IndivMarital>20</IndivMarital><IndivDegree>0</IndivDegree><LiveAddr>北京市市辖区朝阳区xxxxxxx</LiveAddr><LiveMj>299.66</LiveMj><LocalResid>10</LocalResid><IndivMobile>13581829258</IndivMobile><PositionOpt>50</PositionOpt><IndivEmpName>个体</IndivEmpName><IndivEmpTyp>Z</IndivEmpTyp><MailOpt>A</MailOpt><MailAddr>北京市市辖区朝阳区xxxxxxx</MailAddr><PptyLive>Y</PptyLive></IndivInfo><ExtInfo><SpouseName>林羽凡</SpouseName><SpouseIdTyp>20</SpouseIdTyp><SpouseIdNo>350521196211216597</SpouseIdNo><SpouseMobile>135xxxxxxxx</SpouseMobile></ExtInfo><RelList><Result><RelName>黄海涛</RelName><RelMobile>135xxxxxxxx</RelMobile><RelRelation>06</RelRelation></Result></RelList></Result></ApptList><HouInfo><Location>朝阳区xxxxx</Location><HouseArea>299.66</HouseArea><CompDate>2009-01-01</CompDate><PropRight>12</PropRight><HouseKindList>01</HouseKindList><HouseClass>01</HouseClass><HouseType>09</HouseType><HouseFrameSign>99</HouseFrameSign><HouseCertKind>03</HouseCertKind><PptyProvince>110000</PptyProvince><PptyCity>110100</PptyCity><PptyArea>110105</PptyArea><PptyAddr>朝阳区xxxxx</PptyAddr><OwnerName>林羽凡</OwnerName><HouseCertNo>北京房权证朝字第907946号</HouseCertNo></HouInfo><GurtInfo><gurtAmt>2.0E7</gurtAmt><collateralValue>2.0E7</collateralValue><gurtStartDt>2017-11-02</gurtStartDt><gurtEndDt>2020-11-02</gurtEndDt><gurtSignDt>2017-11-02</gurtSignDt><collInd>Y</collInd><regSts>02</regSts><mortgagorTyp>01</mortgagorTyp><rightCertTyp>01</rightCertTyp><rightCertNo>京(2017)朝不动产证明第0075996号</rightCertNo><custName>林羽凡</custName><mortgageType>01</mortgageType><isRent>N</isRent><obligorName>林羽凡</obligorName></GurtInfo><ApplInfo><ApplCde>201711131200000131495</ApplCde><ApplSeq>1666645</ApplSeq><IdTyp>20</IdTyp><IdNo>350521196211216597</IdNo><CustName>林羽凡</CustName><ProPurAmt>2.0E7</ProPurAmt><Purpose>OTH</Purpose><AppOrigin>03</AppOrigin><DocChannel>SYS001</DocChannel><ApplyDt>2017-10-27</ApplyDt><FstPct>0</FstPct><FstPay>0</FstPay><ApplyAmt>2.0E7</ApplyAmt><ApprvAmt>2.0E7</ApprvAmt><ApplyTnr>36</ApplyTnr><ApplyTnrTyp>M</ApplyTnrTyp><ApprvTnr>36</ApprvTnr><ApprvTnrTyp>M</ApprvTnrTyp><LoanTyp>ZYYH002</LoanTyp><MtdCde>LM004</MtdCde><LoanFreq>1M</LoanFreq><MtdMode>RV</MtdMode><PriceIntRat>0.07799998999999999</PriceIntRat><CrtDt>2017-11-02</CrtDt><TypGrp>04</TypGrp><GutrOpt>20</GutrOpt><CrtBch>800000001</CrtBch><CrtBchInd>N</CrtBchInd><RepcOpt>NYF</RepcOpt><DueDayOpt>2</DueDayOpt><DueDay>21</DueDay><Form>04</Form></ApplInfo><MtdList><Result><MtdCde>LM004</MtdCde><MtdTyp>04</MtdTyp><LoanInstal>36</LoanInstal><ApplMtdRateTyp>1</ApplMtdRateTyp><ApplMtdRateFloat>64.2105</ApplMtdRateFloat></Result></MtdList><AcctList><Result><ApplAcKind>01</ApplAcKind><ApplAcTyp>01</ApplAcTyp><RpymAcBank>105100000017</RpymAcBank><RpymAcNam>于三</RpymAcNam><RpymAcNo>6217000010039470748</RpymAcNo><RpymIdTyp>20</RpymIdTyp><RpymMethod>1</RpymMethod></Result><Result><ApplAcKind>02</ApplAcKind><ApplAcTyp>01</ApplAcTyp><RpymAcBank>105100000017</RpymAcBank><RpymAcNam>林羽凡</RpymAcNam><RpymAcNo>5522450010194467</RpymAcNo><RpymIdTyp>20</RpymIdTyp><RpymIdNo>350521196211216597</RpymIdNo><RpymMethod>1</RpymMethod></Result></AcctList></MSG></REQ>";
            System.out.println("加密前:" + sourceStr);
            byte[] encryptStrByte = RSATest.encryptByPublicKey(sourceStr.getBytes(), publicKey);
            byte[] btt = Base64.encodeBase64(encryptStrByte);
            String encryptStr = new String(btt);
            System.out.println("加密后:" + encryptStr);
            System.out.println("长度:" + encryptStr.length());
            // 私钥解密  
            byte[] decryptStrByte = RSATest.decryptByPrivateKey(Base64.decodeBase64(Base64.encodeBase64(encryptStrByte)), privateKey);
            String sourceStr_1 = new String(decryptStrByte);
            System.out.println("解密后:" + sourceStr_1);
        }
    }  

    密钥长度修改为2048位时,报以下错误:

    Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
        at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
        at sun.security.rsa.RSAPadding.unpad(Unknown Source)
        at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
        at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
        at javax.crypto.Cipher.doFinal(Cipher.java:2223)
        at com.caxs.esign.util.MYtest.decryptByPrivateKey(MYtest.java:117)
        at com.caxs.esign.util.MYtest.main(MYtest.java:175)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

    这是由于最大解密长度不正确导致报错,MAX_DECRYPT_BLOCK应等于密钥长度/8(1byte=8bit),所以当密钥位数为2048时,最大解密长度应为256.

    private static final int MAX_DECRYPT_BLOCK = 128;

    转载于:https://www.cnblogs.com/jpfss/p/10204455.html

    展开全文
  • decryption

    2010-01-16 17:34:40
    asdfasfdasdfafd decryption
  • Deciphering Malware’s use of TLS (without Decryption)是Anderson等人于2016年发表的关于采用机器学习进行恶意加密流量检测的论文,该论文以特征提取和特征设计为主要内容,最后将提取的特征分为四个特征子集,...


    前言

    本文是关于个人阅读Deciphering Malware’s use of TLS (without Decryption)时的个人阅读笔记,原文点击此处

    一、简介

    Deciphering Malware’s use of TLS (without Decryption)是Anderson等人于2016年发表的关于采用机器学习进行恶意加密流量检测的论文,该论文以特征提取和特征设计为主要内容,最后将提取的特征分为四个特征子集,然后采用逻辑斯蒂二分类模型和多分类模型进行训练,得到可用于区分恶意加密流量和正常加密流量的二分类器及用于进一步找出恶意加密流量所属恶意软件家族的多分类器。该论文通过对不同特征子集训练所得的分类器进行验证,得出特征设计对于采用机器学习的方法进行恶意加密流量检测的重要性。

    二、数据集

    数据集包括恶意加密流量和正常加密流量,恶意加密流量是通过沙箱运行恶意软件采集的通过TLS协议加密流量,共含18种恶意软件家族,详见图1。正常加密流量是通过截获公司内部流量所得。由于进行沙箱模拟的操作系统中也有可能额外发出一些加密流量,所以对通过沙箱模拟的恶意流量安装其TLS握手包中采用的密码套件列表是否与操作系统提供的密码套件列表进行进行了筛选。
    图1 文章中使用到的18类恶意软件家族

    三、特征提取

    图2-a 恶意TLS流量(红)与正常TLS流量(蓝)客户端提供的密码套件对比
    图2-b 恶意TLS流量(红)与正常TLS流量(蓝)客户端公钥长度对比
    图2-c 恶意TLS流量(红)与正常TLS流量(蓝)采用的客户端对比
    图2-d 恶意TLS流量(红)与正常TLS流量(蓝)客户端提供的TLS扩展件对比
    图2 恶意TLS流量与正常TLS流量客户端提供的密码套件、公钥长度、TLS扩展件、采用的客户端共四种特征数据对比图,其中红色代表恶意加密流量,蓝色代表正常加密流量,且为方便展示已对各密码

    图3-a 恶意TLS流量(红)与正常TLS流量(蓝)服务器端选择的密码套件对比
    图3-b 恶意TLS流量(红)与正常TLS流量(蓝)证书有效时长对比
    图3-c 恶意TLS流量(红)与正常TLS流量(蓝)SAN证书数量对比
    图3-d 恶意TLS流量(红)与正常TLS流量(蓝)服务器端采用的TLS扩展件对比
    图3 恶意TLS流量与正常TLS流量服务器端采用的密码套件、证书有效时长、SAN证书数量、服务器端选择的TLS扩展件四种特征数据对比图,其中红色代表恶意加密流量,蓝色代表正常加密流量,且为方便展示已对各密码套件和TLS扩展件进行编号
    图4 不同恶意软件家族所用的TLS客户端、提供的密码套件、TLS扩展项和客户端公钥长度
    图4 不同恶意软件家族所用的TLS客户端、提供的密码套件、TLS扩展项和客户端公钥长度
    图5 不同恶意软件家族服务器端特有IP地址、自签证书数量、选择的密码套件及证书类别对比图5 不同恶意软件家族服务器端特有IP地址、自签证书数量、选择的密码套件及证书类别对比

    该论文对恶意加密流量与正常加密流量之间及不同恶意软件家族产生的恶意加密流量之间的各方面数据进行了分析,分析结果如图2、3、4、5。最后根据分析结果提取了五种特征,包括Metadata、SPLT、BD、Unencrypted TLS Header Information、SS

    Metadata:即加密流量元数据,包括输入数据长度、输出数据长度、输入包数量、输出包数量、源端口、目的端口、流量传播的时长。
    SPLT:Sequence of Packet Lengths and Times,即数据包差昂达度和到达间隔时长序列。
    BD:Byte distribution,即字节分布,是用于记录字节分布情况且长度为256的数组。
    Unencrypted TLS Header Information:即处于握手阶段还未进行加密的TLS协议的头部信息,包括客户端提供的密码套件列表和TLS扩展项、服务端选择的密码套件和TLS扩展项、签名证书、客户端公钥长度、记录的长度和时间和类型序列。
    SS:Self-Signed,即TLS协议中使用的证书是否为自签证书(采用SS代表该特征)。

    该论文将以上五种特征划分了四个特征子集,特征子集1仅包括Meta、SPLT、BD三种特征,特征子集2仅包括Unencrypted TLS Header Information这一种特征,特征子集3包括Meta、SPLT、BD、Unencrypted TLS Header Information四种特征,特征子集4包括Meta、SPLT、BD、Unencrypted TLS Header Information、SS五种特征。再采用逻辑斯蒂二分类模型和多分类模型分别对以上四个特征子集进行了训练,共获得八个分类器,包括四个二分类器和四个多分类器。二分类器用于区分恶意加密流量和正常加密流量,多分类器用于找出恶意加密流量所属的恶意软件家族。

    四、实验结果

    实验结果如图6、7,可见包括Meta、SPLT、BD、Unencrypted TLS Header Information、SS五种特征的特征子集4所训练的分类器效果最佳。由五种特征共同训练所得二分类器准确率可达99.6%,多分类器准确率对于多数恶意软件家族可达100%,其余恶意软件家族准确率均在96%以上。同时,仅采用TLS协议中的参数作为特征时,对恶意加密流量与正常加密流量分类的准确率为98.2%,且恶意软件家族Deshacop的分类准确率仅63.6%,由此可见特征设计对于该类方法的重要性。
    图6 采用不同特征子集训练二分类器的准确率,All Data指恶意加密流量中含由底层操作系统发出的TLS流量,No SChannel指不含由底层操作系统发出的TLS流量
    图6 采用不同特征子集训练二分类器的准确率,All Data指恶意加密流量中含由底层操作系统发出的TLS流量,No SChannel指不含由底层操作系统发出的TLS流量
    图7 采用不同特征子集训练多分类器的准确率
    图7 采用不同特征子集训练多分类器的准确率

    展开全文
  • RSA解密报 Decryption error

    千次阅读 2018-11-29 16:45:21
    最近在使用RSA加密密码,后台test类测试没问题,但js前端传过来却解析失败,报Decryption error.纠结了一晚上,终于发现了问题的所在 简单介绍一下: RSA可以实现非对称加密。一直是最广为使用的"非对称...
  • Siemens s7-200 password decryptor
  • Picked up JAVA_TOOL_... javax.crypto.BadPaddingException: Decryption error at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:383) at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:294) at ...
  • Exception in thread "main" javax.crypto.BadPaddingException: Decryption error at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380) at sun.security.rsa.RSAPadding.un...
  • universal data decrypter
  •  BadPaddingException Decryption error     cipher = Cipher.getInstance("RSA");// RSA解密 改成"RSA/ECB/PKCS1Padding" 搞定   还遇到过get传的加密数据没有urldecode,导致+全变成 空格,...
  • pip._vendor.urllib3.exceptions.SSLError: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] decryption failed or bad record mac (_ssl.c:2309) pip install tensorflow==2.1.0 -i https://pypi.douban.com/simple ...
  • Checkout token decryption failed see please attached below http://prntscr.com/qah6mv </p> <p>I am use demo account My Merchant ID: e12b1507-b333-4bd5-94d2-d299288d58e0 publickey : 1IK3aOYpmaZaW28...
  • Microsoft CryptoAPI (CAPI) usage sample for decryption in flat assembler

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 11,783
精华内容 4,713
关键字:

decryption