提供一个AES128位/CBC模式加解密工具类

AES加密、解密工具类 一、AES介绍 AES(Advanced Encryption Standard),中文名称高级加密标准。 AES是开发中常用的加密算法之一。然而由于前后端开发使用的语言不统一,导致经常出现前端加密而后端不能解密的情况出现。然而无论什么语言系统,AES 的算法总是相同的, 因此导致结果不一致的原因在于 加密设置的参数不一致 。于是先来看看在两个平台使用AES加密时需要统一的几个参数。 密钥长... 阅读详情
每次都从头写太烦了,直接贴出来作为备忘
package com.lihong.DDPush;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Random;

/**
 * Created by lihong10 on 2017/8/16.
 */
public class AESUtils {

    //算法/模式/填充
    private static final String CipherMode = "AES/CBC/PKCS5Padding";
    private static final String DEFAULST_SECURITY_KEY = "XXX-123-!@#$%^&*()_+=,./";
    private static final String encodFormat = "UTF-8";

    /**
     * 创建密钥
     *
     * @param key
     * @return
     */
    private static SecretKeySpec createKey(String key) {
        key = key == null ? "" : key;
        StringBuilder sb = new StringBuilder(16);
        sb.append(key);
        while (sb.length() < 16) {
            sb.append("0");
        }
        if (sb.length() > 16) {
            sb.setLength(16);
        }

        byte[] data = null;
        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }

    /**
     * 创建初始化向量
     *
     * @param password
     * @return
     */
    private static IvParameterSpec createIV(String password) {
        password = password == null ? "" : password;
        StringBuilder sb = new StringBuilder(16);
        sb.append(password);
        while (sb.length() < 16) {
            sb.append("0");
        }
        if (sb.length() > 16) {
            sb.setLength(16);
        }

        byte[] data = null;
        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new IvParameterSpec(data);
    }

    /**
     * AES-128/CBC算法加密字节数据
     *
     * @param content
     * @param password 密钥
     * @param iv       初始化向量
     * @return byte[]
     */
    public static byte[] aes128CBCEncrypt(byte[] content, String password, String iv) {
        try {
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, createKey(password), createIV(iv));
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * AES-128/CBC算法解密字节数组
     *
     * @param content
     * @param password 密钥
     * @param iv       初始化向量
     * @return byte[]
     */
    public static byte[] aes128CBCDecrypt(byte[] content, String password, String iv) {
        try {
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, createKey(password), createIV(iv));
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * AES-128加密字符串
     *
     * @param content
     * @return
     */
    public static String encrypt(String content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(DEFAULST_SECURITY_KEY.getBytes(encodFormat)));
            byte[] bytes = kgen.generateKey().getEncoded();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(bytes, "AES"));
            byte[] result = cipher.doFinal(content.getBytes(encodFormat));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                String hex = Integer.toHexString(result[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES-128 CBC加密方式, 加密后使用Base64转码
     *
     * @param content        待加密内容
     * @param encodingFormat
     * @param key            密钥
     * @param initVector     初始化向量
     * @return
     * @throws Exception
     */
    public static String aesCBCEncrypt(String content, String encodingFormat, String key, String initVector) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(encodingFormat), "AES");
            //使用CBC模式,需要一个向量iv,可增加加密算法的强度
            IvParameterSpec vector = new IvParameterSpec(initVector.getBytes(encodingFormat));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, vector);
            byte[] encrypted = cipher.doFinal(content.getBytes(encodingFormat));
            //此处使用BASE64做转码。
            String result = new BASE64Encoder().encode(encrypted);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES-128 CBC解密方式
     *
     * @param content        待解密的Base64字符串
     * @param encodingFormat
     * @param key            密钥
     * @param initVector     初始化向量
     * @return
     */
    public static String aesCBCDecrypt(String content, String encodingFormat, String key, String initVector) {
        try {
            SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(encodingFormat), "AES");
            IvParameterSpec vector = new IvParameterSpec(initVector.getBytes());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, vector);
            //先用base64编码,因为对应的加密使用Base64解码
            byte[] base64Bytes = new BASE64Decoder().decodeBuffer(content);
            byte[] original = cipher.doFinal(base64Bytes);
            String result = new String(original, encodingFormat);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String encrypt(String content, String key) {
        if (isEmpty(key)) {
            return encrypt(content);
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(key.getBytes(encodFormat)));
            byte[] bytes = kgen.generateKey().getEncoded();
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(bytes, "AES"));
            byte[] result = cipher.doFinal(content.getBytes(encodFormat));
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < result.length; i++) {
                String hex = Integer.toHexString(result[i] & 0xFF);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sb.append(hex.toUpperCase());
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 解密
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        if (isEmpty(content)) {
            return null;
        }
        byte[] bytes = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            bytes[i] = (byte) (high * 16 + low);
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(DEFAULST_SECURITY_KEY.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] result = cipher.doFinal(bytes);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 解密
     *
     * @param content
     * @param securityKey
     * @return
     */
    public static String decrypt(String content, String securityKey) {

        if (isEmpty(securityKey)) {
            return decrypt(content);
        }
        byte[] bytes = new byte[content.length() / 2];
        for (int i = 0; i < content.length() / 2; i++) {
            int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
            bytes[i] = (byte) (high * 16 + low);
        }
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(securityKey.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] result = cipher.doFinal(bytes);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static boolean equal(byte[] a1, byte[] a2) {
        if (a1 != null && a2 != null && a1.length == a2.length) {
            for (int i = 0; i < a1.length; i++) {
                if (a1[i] != a2[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    private static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }


    public static void main(String... args) throws UnsupportedEncodingException {

        String initVector = "AaBbCcDd1234!@#$";
        String key = "WwXxYyZz1234!@#$";

        int total = 100000;
        int run = 0;
        int count = 0;
        String[] strArr = new String[]{
                "//////\\\\+++、、",
                "+++、、//////\\++!",
                "++!@#%¥……,。、……&*(",
                "【】)&(\\\" + \"中国",
                "事实上",
                "&(\\\" + \"中国谁哟的事实上122你的",
                "12343567"};
        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < total; i++) {
            run++;
            StringBuilder builder = new StringBuilder();
            builder.append(random.nextInt(strArr.length));
            builder.append(random.nextInt(strArr.length));
            builder.append(random.nextInt(strArr.length));
            builder.append(random.nextInt(strArr.length));
            builder.append(random.nextInt(strArr.length));
            byte[] original = builder.toString().getBytes("UTF-8");
            byte[] encrypted = aes128CBCEncrypt(original, key, initVector);
            byte[] decrypted = aes128CBCDecrypt(encrypted, key, initVector);
            if (equal(original, decrypted)) {
                count++;
            } else {
                System.out.println("字符串加解密后内容不一致");
                System.out.println("原始字符串:  " + Arrays.toString(encrypted));
                System.out.println("解密字符串:  " + Arrays.toString(decrypted));
            }
        }
        if (total == count) {
            System.out.println("测试全部通过");
        } else {
            System.out.println("加解密出现缺陷数据");
        }

        System.out.println("运行总次数是: " + run);

    }


}
算法实现:对称加解密算法AES+128位加解密+加解密模式CBC+填充模式PKCS5Padding+base64编码 一、前言 只想要代码的可以直接往后看。 工作以来接触过RSA、AES、HMAC-MD5等数据加解密算法,最近想总结一下。还记得大四刚实习时,项目经理让我用RSA算法实现用户登录注册功能的前后端的数据加密流程,对于当时我这张白纸来说,这玩意儿简直太高深莫测了,而且是一个全国项目,工程好多,工程结构、互相怎么调用我都还没弄清楚,,内心无比慌张,刚来实习又不敢拒绝说不会,硬着头皮接了下来,其实还好,... 阅读详情

相关推荐

工具篇——AESCBCUtil(用于AES加密解密)

写代码的四点: 1.明确需求。要做什么? 2.分析思路。要怎么做?(1,2,3……) 3.确定步骤。每一个思路要用到哪些语句、方法和对象。 4.代码实现。用具体的语言代码将思路实现出来。 学习新技术的四点: 1.该技术是什么? 2.该技术有什么特点?(使用需注意的方面) 3.该技术怎么使用?(写Demo) ...

一个灵活的胖子MrWang 7289

AES128CBC加密模式(工具类和源码)

啦啦啦

qq_42938698的博客 2653

AES-128-CBC-PKCS5PADDING 加解密实现

Author: Joyce_BY, all rights reserved. Contact by email: Yagnes0126@gmail.com 本文目的及实验环境 1、实现128-bit的AES加解密过程 2、python3.7.0,windows10 原理及代码 整体原理图 注意:最后一轮变换没有mixcolumn过程。 &amp;amp;amp;amp;amp;nbsp; 数据分组 将一开始传入AES算法模块的数据,...

Joyce_BY的博客 7829

AES在线加解密工具

总的来说,AES加密/解密工具为业内提供了一个简单易用、免费开放的在线工具,让大家无需安装软件或下载工具,只要有一个网络连接就能完成AES加密过程。AES加密/解密工具操作简单明了,只需要输入明文和密钥,就能快速进行加密和解密操作。此外,AES加密/解密工具还提供了多种加密模式,如CBC、ECB、CFB、OFB等,可以让用户充分自由选择最适合自己情况的加密模式,以尽量保护加密信息的安全性。现在,有一款免费的在线AES加密工具——AES加密/解密工具来帮助大家快速实现AES加密,让加密变得简单易用。

封神之路~ 6872

AES 加密工具(ECB,CBC,CMAC)

AES工具,支持ECB,CBC加解密运算,以及CMAC运算。支持多种PADDING

Comsol有限元网格剖分实战:从基础操作到高效仿真技巧

本文系统介绍了COMSOL有限元网格剖分的核心实战技巧。从基础的物理场控制与用户控制网格选择,到三角形、四边形、四面体等网格单元类型的适用场景,再到扫掠网格、边界层网格与复制网格等高效剖分方法,最后讲解了网格质量评估与几何预处理的关键步骤。旨在帮助用户掌握从自动到手动、从基础到高效的网格剖分艺术,实现仿真精度与计算效率的最佳平衡。

j7k8l的博客 376

Java实现AES-128-CBC算法加解密

AES加解密工具类 import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List...

王绍桦 1万+

别再乱装了!Win10下NVIDIA显卡驱动、CUDA 11.0和cuDNN 8.0.5保姆级配置指南(含版本匹配避坑)

本文提供Win10下NVIDIA显卡驱动、CUDA 11.0和cuDNN 8.0.5的保姆级配置指南,详细解析版本匹配逻辑与安装步骤。从驱动选择到环境变量配置,再到框架测试,手把手教你避开常见坑点,确保深度学习环境一次配置成功。特别强调版本匹配的重要性,帮助开发者高效搭建GPU开发环境。

weixin_30600197的博客 307

实战篇-OpenSSL之AES加密算法-CBC模式

本文属于《OpenSSL加密算法库使用系列教程》之一,欢迎查看其它文章。 实战篇-OpenSSL之AES加密算法-CBC模式一、AES简介二、CBC模式1、命令行操作2、函数说明3、编程实现(1)特别注意(2)实现CBC模式加解密(3)测试代码 一、AES简介 密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。 这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级

百里杨的博客 1万+

京东云鼎环境配置与API安全接入实战:ISV服务商如何搞定数据加密与商家授权

本文详细介绍了京东云鼎环境配置与API安全接入的实战指南,帮助ISV服务商解决数据加密与商家授权等核心问题。通过京东开放平台的应用申请流程,结合多租户数据隔离策略和自动化授权实现,确保电商生态中的安全高效运营。文章还提供了避坑指南,助力开发者规避常见配置错误。

weixin_28705087的博客 353

FPGA与GPU异构计算:重塑嵌入式AI的算力边界与场景定义

本文深入探讨了FPGA与GPU异构计算如何突破嵌入式AI的算力瓶颈。通过分析工业视觉、智能交通及航天等场景,阐述了FPGA负责高速数据采集与预处理,GPU专注复杂AI推理的协同模式,有效解决了传统单一架构在算力、功耗、接口和实时性上的挑战,为嵌入式AI应用提供了高效能解决方案。

spice的博客 486

AES 加解密模式CBC + 填充模式PKCS5Padding + 128位加解密

对称加解密算法AES +加解密模式CBC+ 填充模式PKCS5Padding + 128位加解密 1.对称加密: 加密者和解密者用的是同一串秘钥 2.AES有四种加解密模式:CBC、EBC、CFB、OFB 。CBC模式下,加密时,是对明文进行分组加密的,每组大小一致,到 最后一组时,可能长度不够,这个时候就需要填充到一样长度,就有了下面的填充模式。 ...

SmallTenMr的博客 7478

044.树莓派4B部署YOLO:从系统烧录到模型运行

《树莓派4B部署YOLOv8实战笔记》摘要:本文详细记录了在ARM架构树莓派4B上部署YOLOv8的全流程。关键点包括:必须使用64位系统并手动编译OpenCV(禁用FFMPEG、开启NEON优化);模型需在x86转换为TFLite格式(分辨率不超过320×320);推理代码使用tflite_runtime替代TensorFlow以减少内存占用;针对USB摄像头卡顿、内存泄漏等典型问题给出了解决方案。

2603_95664987的博客 169

AES128加解密流程详细介绍

AES128加解密流程详细介绍 公司想要对嵌入式设备里的文本进行加密,怎么办呢,只能用AES128试试,经过一上午的了解,整理了下流程。 参考文章: AES加密 https://zhuanlan.zhihu.com/p/125633081 https://www.sohu.com/a/278722262_100245441 AES加密每次只能加密16字节,我们先要学会如何对16字节数据进行加密,学会之后再学习大文件加密就简单多了。 下面介绍如何对16字节数据进行加密。 AES加密开始前要准备的东西 1

John Lee 的专栏 2万+

芒果YOLO11改进106:检测头篇DynamicHead动态检测头:基于DynamicHead,二次原创提出SATNeXt模块,提出全新的动态DynamicSatDetect

检测头篇DynamicHead动态检测头:基于DynamicHead,二次原创提出SATNeXt模块,提出全新的动态DynamicSatDetect

包括YOLOv5、YOLOv7、YOLOv8等模型改进 774

基于STM32LXXX的模数转换芯片ADC(TLA2528IRTER)驱动C程序设计

define TLA2528_ADDR 0x12 << 1 // 用于HAL传输的8位地址(写入为0x24,读取为0x25)// 100kHz (示例值,需根据实际时钟计算)#define TLA2528_REG_PIN_CFG 0x00 // 引脚配置寄存器。#define TLA2528_REG_CHN_SEL 0x01 // 通道选择寄存器。

myron6688的博客 230

AES加解密模式

要想学习AES,首先要清楚三个基本的概念:密钥、填充、模式。 1、密钥 密钥是AES算法实现加密和解密的根本。对称加密算法之所以对称,是因为这类算法对明文的加密和解密需要使用同一个密钥。 AES支持三种长度的密钥: 128位,192位,256位 平时大家所说的AES128,AES192,AES256,实际上就是指AES算法对不同长度密钥的使用。 三种密钥的区别: 从安全性来看,AES256安全性最高。从性能看,AES128性能最高。本质原因是它们的加密处理轮数不同。 2、填充 要想了解填..

liyuan0714的专栏 1万+

R语言单因素被试内ANOVA检验

在R语言中,我们可以使用多种方法进行被试内ANOVA检验,其中包括使用内建函数或使用外部包。我们随机选择了10个被试,并对每个被试使用了三种不同的药物处理。通过上述代码示例,我们可以使用R语言进行单因素被试内ANOVA检验。假设我们的数据存储在一个名为"data"的数据框中,其中包含两个列:一个列是被试的编号,另一个列是生物指标的测量值。在上述代码中,我们创建了一个名为"data"的数据框,其中"Subject"列包含了被试的编号,"Measurement"列包含了生物指标的测量值。参数指定了数据来源。

PixelNovaO的博客 363

C语言 AES加解密

AES加解密

Genven_Liang的博客 1万+

深度学习工具包 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")

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

java aes128cbc_AES128位,CBC模式加解密

使用原因:因为在项目中,需要在与客户端(IOS,Android)交互的时候,保存一些私有信息,不被别人看到,所以,使用了比较流行的可以反向加解密的AES。PHP 源码$aes = new aes;echo $aes->aes128cbcEncrypt("11122222");echo "\n";echo $aes->aes128cbcEncrypt("中文aes演示");echo "\...

weixin_30735701的博客 1542

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

AES 128位CBC加密解密(不使用固定IV)

安全检查时要求账号和密码加密后才能存到数据库中,要求加密算法如下: 1)分组密码算法:AES(密钥长度在128位及以上)(GCM或CBC模式) 2)流密码算法:AES(密钥长度在128位及以上)(OFB或CTR模式)、chacha20 3)非对称加密算法:RSA(2048位及以上)、ECC(256位以上) 4)哈希算法:SHA2、SHA3 5)密钥交换算法:DSA/DH(密钥长度2048位及以上)...

weixin_39722651的博客 2万+

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

AES-128-CBC加密

1.工具类编写,用户后端 package com.project.util; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import javax.crypto.Ciphe...

qq_40552337的博客 8695

AES AES/CBC/PKCS5Padding模式 128位秘钥长度和向量长度

AES是一种对称加密技术 即加密密钥和解密密钥相同在密码学中又称Rijndael加密法,AES/CBC/PKCS5Padding模式,128位秘钥长度和向量长度

预立数据科技 1万+

Python AES/CBC/PKCS5Padding加解密

拓展公司自动化测试业务,某个接口需要用到加解密,业务是用java的AES/CBC/PKCS5Padding加解密,搬了各处砖,都不同的坑,只能在一次次踩坑报错中自力更生,分享出来以便大家别走我这样的路子,还有就是给自己做个标记,以后要用也好找~~~~ 哈哈哈!!! 写得不好,请多多指教~ 先普及一下AES加密 AES加密 AES加密是建立在DES加密不能满足破解难度...

Holidayzz的博客 6491

Java中的AES加解密(CBC模式)

通过有线传输明文密码等机密数据总是容易受到安全性攻击。始终建议对此类信息进行加密并使用SSL来传输这些机密数据。Java为此提供了多种加密算法。在这篇文章中,我们将讨论AES(高级加密标准)java中的对称加密算法,具有CBC模式,比3DES更快,更安全。 加密类型 众所周知,有两种基本的加密类型——非对称加密和对称加密。非对称加密使用两个不同的密钥作为公钥和私钥。在这里,您可以使用公钥加密敏感信息,并使用匹配的私钥来解密相同的信息。当涉及 2 个不同的端点时,主要使用非对称加密,例如VPN客户端和服务

weixin_47145766的博客 8667

AES加密,CBC模式,使用向量iv,工具类

适用于参数前后端加减密,提高安全性。 import cn.hutool.core.codec.Base64; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * @Description: AES单元类 提供A...

Wy_Vae的博客 7718
上一篇: netty - HashedWheelTimer用法测试
下一篇: java中静态块、main方法、构造块、构造方法的执行顺序复习
lhever_
博客等级 码龄14年 213粉丝 130原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值