C# 实现的 AES 加密算法

[代码]AESEncryptionUtility.cs

using System;
using System.IO;
using System.Security.Cryptography; 

//
// Sample encrypt/decrypt functions
// Parameter checks and error handling
// are ommited for better readability
// @author:Ashwin Kumar
// Date : 12/3/2008
public class AESEncryptionUtility
{
	static int  Main(string[] args)
    {
		if (args.Length < 2)
            {
                Console.WriteLine("Usage: AESEncryptionUtility infile outFile");
                return 1;
            }
			string infile = args[0];
            string outfile = args[1];
			//string keyfile = args[2];
			//var key = File.ReadAllBytes(keyfile);
			Encrypt(infile,outfile,"test");
			Decrypt(outfile,"_decrypted"+infile,"test");
			return 0;

	}

    // Encrypt a byte array into a byte array using a key and an IV
    public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV)
    {
        // Create a MemoryStream to accept the encrypted bytes
        MemoryStream ms = new MemoryStream();
        // Create a symmetric algorithm.
        // We are going to use Rijndael because it is strong and
        // available on all platforms.
        // You can use other algorithms, to do so substitute the
        // next line with something like
        //      TripleDES alg = TripleDES.Create();
        Rijndael alg = Rijndael.Create();
        // Now set the key and the IV.
        // We need the IV (Initialization Vector) because
        // the algorithm is operating in its default
        // mode called CBC (Cipher Block Chaining).
        // The IV is XORed with the first block (8 byte)
        // of the data before it is encrypted, and then each
        // encrypted block is XORed with the
        // following block of plaintext.
        // This is done to make encryption more secure.
        // There is also a mode called ECB which does not need an IV,
        // but it is much less secure.
        alg.Key = Key;
        alg.IV = IV;
        // Create a CryptoStream through which we are going to be
        // pumping our data.
        // CryptoStreamMode.Write means that we are going to be
        // writing data to the stream and the output will be written
        // in the MemoryStream we have provided.
        CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
        // Write the data and make it do the encryption
        cs.Write(clearData, 0, clearData.Length);
        // Close the crypto stream (or do FlushFinalBlock).
        // This will tell it that we have done our encryption and
        // there is no more data coming in,
        // and it is now a good time to apply the padding and
        // finalize the encryption process.
        cs.Close();
        // Now get the encrypted data from the MemoryStream.
        // Some people make a mistake of using GetBuffer() here,
        // which is not the right way.
        byte[] encryptedData = ms.ToArray();
        return encryptedData;
    } 

    // Encrypt a string into a string using a password
    //    Uses Encrypt(byte[], byte[], byte[])
    public static string Encrypt(string clearText, string Password)
    {
        // First we need to turn the input string into a byte array.
        byte[] clearBytes =
          System.Text.Encoding.Unicode.GetBytes(clearText);
        // Then, we need to turn the password into Key and IV
        // We are using salt to make it harder to guess our key
        // using a dictionary attack -
        // trying to guess a password by enumerating all possible words.
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
        // Now get the key/IV and do the encryption using the
        // function that accepts byte arrays.
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV.
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael.
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size.
        // You can also read KeySize/BlockSize properties off
        // the algorithm to find out the sizes.
        byte[] encryptedData = Encrypt(clearBytes,
                 pdb.GetBytes(32), pdb.GetBytes(16)); 

        // Now we need to turn the resulting byte array into a string.
        // A common mistake would be to use an Encoding class for that.
        //It does not work because not all byte values can be
        // represented by characters.
        // We are going to be using Base64 encoding that is designed
        //exactly for what we are trying to do.
        return Convert.ToBase64String(encryptedData);
    }

    // Encrypt bytes into bytes using a password
    //    Uses Encrypt(byte[], byte[], byte[])
    public static byte[] Encrypt(byte[] clearData, string Password)
    {
        // We need to turn the password into Key and IV.
        // We are using salt to make it harder to guess our key
        // using a dictionary attack -
        // trying to guess a password by enumerating all possible words.
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); 

        // Now get the key/IV and do the encryption using the function
        // that accepts byte arrays.
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV.
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael.
        // If you are using DES/TripleDES/RC2 the block size is 8
        // bytes and so should be the IV size.
        // You can also read KeySize/BlockSize properties off the
        // algorithm to find out the sizes.
        return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16));
    }

    // Encrypt a file into another file using a password
    public static void Encrypt(string fileIn,
                string fileOut, string Password)
    {
        // First we are going to open the file streams
        FileStream fsIn = new FileStream(fileIn,
            FileMode.Open, FileAccess.Read);
        FileStream fsOut = new FileStream(fileOut,
            FileMode.OpenOrCreate, FileAccess.Write);
        // Then we are going to derive a Key and an IV from the
        // Password and create an algorithm
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
        Rijndael alg = Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV = pdb.GetBytes(16);
        // Now create a crypto stream through which we are going
        // to be pumping data.
        // Our fileOut is going to be receiving the encrypted bytes.
        CryptoStream cs = new CryptoStream(fsOut,
            alg.CreateEncryptor(), CryptoStreamMode.Write); 

        // Now will will initialize a buffer and will be processing
        // the input file in chunks.
        // This is done to avoid reading the whole file (which can
        // be huge) into memory.
        int bufferLen = 4096;
        byte[] buffer = new byte[bufferLen];
        int bytesRead;
        do {
            // read a chunk of data from the input file
            bytesRead = fsIn.Read(buffer, 0, bufferLen);
            // encrypt it
            cs.Write(buffer, 0, bytesRead);
        } while(bytesRead != 0);
        // close everything
        // this will also close the unrelying fsOut stream
        cs.Close();
        fsIn.Close();
    } 

    // Decrypt a byte array into a byte array using a key and an IV
    public static byte[] Decrypt(byte[] cipherData,
                                byte[] Key, byte[] IV)
    {
        // Create a MemoryStream that is going to accept the
        // decrypted bytes
        MemoryStream ms = new MemoryStream();
        // Create a symmetric algorithm.
        // We are going to use Rijndael because it is strong and
        // available on all platforms.
        // You can use other algorithms, to do so substitute the next
        // line with something like
        //     TripleDES alg = TripleDES.Create();
        Rijndael alg = Rijndael.Create();
        // Now set the key and the IV.
        // We need the IV (Initialization Vector) because the algorithm
        // is operating in its default
        // mode called CBC (Cipher Block Chaining). The IV is XORed with
        // the first block (8 byte)
        // of the data after it is decrypted, and then each decrypted
        // block is XORed with the previous
        // cipher block. This is done to make encryption more secure.
        // There is also a mode called ECB which does not need an IV,
        // but it is much less secure.
        alg.Key = Key;
        alg.IV = IV;
        // Create a CryptoStream through which we are going to be
        // pumping our data.
        // CryptoStreamMode.Write means that we are going to be
        // writing data to the stream
        // and the output will be written in the MemoryStream
        // we have provided.
        CryptoStream cs = new CryptoStream(ms,
            alg.CreateDecryptor(), CryptoStreamMode.Write);
        // Write the data and make it do the decryption
        cs.Write(cipherData, 0, cipherData.Length);
        // Close the crypto stream (or do FlushFinalBlock).
        // This will tell it that we have done our decryption
        // and there is no more data coming in,
        // and it is now a good time to remove the padding
        // and finalize the decryption process.
        cs.Close();
        // Now get the decrypted data from the MemoryStream.
        // Some people make a mistake of using GetBuffer() here,
        // which is not the right way.
        byte[] decryptedData = ms.ToArray();
        return decryptedData;
    }

    // Decrypt a string into a string using a password
    //    Uses Decrypt(byte[], byte[], byte[])
    public static string Decrypt(string cipherText, string Password)
    {
        // First we need to turn the input string into a byte array.
        // We presume that Base64 encoding was used
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        // Then, we need to turn the password into Key and IV
        // We are using salt to make it harder to guess our key
        // using a dictionary attack -
        // trying to guess a password by enumerating all possible words.
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65,
            0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
        // Now get the key/IV and do the decryption using
        // the function that accepts byte arrays.
        // Using PasswordDeriveBytes object we are first
        // getting 32 bytes for the Key
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV.
        // IV should always be the block size, which is by
        // default 16 bytes (128 bit) for Rijndael.
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size.
        // You can also read KeySize/BlockSize properties off
        // the algorithm to find out the sizes.
        byte[] decryptedData = Decrypt(cipherBytes,
           pdb.GetBytes(32), pdb.GetBytes(16));
        // Now we need to turn the resulting byte array into a string.
        // A common mistake would be to use an Encoding class for that.
        // It does not work
        // because not all byte values can be represented by characters.
        // We are going to be using Base64 encoding that is
        // designed exactly for what we are trying to do.
        return System.Text.Encoding.Unicode.GetString(decryptedData);
    }

    // Decrypt bytes into bytes using a password
    //    Uses Decrypt(byte[], byte[], byte[])
    public static byte[] Decrypt(byte[] cipherData, string Password)
    {
        // We need to turn the password into Key and IV.
        // We are using salt to make it harder to guess our key
        // using a dictionary attack -
        // trying to guess a password by enumerating all possible words.
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
        // Now get the key/IV and do the Decryption using the
        //function that accepts byte arrays.
        // Using PasswordDeriveBytes object we are first getting
        // 32 bytes for the Key
        // (the default Rijndael key length is 256bit = 32bytes)
        // and then 16 bytes for the IV.
        // IV should always be the block size, which is by default
        // 16 bytes (128 bit) for Rijndael.
        // If you are using DES/TripleDES/RC2 the block size is
        // 8 bytes and so should be the IV size.
        // You can also read KeySize/BlockSize properties off the
        // algorithm to find out the sizes.
        return Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16));
    }

    // Decrypt a file into another file using a password
    public static void Decrypt(string fileIn,
                string fileOut, string Password)
    {
        // First we are going to open the file streams
        FileStream fsIn = new FileStream(fileIn,
                    FileMode.Open, FileAccess.Read);
        FileStream fsOut = new FileStream(fileOut,
                    FileMode.OpenOrCreate, FileAccess.Write);
        // Then we are going to derive a Key and an IV from
        // the Password and create an algorithm
        PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
            new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
            0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
        Rijndael alg = Rijndael.Create();
        alg.Key = pdb.GetBytes(32);
        alg.IV = pdb.GetBytes(16);
        // Now create a crypto stream through which we are going
        // to be pumping data.
        // Our fileOut is going to be receiving the Decrypted bytes.
        CryptoStream cs = new CryptoStream(fsOut,
            alg.CreateDecryptor(), CryptoStreamMode.Write);
        // Now will will initialize a buffer and will be
        // processing the input file in chunks.
        // This is done to avoid reading the whole file (which can be
        // huge) into memory.
        int bufferLen = 4096;
        byte[] buffer = new byte[bufferLen];
        int bytesRead;
        do {
            // read a chunk of data from the input file
            bytesRead = fsIn.Read(buffer, 0, bufferLen);
            // Decrypt it
            cs.Write(buffer, 0, bytesRead);
        } while(bytesRead != 0);
        // close everything
        cs.Close(); // this will also close the unrelying fsOut stream
        fsIn.Close();
    }
 }
C#代码实现对AES加密解密 ES(The Advanced Encryption Standard)是美国国家标准与技术研究所用于加密电子数据的规范。它被预期能成为人们公认的加密包括金融、电信和政府数字信息的方法。 本文实例为大家介绍C#实现对AES加密解密的详细代码,分享给大家供大家参考,具体内容如下 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; namespace AESDemo { 立即下载

相关推荐

线上专利申请(超详细)| 签名确认

在【法人登录】页面点击【证书登录】按钮,弹出证书登录提示框,点击【确 认】按钮,进入到输入证书密码页面,点击【取消】按钮,取消本次操作。企业在提交申请时,需要增加签名,如使用企业账户点击提交,会弹出“法人、代理机构不能签名,请使用经办人签名”,这个时候就需要换个账号了。在需要签名时,将专利官网的登录方式点击法人登录,选择扫码登录,使用移动端经办人账户的扫一扫功能扫描登录。登录完成后,再点击签名,使用移动端扫一扫功能,扫描签名,输入证书号,确认签名,并提交。最后,祝大家的申请都成功!

weixin_62112323的博客 9114

C#中实现软件使用次数限制

代码如下:using System;using System.Collections.Generic;using System.Text;using System.IO;using System.Security.Cryptography;using Microsoft.Win32;//****************************************

WindRand的专栏 4215

从 YOLO 到视觉大模型:工程实践中如何选择?

本文对比了传统视觉模型YOLO与视觉大模型的差异。YOLO是单任务专用模型,适合规则明确、实时性要求高的检测任务;视觉大模型则具备通用视觉理解能力,但存在推理延迟大、算力成本高和"过度智能"等问题。在实际工程中,参数规模并非越大越好,7B-8B模型往往更均衡。控制大模型幻觉需通过严格Prompt设计、定向样本微调和任务拆解等方法。工业落地时应根据任务特性选择模型:YOLO适用于确定性高的场景,视觉大模型更适合复杂多变的环境。模型效果的关键在于任务边界、数据质量和系统设计,而非单纯追求参数

aiia18的博客 951

C# 加密解密算法

using System;using System.Data;using System.Configuration;using System.Web;using System.IO;using System.Security.Cryptography;     public class EncDec    ...{        // Encrypt a byte array into a b

954

STM32平台下FreeModbus TCP协议栈集成指南

深入讲解在STM32平台如何移植和配置freemodbus协议栈,实现TCP通信功能。结合嵌入式开发细节,帮助开发者快速掌握freemodbus的应用与调试技巧。

weixin_36001279的博客 1144

Arco Design Pro PC端商家后台框架 | Axure高保真原型库

摘要:本Axure原型设计方案基于字节跳动ArcoDesignPro规范,提供企业级后台快速搭建方案。包含动态表格、表单验证等核心组件,采用中继器驱动设计,支持响应式布局。方案覆盖80%后台常用交互,可节省60%原型制作时间,配套完整设计文档和组件库,实现原型到开发的高效衔接。特别适用于电商、SaaS等后台系统开发,支持权限管理、数据分析等场景,显著提升团队协作效率。

招风的黑耳优快云 3985

C# Aes加密算法

1 /// <summary> 2 /// AES加密 对应java中的 aes/cbc/pkcs5padding 模式的算法 3 /// </summary> 4 /// <param name="s">待加密的字符串</param> 5 ...

anwei1497的博客 243

K8s私有仓库拉取镜像报错解决:x509 certificate signed by unknown authority

在Kubernetes环境中使用自签名证书的私有Harbor镜像仓库时,常会遇到证书验证失败的问题。本文将详细讲解如何解决这个常见的证书问题。Kubernetes版本:1.28.2容器运行时:containerd 1.6.20私有仓库:Harbor(使用自签名证书)(超简单搭建私有仓库Harbor-亲测无坑解决K8s私有仓库证书问题的关键在于正确配置容器运行时(本例中是containerd)信任私有仓库的证书。

lzz的博客 2143

[C#]AES加密算法实现 各大神汇总

public static class AesSecret { #region 秘钥对 private const string saltString = "Wolfy@home"; private const string pWDString = "home@Wolfy"; #endregion #r...

我的笔记 7904

ROS-Industrial :simple_message

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录1. 概述2. 协议(Protocol)3. HEADER解析3.1 MSG_TYPE3.2 COMM_TYPE3.3 REPLY CODE 1. 概述 Simple_Message是ROS-Industrial的一部分,定义了用于与工业机器人控制器通信的简单消息连接协议。另外还包括处理连接受限系统的处理器和管理器类。 2. 协议(Protocol) 简单消息(simplemessage)协议定义了ROS的驱动层和机器人控制器之.

flsxyw的博客 782

LeRobot 官方论文:一个用于端到端机器人学习的开源库

本文介绍了一个名为LeRobot的开源库,旨在解决机器人学习领域的碎片化问题。该库提供了端到端的技术栈,包括统一的机器人中间件API、标准化的数据集格式(LeRobotDataset)、优化的推理栈以及多种最先进机器人学习算法的实现。LeRobot支持多种低成本开源机器人平台(如SO-10X、ALOHA-2等),通过共享中间件实现便捷的遥操作和数据收集。其数据集格式已广泛应用于社区,截至2025年9月已有16,000多个数据集公开共享。该库还支持流式处理大规模数据,降低了研究门槛。在模型方面,LeRobot

2506_90492529的博客 909

用C#实现AES加密算法

好久没有逛论坛了,找工作比较累啊。毕业就意味这失业。也好久没写文章了,今天到论坛上碰到一个网友问AES加密的问题,忙活了个把小时,才发现那哥们真粗心,写错了个对象,导致解密错误。反正闲着无事,把以前写的代码拿出来,改了下。贴出来,也让大家以后熟悉熟悉。顺序介绍下.NET中的加密算法,有时间再来写篇关于.NET下加密算法扩展的文章。由于一般大家用到的都是对称加密算法,所以今天只说这个。 1.关于.

1672

XSS漏洞之PDF生成:从XSS到服务端任意文件读取

XSS是最为常见的Web漏洞之一,多年来连续入选OWASP TOP10,相信大家都耳熟能详。 它是一种代码注入类的攻击,是一种客户端侧的攻击,攻击者通过在Web应用中注入恶意JavaScript代码,通过点击URL,最终在受害者浏览器端执行的一种漏洞。主要有反射型XSS、存储型XSS、基于DOM的XSS三类。XSS一些比较常规的危害大概有:重定向浏览器、窃取Cookie、浏览器劫持等。本文章侧重于发现XSS后的进一步利用。 主要介绍在某次实际测试过程中,发现XSS漏洞之后,如何进一步的利用,最终通过XSS达

计算机毕业论文源码,学生个人网页制作html源码。贴近用户做网络推广和互联网优化。 3782

AES128加密算法的实现(C/Java/C#)

最近项目中有一个需求,实现AES128的加密算法,用于硬件和平台的通信。硬件加密部分使用C语言完成、平台有两种不同的环境:java(Linux)和C#(Windows)。在网上搜集了一些资料,有人实现过纯C代码的AES加密解密算法,这样实际上有一种较为简单的解决思路:加密部分直接拿过来使用;解密部分可以打包为dll(windows环境)或SO(linux环境)库供平台调用。但考虑到环境的兼容性等问...

zhoudapeng01的专栏 4539

蓝牙模块HM-10手册

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

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

C# 实现对称加密算法(AES)与非对称加密算法(RSA),包含前端加密对应算法实现

加密算法

LJF的博客 6525

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

安全架构-加密算法-AES加密.NET C#实现

安全架构-加密算法-AES加密.NET C#实现 方法一: using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; namespace Csharp { class AESHelper { /// <summary> /// AES加密 /// &l

ctotalk 6682

PHP松散比较导致MD5绕过原理与实战

PHP中的松散比较(==)在字符串类型转换时存在科学计数法解析特性:当两个字符串均匹配'0e[0-9]+'模式时,会被强制转为浮点数0,从而导致恒等判断。这一语言机制本用于便捷类型转换,却在Web安全中构成典型逻辑漏洞,尤其在md5哈希值参与松散比较的场景下,可被用于绕过身份校验或权限控制。其技术价值在于揭示‘代码行为即攻击面’的核心安全理念,广泛应用于CTF Web题、PHP代码审计、渗透测试及企业级应用安全加固。本文聚焦该漏洞的成因、构造方法与防御实践。

weixin_34248023的博客 460

[C#]AES加密算法实现

密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS197,并在2002年5月26日成为有效的标准。2006年...

weixin_34367845的博客 155

AES256位对称加密算法,实现C#与Java代码互通

C# AES加密代码 public static class AESCrypto { /// <summary> /// 字串加密 /// </summary> /// <param name="SourceStr">加密前字串</param> /// <param name="CryptoKey">密钥</param> ///.

冻死的企鹅 1107

C# AES加密算法,可以实现逆向解密成明文

【代码】C# AES加密算法,可以实现逆向解密成明文。

qq_64948696的博客 1137
上一篇: 关于猫叫、老鼠逃跑、人被惊醒的程序设计
下一篇: iTextSharp 使用详解(转)
devgis
博客等级 码龄16年 52粉丝 60原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值