RSA加解密及加密数据长度处理

RSA加密请求报错:javax.crypto.BadPaddingException: Decryption error ????摘要 今天分享下 —— RSA加密 请求报错:javax.crypto.BadPaddingException: Decryption error,欢迎关注! 相关文章阅读:springboot+security基于前后端分离的RSA密码加密登录流程 ????解决方法 在登录方法里把空格替换成+号即可,就问你骚不骚 String inputDecryptData = ""; try { Object privateKey = redisUtil 阅读详情

一、关于RSA

     RSA是非对称加密,由一个公钥和私玥组成。公钥加密-私玥解密或私钥加密-公玥解密。其安全性生成的位数有关,位数越大越安全,目前最大支持2048。RSA加密的原理是通过算法实现的,主要用到的是欧拉定理。生成后的是base64 编码过的。

    缺点,效率底,小量数据加密可以使用RSA

二、流程

     RSA算法常用于非对称加密,非对称加密流程如下:

   (1)乙方生成两把密钥(公钥和私钥)。公钥是公开的,任何人都可以获得,私钥则是保密的。

   (2)甲方获取乙方的公钥,然后用它对信息加密。

   (3)乙方得到加密后的信息,用私钥解密。

三、代码实现

package com.res.core;


import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class SecurityUtil {

    //private final static Logger log = Logger.getLogger(SecurityUtil.class);
    private String secretKey;//加解密密钥
    private String charetSet = "utf-8";

    /**
     * 加密算法RSA
     */
    private static final String KEY_ALGORITHM = "RSA";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;
    /**
     * 常量0
     */
    private static final int ZERO = 0;

    public SecurityUtil(){

    }

    public SecurityUtil(String secretKey) {
        this.setSecretKey(secretKey);
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public void setCharetSet(String charetSet) {
        this.charetSet = charetSet;
    }

    /**
     * AES加密
     *
     * @param str
     * @return
     */
    public String encryptStrWithAes(String str) {
        String resStr = null;
        try {
            byte[] raw = secretKey.getBytes(charetSet);
            SecretKeySpec key = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] byteContent = str.getBytes(charetSet);
            byte[] encrypted = cipher.doFinal(byteContent);
            BASE64Encoder encoder = new BASE64Encoder();
            resStr = encoder.encode(encrypted);
        } catch (Exception e) {
            //log.error("AES加密失败", e);
            throw new RuntimeException("AES加密失败",e) ;
        }
        return resStr;
    }

    /**
     * AES解密
     *
     * @param str
     * @return
     */
    public String decryptStrWithAes(String str) {
        String resStr = null;
        try {
            byte[] raw = secretKey.getBytes(charetSet);
            SecretKeySpec key = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, key);
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] decrypted = cipher.doFinal(decoder.decodeBuffer(str));
            resStr = new String(decrypted, charetSet);
        } catch (Exception e) {
            //log.error("AES解密失败", e);
            throw new RuntimeException("AES解密失败",e) ;
        }
        return resStr;
    }

    public String aesEncode(String str){

        String resStr = null;
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(secretKey.getBytes(charetSet));
            KeyGenerator kGen = KeyGenerator.getInstance("AES");
            kGen.init(128, random);
            SecretKey secretKey = kGen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
            byte[] byteContent = str.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            BASE64Encoder encoder = new BASE64Encoder();
            resStr= encoder.encode(result);
        } catch (Exception e){
            e.printStackTrace();
        }
        return resStr;
    }

    public String aesDecode(String str){
        String resStr = null;
        try {

            KeyGenerator kGen = KeyGenerator.getInstance("AES");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(secretKey.getBytes());
            kGen.init(128, random);
            SecretKey secretKey = kGen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] decrypted = cipher.doFinal(decoder.decodeBuffer(str));
            resStr = new String(decrypted, charetSet);
        } catch (Exception e){
            e.printStackTrace();
        }
        return resStr;
    }

    /**
     * 随机生成密钥对
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        System.out.println("公钥:" + publicKeyString);
        System.out.println("私钥:" + privateKeyString);

    }
    /**
     * RSA公钥加密
     * @param str
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String encrypt( String str, String publicKey ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * RSA私钥解密
     * @param str
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        return new String(cipher.doFinal(inputByte));
    }

    /**
     * 公钥加密
     *
     * @param content      源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(String content, String publicKey)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        byte[] data = content.getBytes(StandardCharsets.UTF_8);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        byte[] encrypt = encrypt(data, KeyFactory.getInstance(KEY_ALGORITHM), keyFactory.generatePublic(x509KeySpec));
        return  Base64.encodeBase64String(encrypt);
    }


    /**
     * 私钥加密
     *
     * @param content       源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String encryptByPrivateKey(String content, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        byte[] data = content.getBytes(StandardCharsets.UTF_8);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        byte[] encrypt = encrypt(data, keyFactory, privateK);
        return Base64.encodeBase64String(encrypt);
    }


    /**
     * 私钥解密
     *
     * @param content 已加密数据
     * @param privateKey    私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPrivateKey(String content, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        //64位解码加密后的字符串
        byte[] encryptedData = Base64.decodeBase64(content.getBytes(StandardCharsets.UTF_8));
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return new String(decrypt(encryptedData, keyFactory, keyFactory.generatePrivate(pkcs8KeySpec)));
    }


    /**
     * 公钥解密
     *
     * @param content 已加密数据
     * @param publicKey     公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String content, String publicKey)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        //64位解码加密后的字符串
        byte[] encryptedData = Base64.decodeBase64(content.getBytes(StandardCharsets.UTF_8));
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        return new String(decrypt(encryptedData, keyFactory, publicK));

    }

    /**
     * 解密公共方法
     */
    private static byte[] decrypt(byte[] data, KeyFactory keyFactory, Key key) throws Exception {

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, key);
        return encryptAndDecrypt(data, cipher, MAX_DECRYPT_BLOCK);
    }

    /**
     * 加密公共方法
     */
    private static byte[] encrypt(byte[] data, KeyFactory keyFactory, Key key) throws Exception {
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return encryptAndDecrypt(data, cipher, MAX_ENCRYPT_BLOCK);
    }


    /**
     * 加密解密分段处理公共方法
     */
    private static byte[] encryptAndDecrypt(byte[] data, Cipher cipher, int maxSize) throws Exception {
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = ZERO;
        byte[] cache;
        int i = ZERO;
        // 对数据分段加密
        while (inputLen - offSet > ZERO) {
            if (inputLen - offSet > maxSize) {
                cache = cipher.doFinal(data, offSet, maxSize);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, ZERO, cache.length);
            i++;
            offSet = i * maxSize;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }


    public static String decryptRSADefault(String privateKeyStr,String data) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] privateKeyArray = privateKeyStr.getBytes();
        byte[] dataArray = data.getBytes();
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyArray));
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(cipher.doFinal(Base64.decodeBase64(dataArray)), StandardCharsets.UTF_8);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            /*genKeyPair();*/
            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDrqdHrXcgPbVvJkVfV9yyWfOsQiMSWtZRz40GUDjhiLmW6lsrU5" +
                    "HixbIc69O6ms4LL3joYnFvkvTRAkBbuMTRY6aaup6Cpsg+9HDFS6qlSPeq53VlTkoIZ990QvSL6fMyT/mwt7T66QevU8cXUHv3RT4Sbj5TclIwr2PXiom84mwIDAQAB";

            String privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAOup0etdyA9tW8mRV9X3LJZ86xCIxJa1lHPjQZQOOGIuZbqWytTke" +
                    "LFshzr07qazgsveOhicW+S9NECQFu4xNFjppq6noKmyD70cMVLqqVI96rndWVOSghn33RC9Ivp8zJP+bC3tPrpB69TxxdQe/dFPhJuPlNyUjCvY9eKibzibAgM" +
                    "BAAECgYAnJ9MqIS3halEq34xRj70Hz/+agq7vP4JH8wVtXSN/JKhgZTeUQdXP3PFnGVUhu4fK6cSLXEdkbQ9mfspgjypcHeV+lTzqR52oiuPEiMJPHFsSNYslorL" +
                    "ONmSWHyFGZAQe9H6Tl02GuIkSAXeruPYIHkx8WBGsIIwUeO3vRyXtUQJBAP033/PF8yAQwOJ6nnthcaaeSfu9zovPicKZ6P+5gXdBQYXX61cLqDX3gnyASZyrkgRn7" +
                    "FiZqZF2HPitPLJ+w+MCQQDuQJNYn7zt09E2fEvNjzWobt2oilpn/rDPzEzeaSGg1soxWt7KLWFqNfL+t++iUvlj+Kzx3I+o36HQK32vroXpAkABh7DmvC935iIEPFFw1" +
                    "WnmY9Z2mvMAjUR71Io/4VMS8WX/9QoLAJsHmHNFZVEMjUzYkfgvoN4RbvFF32YafgGZAkAAgG5O/3ccYRfNr5FRS33nbuRUmIX8NhMVPO7kgQArIIiodfKGJnZQDPEID" +
                    "Eca5mXUChADKl27E0157L2FAy8RAkAmnqO1yH+jN0dYccz6CibH0ReTjFNddojHqMxzl/ohDlCBTtn3RPHnzVz4U7iOh15Ka4JCVh+mMYtVoA9rgZwl";

            String content = "aRiSY6lzi0k/VfnSRc25R31pp4rEHfx633+E/vUF7yzzD9Gdblgn295jdvHn4eSB/uuDpYmwNQkpjYpaMCXJOJ6f2/Pp3uJEvurgnOOOoGw6OUHEUQh3YCYngWGi8jbwtXs0D5OZw1S6zQQAFWMMpzReMdEt67DcNOqvIe68xmCVTvfJhnW7lzFRrtcMe2w8ia8vYLJwlfr2fA1OfJlI+h6obEyVSFJhISTmccfkCCNqbZNnlzow2jA+NMkGoLnXXdOAnWspo7E/OV2mKkOhXxmFsUTCPE4ToC41N47VLn6Lc7byyYyMhPO4ZsmFI1tZAH01OiF+hMGgaHGzhHySpQ==";
            String decrypt = decryptByPrivateKey(content,privateKey);
            System.out.println("解密结果:" + decrypt);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

 

RSA非对称加密算法解析:密钥、明文及密文长度的约定--以及使用RSA算法实现登录时的前后端的加解密 1、RSA算法基础 RSA算法是一种非对称加密算法,非对称即:加解密用的不是同一个秘钥,它有一对秘钥,分为公钥和私钥。公钥加密,一般是客户端进行处理;私钥解密,一般是后端处理。公钥要暴露给加密方使用,私钥则要藏起来,一般由服务器管理。 1.1关于秘钥长度 一般来说,我们默认使用或常用的秘钥长度值是1024bit位,即1024/8=128byte,目前主流可选值:1024、2048、3072、... 阅读详情

相关推荐

关于VUE中RSA分段加解密的解决方案

首先我们npm install jsencrypt --save 把依赖下加粗样式载下来 rsa加密有长度限制 rsa算法本身要求加密内容也就是明文长度m必须0<m<密钥长度n。如果小于这个长度就需要进行padding,因为如果没有padding,就无法确定解密后内容的真实长度,字符串之类的内容问题还不大,以0作为结束符,但对二进制数据就很难,因为不确定后面的0是内容还是内容结束符。而只要用到padding,那么就要占用实际的明文长度,于是实际明文长度需要减去padding字节长度。我们一般使

weixin_53687450的博客 2533

javax.crypto.BadPaddingException : Decryption error

客户端将参数加密后通过http方式调用接口,接口服务方在获取参数进行解密时发生这个错误 发现主要原因为: 原始加密参数值为: 例如:dkjgoeFGKJ+ERO7/999JLJkjk== 获取的加密参数值为: dkjgoeFGKJ ERO7/999JLJkjk== 注意到是+位置获取后试空格了 解决方式: ...

lu_zhou的博客 2万+

javax.crypto.BadPaddingException: Decryption error

前言 进行接口调试时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...

知识改变命运,ヾ(◍°∇°◍)ノ゙【求关注】 1万+

java rsa 解密报:javax.crypto.BadPaddingException: Decryption error

Exception in thread "main" javax.crypto.BadPaddingException: Decryption error    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:29...

kzcming的博客 10万+

win11怎么安装dosbox和masm来运行汇编程序(小白,萌新篇)

一文教会你如何部署dosbox和masm环境

m0_73279193的博客 4699

STM32 I²C外设深度解析:时序配置、主从模式与可靠性工程

I²C是一种广泛应用于嵌入式系统的同步串行总线协议,其核心在于精确的时序控制与可靠的电气特性匹配。理解SCL/SDA信号建立/保持时间、上升下降沿约束及硬件滤波机制,是保障通信稳定的基础;STM32通过I2C_TIMINGR寄存器实现对PRESC、SCLH、SCLL、SDADEL和SCLDEL等关键参数的精细调控,直接影响tSU:DAT、tVD:DAT等标准时序合规性;该能力支撑工业级高可靠场景下的主从双向通信、时钟拉伸管理与错误恢复;本文聚焦STM32平台,结合寄存器级配置、状态机行为与实战调试经验,系统

weixin_42146230的博客 87

RSA 加解密(Java 实现)

RSA 算法是一种非对称加解密算法。服务方生成一对 RSA 密钥,即公钥 + 私钥,将公钥提供给调用方,调用方使用公钥对数据进行加密后,服务方根据私钥进行解密。

长安明月的博客 3万+

LoRa项目实战:手把手教你为ESP32选配和焊接天线(从PCB到信号测试)

本文详细介绍了为ESP32选配和焊接LoRa天线的全流程,包括天线选型、PCB布局设计、焊接工艺及信号测试。重点解析了PCB板载天线、导线天线和陶瓷贴片天线的适用场景与性能特点,并提供专业的焊接技巧和信号测试方案,帮助开发者优化LoRa模块的无线通信性能。

weixin_30470643的博客 393

Java RSA加解密算法学习

RSA加密默认密钥长度是1024,但是密钥长度必须是64的倍数,在512到65536位之间即可。RSA加密数据有长度限制,如果加密数据太长(大于密钥长度)会报错,此时的解决方案是 可以分段加密。RSA如果采用分段加密,当密钥对改为2048位时,RSA最大加解密文大小也需要调整:RSA密钥长度=1024时, 最大加密明文长度是117,解密明文长度是128;RSA密钥长度=2048时, 最大加密明文长度是245,解密明文长度是256;

天天新知 4194

VASPKIT绘制平面平均电荷差分密度

平面平均密度差(planar-averaged electron density difference)是密度差的衍生。密度差是个三维空间函数,经常通过绘制平面图、等值面图方式图形化考察。虽然这两种图很直观,但平面图会受到截面选取的影响,而等值面图会受到等值面数值(isovalue)选取的影响,因此都有一定任意性,也不容易定量讨论。对于电子转移有比较明确方向的情况,可以绘制平面平均密度差曲线,由此可以清楚地考察垂直于选取的方向上每个截面上的密度差积分值,在定量讨论、对比上比较便利。

weixin_43948934的博客 1万+

ESP32固定翼航模硬件设计与飞行力学解析

固定翼无人机是嵌入式控制与空气动力学交叉实践的经典载体,其飞行稳定性本质源于重心、气动中心与控制面的物理耦合关系。理解静稳定度(Static Margin)、升力系数调控、偏航力矩生成等基础原理,是实现可靠姿态控制的前提。在低成本工程约束下,材料刚度、结构弹性与电机-驱动协同设计共同决定了系统动态响应边界。ESP32平台凭借高精度PWM、低功耗双模无线及丰富GPIO,成为教学级航模开发的理想主控;而魔术贴基板、可调电池配重、柔性尾翼等创新结构,则将抽象的飞行力学概念转化为可测量、可调试的实体对象,广泛应用于

weixin_29859471的博客 365

关于RSA加密算法的长度问题

RSA是常用的非对称加密算法。近来有学生在项目中使用System.Security类库中的RSA加密算法时,出现了“不正确的长度”,这实际上是因为待加密的数据超长所致。.net Framework中提供的RSA算法规定,每次加密的字节数,不能超过密钥的长度值减去11,而每次加密得到的密文长度,却恰恰是密钥的长度。所以,如果要加密较长的数据,可以采用数据截取的方法,分段加密。或者增加自定义分块

无名剑 5895

【灰度共生矩阵(GLCM)原理及代码实现】

文章主旨详细介绍灰度共生矩阵(Gray-Level Co-occurrence Matrix, GLCM)的生成原理、核心特征量及其在图像纹理分析中的应用,并提供了可运行的Python代码实现。该网页是一篇理论结合实践的优秀技术文章。它不仅清晰地解释了GLCM这一经典纹理分析工具背后的数学原理,还提供了完整、可复现的代码,非常适合计算机视觉或图像处理领域的学习者和开发者入门并实践灰度共生矩阵。读者可以通过运行代码来直观理解GLCM如何工作,并提取图像的纹理特征。

blotemj.blog.youkuaiyun.com 179

java RSA加密解密

该工具类中用到了BASE64,需要借助第三方类库:javabase64-1.3.1.jar 注意: RSA加密明文最大长度117字节,解密要求密文最大长度为128字节,所以在加密和解密的过程中需要分块进行。 RSA加密对明文的长度是有限制的,如果加密数据过大会抛出如下异常:

Iteam项目组 Smith&Wesson(史密斯威森) 1092

如何在 SAPGUI 里显示上传到 ABAP 服务器的 PDF 文件

在 SAPGUI 里显示 PDF 文件是实际项目中一个很有用的需求。因为在 SAP 实际业务场景中,有大量的流程会生成 PDF 格式的数据。把这种类型的数据输出显示在 SAPGUI 里,方便最终用户查看。本教程后续步骤,还会向大家介绍如何使用 ABAP 代码生成 PDF 格式的数据。本步骤只是简单的将本地 PDF 文件,上传到 ABAP 系统并显示在 SAPGUI 里。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 2686

7、Python高光谱分析工具(PyHAT)简介

Python高光谱分析工具(PyHAT)是一个开源、跨平台的Python库及图形用户界面,用于行星光谱数据的可视化与分析。它支持多种高光谱传感器数据,如火星勘测轨道飞行器的CRISM、月船1号的M3以及SELENE Kaguya SP点光谱仪,提供预处理、衍生产品生成、统计学习和机器学习分析功能。PyHAT基于Pandas和NumPy构建,兼容Jupyter和QGIS环境,旨在解决现有光谱分析方法缺乏开源实现、难以探索性分析和算法分散的问题。其模块化架构涵盖数据输入/输出、通用光谱变换、测绘与点观测工具及高

aa123的博客 138

加密算法RSA是怎么进行加解密的

KeyUtil 是一个功能完备的 RSA 加密和签名工具类,适用于需要非对称加密和数字签名的场景。以下是对每个方法的详细解释,包括功能、实现原理和代码逻辑。

keyboard专栏 827

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

python 中的rsa加密使用

RSA 是一种非对称加密算法,广泛应用于数据加密和数字签名。它涉及公钥和私钥的生成,公钥用于加密数据,私钥用于解密数据。在 Python 中实现 RSA 加密通常使用。

mcqK47LHZ的博客 382

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

java RSA加密解密实现

该工具类中用到了BASE64,需要借助第三方类库:javabase64-1.3.1.jar 下载地址:http://download.youkuaiyun.com/detail/centralperk/5025595 注意: RSA加密明文最大长度117字节,解密要求密文最大长度为128字节,所以在加密和解密的过程中需要分块进行。 RSA加密对明文的长度是有限制的,如果加密数据过大会抛出如下异

pifengyz的专栏 2415

Python3使用RSA分段加密解密

import Crypto from Crypto.Hash import MD5 from Crypto.PublicKey import RSA # 计算签名 from Crypto.Signature import PKCS1_v1_5 # 计算加密解密 from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 from base64 import b64decode, b64encode class RsaUtil(object):

不写代码的博客 1565

python-rsa-base64-加解密

将RSA 加密的数据 进行base64加密 然后 再base64解密 再 RSA解密. import base64 import rsa def create_keys(): # 生成公钥和私钥 Public_key, Private_key = rsa.newkeys(1024) pub = Public_key.save_pkcs1() with open('Public_key.pem', 'wb+')as f: # 公 f.write(pub.

叽里呱啦的一大摊,人生太艰难. 1731

【转】 Java 进行 RSA 加解密时不得不考虑到的那些事儿

【转】 Java 进行 RSA 加解密时不得不考虑到的那些事儿 1. 加密的系统不要具备解密的功能,否则 RSA 可能不太合适 公钥加密,私钥解密。加密的系统和解密的系统分开部署,加密的系统不应该同时具备解密的功能,这样即使黑客攻破了加密系统,他拿到的也只是一堆无法破解的密文数据。否则的话,你就要考虑你的场景是否有必要用 RSA 了。 2. 可以通过修改生成密钥的长度来调整密文长度 生成...

weixin_30279751的博客 109
上一篇: RSA中的数学概念
下一篇: Threadpool Description:线程池描述
West Money
博客等级 码龄9年 7粉丝 48原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值