xml文件签名、验签

XML加密和数字签名 XMLCipher:XMLCipher 类是 javax.xml.crypto.dsig.XMLSignature 包中的主要类,用于执行 XML 加密和解密操作。它提供了加密和解密 XML 数据的功能。EncryptedData:EncryptedData 类用于表示加密的 XML 数据。它包含加密数据和加密算法的信息。KeyInfo:KeyInfo 类用于表示与密钥相关的信息,如密钥的类型、密钥的值等。在 XML 加密中,它通常包含用于解密的密钥信息。 阅读详情
xml文件签名、验签,特别说明:该签名认证方法需要证书,本地测试使用的是keystore.p12,可根据实际情况修改

第一步:创建证书

keytool -genkey -alias myalias -storetype PKCS12 -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -keystore keystore.p12 -validity 365

第二步:xml签名和验签

import lombok.extern.slf4j.Slf4j;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.crypto.XMLStructure;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;


/**
 * packageName com.utils
 * @author 
 * @version JDK 8
 * @className XmlSignUtil
 * @date 2024/5/7 0007
 * @description 
 * 创建证书:keytool -genkey -alias myalias -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 365
 * 创建证书:keytool -genkey -alias myalias -storetype PKCS12 -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -keystore keystore.p12 -validity 365
 */
@Slf4j
public class XmlSignUtil {

    public static void main(String[] args) throws Exception {
        XmlSignUtil xmlSignUtil = new XmlSignUtil();
        //加载密钥库文件
        String pfxFile = System.getProperty("user.dir")+"/distfile/keystore.p12";
        //处理前的文件路径
        String srcFile = System.getProperty("user.dir")+"/dec-license-monitor-utils/signed.xml";
        //处理后的文件路径
        String dstFile = System.getProperty("user.dir")+"/dec-license-monitor-utils/dstFile/signed.xml";
        xmlSignUtil.sign(pfxFile,"yw@123".toCharArray(),srcFile,dstFile);
        //文件路径
//        String dstFile = System.getProperty( "user.dir" ) + File.separator + "license.xml";
        boolean flag = xmlSignUtil.validateSign(dstFile);
        System.out.println(flag);
    }

    /**
     * xml签名
     * @param pfxFile 加载密钥库文件路径
     * @param password 证书密码
     * @param srcFile 处理前的xml文件路径
     * @param dstFile 处理后的xml文件路径
     * @throws Exception
     */
    public static void sign(String pfxFile,char[] password,String srcFile,String dstFile) {
        try {
            XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

            Transform envelopedTransform = xmlSignatureFactory.newTransform(Transform.ENVELOPED , (XMLStructure) null);
            DigestMethod sha1DigestMethod = xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1 , null);

            //创建reference元素
            Reference reference = xmlSignatureFactory.newReference("" ,
                    sha1DigestMethod ,
                    Collections.singletonList(envelopedTransform),
                    null , null);

            SignatureMethod rsaSignatureMethod = xmlSignatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1 , null);
            CanonicalizationMethod canonicalizationMethod = xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE ,
                    (XMLStructure) null);
            //创建SignedInfo元素
            SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
                    canonicalizationMethod ,
                    rsaSignatureMethod,
                    Collections.singletonList(reference));

            //创建密钥对
            KeyStore keyStore = KeyStore.getInstance("PKCS12");



            File file = new File(pfxFile);
            FileInputStream fis = new FileInputStream(file);
            keyStore.load(fis, password);
            fis.close();

            //获取别名
            Enumeration enumas = keyStore.aliases();
            String alias = null;
            while (enumas.hasMoreElements()) {
                alias = (String) enumas.nextElement();
            }

            //准备密钥对
            Key key = keyStore.getKey(alias, password);
            KeyPair keyPair = null;
            if (key instanceof PrivateKey) {
                Certificate cert = keyStore.getCertificate(alias);
                PublicKey publicKey = cert.getPublicKey();
                keyPair = new KeyPair(publicKey, (PrivateKey) key);
            }

            X509Certificate x509 = (X509Certificate) keyStore.getCertificate(alias);

            KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
            List x509Content = new ArrayList();
            x509Content.add(x509);
            x509Content.add(x509.getSubjectX500Principal().getName());
            X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
            KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            Document document = documentBuilderFactory.newDocumentBuilder().
                    parse(new FileInputStream(srcFile));
            DOMSignContext domSignContext = new DOMSignContext(keyPair.getPrivate() , document.getDocumentElement());

            //创建Signature元素
            XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo , keyInfo);
            xmlSignature.sign(domSignContext);


            //输出处理后的文件
            OutputStream outputStream = new FileOutputStream(dstFile);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(new DOMSource(document) , new StreamResult(outputStream));
            log.info("XmlSign签名成功!");
        } catch (Exception e) {
            log.error("XMLsign签名异常:",e.getMessage());
        }
    }

    /**
     * 加密后的文件进行验签
     * @param dstFile 处理后的xml文件路径
     * @return
     * @throws Exception
     */
    public static boolean validateSign(String dstFile) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);

            Document document = documentBuilderFactory.newDocumentBuilder().
                    parse(new FileInputStream(dstFile));
            NodeList nodeList = document.getElementsByTagNameNS(XMLSignature.XMLNS , "Signature");

            if(nodeList.getLength() == 0){
                throw new Exception("Cannot find Signature element");
            }

            DOMValidateContext validateContext = new DOMValidateContext(new X509KeySelector() , nodeList.item(0));

            XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");
            XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(validateContext);

            boolean result = xmlSignature.validate(validateContext);
            log.info("xmlSign验签结果:"+result);
            return result;
        } catch (Exception e) {
            log.error("XmlSign验签失败:",e.getMessage());
        }
        return false;
    }

xml签名的时候,首先需要有一个xml文件,加密时,在xml文件中添加一个加密节点,内容为加密信息,验签时,根据xml内容和加密信息进行比对。

以上方法亲测有效,如果遇到什么问题,欢迎留言。

农行BRIDGE商户直连Java V1.4 Demo接入与避坑指南 银行支付接口对接中,商户直连模式让企业能在自有公众号或App内完成交易,无需跳转银行页面。农行缴费中心提供的BRIDGE商户直连便是典型方案,其报文基于XML结构,通过RSA双向签名保障安全:商户私钥签名上行报文,银行公钥验签下行通知。这种模式既保留了商户对支付流程的自主控制,也提升了用户支付体验,广泛适用于学校收费、物业缴费等场景。面向Java开发者,V1.4版本Demo给出从下单、查询、退款到对账的完整代码参考,但实际接入中常遇到证书格式、验签失败、编码乱码、生产环境切换等坑。围绕该Demo的落地要点, 阅读详情

相关推荐

OFD电子签章Java实战:从验签到签章的完整链路与避坑指南

在电子政务和企业信息化浪潮下,版式文档格式(OFD)作为国家标准,正逐步替代PDF成为电子档案、电子合同等场景的合规底座。数字签名技术是保障这些文件真实性与完整性的核心机制,其中基于国密算法体系的SM2非对称加密与SM3摘要算法扮演着关键角色。对于Java后端开发者而言,在业务系统中实现对OFD文件的电子签章与验签,不再是简单的SDK调用,而是涉及解析XML签名结构、处理证书链信任、协调在线签名服务参数等一系列工程细节。本文以一套可运行的Java Demo为例,系统梳理了从脱机验签流程到在线签章请求封装,再

weixin_30431445的博客 305

JAVA中的XML安全与数字签名(包含代码示例)

这篇文章介绍了如何在 Java 中使用数字签名来提高 XML 文档的安全性。数字签名可以用于验证 XML 文档的真实性和完整性。数字签名是使用私钥生成的,私钥由持有人保管。Java 提供了用于生成和验证数字签名的 API。要使用这些 API,需要先获得一个数字证书。数字证书由可信的第三方颁发,包含持有人的公钥和个人信息。文章最后提供了一个示例,演示了如何在 Java 中使用数字签名来保护 XML 文档。

Ciel_7521的博客 2356

Java 微信退款接口实战:证书加载、回调验签与对账兜底

在 Java 后端开发中,微信退款接口涉及双向 HTTPS 认证、证书加载、签名验签与异步通知解密等关键技术环节。其原理基于 PKCS12 证书构建 SSLContext,通过 MD5 签名与 AES-256-ECB 解密保障通信安全。掌握这些机制能有效提升支付系统的健壮性与资金安全,广泛应用于电商、金融等退款场景。本文围绕微信退款接口的 Java 落地,详细拆解从证书加载到回调验签的完整链路,并融入退款查询、状态机与对账兜底等实战经验,帮助开发者避开常见坑点。

weixin_33146151的博客 216

XML签名大全

本文比较全面地介绍了XML签名,但并未深入探究。本人水平有限,错误难免,欢迎指正,共同探讨。  目录:XML签名概览... 1简介... 1为什么需要XML签名... 1数字签名... 2XML签名语法... 2应用... 4实现... 4参考... 4  简介  XML签名是一种基于XML格式的签名规范。它是W3C最早的XML安全方面的推荐标准规范

2303191的专栏 1850

SpringMVC微信支付实战:JSAPI签名、回调验签与退款证书配置

微信支付是小程序电商核心能力,其本质是基于HTTPS的标准化API交互体系。理解JSAPI支付三段式链路(预下单→前端调起→异步通知)、MD5/SHA256签名原理及双向SSL证书机制,是保障资金安全与系统稳定的关键技术基础。在SpringMVC架构下,需手动处理XML解析、敏感参数加解密、事务边界控制与幂等设计,避免因签名错误、回调伪造或库存超卖引发资损。本实践覆盖从code2Session登录态绑定、统一下单签名生成、支付结果异步验签,到p12证书加载退款全流程,适用于Java后端工程师对接微信开放平台

weixin_33462927的博客 150

建行善付通接入实战:支付接口签名、报文与对账避坑指南

银行支付接口与普通互联网开放平台的最大区别,在于资金托管与双向签名机制。无论是电商平台还是供应链系统,接入银行侧的交易资金结算服务,都绕不开商户参数配置、证书签名、报文组装和异步通知这几个关键环节。理解接口的签名原理,掌握报文格式的组装顺序,是跑通交易的基础;而日终对账与差错处理,则是保障资金一致性的核心。善付通作为建设银行的交易资金托管与结算产品,其接口规则稳定、流程规范,但联调阶段常因时间戳、金额单位和分账顺序等问题卡住。本文结合真实接入项目,梳理从签约、支付下单到对账的完整链路,并总结高频故障的排查路

weixin_29202687的博客 326

XML Signature

XML Signature规范是将数字签名和XML组合而成的产物,不要以为XML Signature仅仅是将数字签名技术应用于XML文件。XML Signature包括以下的功能:       1.XML Signature可以对任何能够以URI形式(uniform resource identifier)定位的资源做签名。既包括与签名同在一个XML文件中的元素,也包括其他XML文件中的元

1159

OFD电子签章开发实战:从格式结构到验签通过的关键细节

版式文档在电子政务与商务场景中广泛应用,电子签章是保障文件真实性与完整性的关键环节。相比常见的PDF签章,OFD作为我国自主版式标准,其签章实现涉及XML签名封装、ZIP包结构、摘要算法及证书链校验等底层机制。理解OFD签章的数据结构与验签原理,有助于开发者在国产化适配中快速定位问题。本文从摘要计算、签名构造到包嵌入,梳理了OFD电子签章Demo开发的核心流程,并针对文档摘要不匹配、XML规范化、印章嵌入等高频踩坑点给出排查思路,帮助开发者交付可验证的合法签章文件。

weixin_33978578的博客 144

xml签名和普通数字签名

关于xml签名到底有什么用,刚开始感觉比较近鸡肋,不就是把签名总结成放到一个xml文档中嘛? 首先,xml签名和普通签名都有签名的特性,即保证完整性,不可否认性,身份鉴别等。这就导致了我一开始以为xml签名和普通的签名区别不大。 实际上: 1.xml签名是什么? 顾名思义,xml签名就是把一份签名信息转换成xml文档。 这个文档的结构大体是固定的,内容大概包括:要签名的对象、签名算法、对数据的处理方法(规范化)、数据转换方式、摘要算法、签名值等。 2.传统签名方式的不足之处? 传统的签名方式一般为签名方把

qq_39286701的博客 1102

高通Camx架构调试不求人:手把手教你开UMD/KMD Log与Dump图像(附离线Log合成脚本)

本文详细介绍了高通Camx架构的调试方法,包括UMD/KMD Log的精准配置与图像Dump技术,帮助工程师快速定位移动影像系统中的问题。通过实战案例和自动化脚本,提升调试效率,适用于图像色彩异常、帧率波动等常见问题的诊断与解决。

weixin_30516243的博客 254

深入解析AndroidManifest.xml与device_admin.xml:打造完美DeviceOwner应用配置

本文深入解析了Android企业级开发中DeviceOwner应用的核心配置文件AndroidManifest.xml与device_admin.xml。详细阐述了如何精准声明DeviceAdminReceiver、定义管理策略,并提供了通过ADB命令进行设置与验证的实战指南,帮助开发者构建权限完整、配置正确的设备所有者应用。

ice55的博客 680

xml文件 内部签名 算法_公钥 私钥 签名 验签 说的啥?

公钥 私钥 签名 验签 说的啥?公钥加密,私钥解密 私钥签名,公钥验签散列算法散列算法,也叫做哈希函数,是从一个任何一种数据中创建小的数字方法,散列函数把消息或者数据压缩成摘要,有时候也叫做摘要算法。 把数据量变小,将数据的格式固定下来。常用的算法有:MD5 SHA1MD5MD5 不是一种加密算法,是一种摘要算法,无论多长的输入, MD5 都会输出长度为 128bits 的一个串。public s...

weixin_39779975的博客 312

NLP DAY1: 文本数据读取

txt 文本数据的读写CSV 及 Excel 文本数据的读写更多的 DataFrame 操作数据规模太大怎么办相信通过本次实验的学习,同学们可以游刃有余地面对各种数据文件了。在接下来的实验中,我们将开始真正地开启自然语言处理之旅,开始认识并熟悉一些常见的针对文本本身的预处理操作。

feifeikon的博客 1058

SHA256withRSA 签名与验签

package com.bfb.gateway.payment.unionpayat.handler.utils;import java.io.File;import java.io.FileInputStream;import java.security.KeyStore;import java.security.PrivateKey;import java.security.PublicKey...

zhl15545506227的博客 2万+

Creo模型装配总结

creo7.0的零件装配操作方法,建立基准面、新建约束、约束顺序

heda3的博客 1万+

AI大模型:(三)3.2 Spring AI实现Agent

SpringAI实现了流式对话功能,通过与Ollama模型集成完成前后端交互,当前版本存在thinking信息丢失问题。系统支持两种工具注册方式(方法注解和函数式),并内置时间工具类展示外部工具调用能力。记忆功能提供多种存储方案(内存、JDBC、NoSQL等),实现跨对话轮次的上下文保持。MCP协议集成方面,服务端实现计算和业务查询工具,客户端支持12306及自定义业务系统接入。完整演示了流式对话、工具调用与记忆功能的综合应用。该实践构建了具备复杂交互能力的AI系统,同时指出生产环境需关注的安全与优化问题。

haylee的专栏 1008

记录一次对XML文件数字签名Base64转码时遇到的坑

前些天,公司业务需要对XML格式的文件做数字签名,签完名后发去网联的联调环境却一直返回文件验签失败,一直改加密的代码和找同事帮忙都没解决。后来,无意间看到了一条有关base64加密的博客,尝试着试了一下,没想到就是base64加密的问题。 我的代码中将字节数组base64转码用的一直是这个方法Base64.encodeBase64String(sa.sign()),原来base64转码到一定的长度...

weixin_44042579的博客 1172

波士顿房价预测分析----以线性回归LinearRegression为例

波士顿房价数据集包括506个样本,每个样本包括13个特征变量和该地区的平均房价,房价显然和多个特征变量相关,先选择一元线性回归与多个特征建立线性方程,观察模型预测的好坏,再选择多元线性回归进行房价预测。13个特征变量缩写含义CRIM城镇人均犯罪率ZN住宅用地所占比例INDUS城镇中非住宅用地所占比例CHAS虚拟变量,用于回归分析NOX环保指数RM每栋住宅的房间数AGE1940 年以前建成的自住单位的比例DIS距离 5 个波士顿的就业中心的加权距离RAD。

我走的每一步都算数 842

裸签、Attach、Detach及其验签方式

裸签:极简形式,适合信任环境中已知数据不会被替换的场景(如本地校验)。Attach 类型:自包含性强,适合需要 “一次传输完成验证” 的场景(如邮件、合同)。Detach 类型:平衡安全性与灵活性,适合大文件或分布式系统(如 XML、大型数据集签名)。为了让理解更完整,我们可以再补充一点细节:裸签:提供「原始数据 + 加密签名值」,但两者是完全分离的,没有任何内置的关联信息(比如 “这个签名属于哪个数据”),需要依赖外部方式(如人工备注、文件名约定)确保配对正确。Attach。

Yisitelz的博客 1330

Sigrity System Explorer Transient Analysis模式进行瞬态仿真分析操作指导-单端信号-并联端接

Sigrity System Explorer Transient Analysis模式可以用于瞬态仿真分析,通过搭建简易拓扑用于前仿真分析通道的时域性能,下面搭建一个简易的单端拓扑并且进行并联端接,以下图为例,准备好发送接收端的IBIS模型, (se_example.ibs,本例发送接收端都使用相同的IBIS模型),以及传输线的S参数模型(W1_welement_se.sp)最上方的图形界面是传输线的模型,本例是一个上下都有参考平面的带状线,右侧的梯形是蚀刻角度,根据W1和W2以及铜厚来确定。

weixin_54787054的博客 374

解决:请求的资源[/xxx/]不可用 描述 源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。

解决:请求的资源[/xxx/]不可用 描述 源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。

念兮为美 1万+

XML数字签名要点

XML数字签名,就是选择出xml文件中的一些内容,然后标准化(规范化),然后对其数据流(UTF8化后)进行计算一个特征码(HASH值).具体算法很多如hash1,has256,sm3等等, 剩下的所谓签名也是很简单,就是用私钥(你的私人密码)加对这个特征码加密, 并给出一个密文。其他人用你的开锁工具(公钥)来开,具体就是先算特征码是否正确,然后用签名串(密文), 来解密,看那个签名串里面加密的特征码和XML明示特征码是否一致。可以选择一个节点,或全部内容,或者部分节点,这个按照具体的环境而定。

xysoft008的专栏 811

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

tp5 php 对接通联支付的协议支付

话不多说,直接上代码。 以获取签约短信为例 /** * 签约短信 * @param $data * @return array * @throws BaseException */ public function bindMsg($data) { $nonceStr = $this->nonceStr();//流水号 // API参数 $params = [ ...

binvip1的博客 1045

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

QuartzDesk License校验漏洞完整分析:一个“自包含证书“导致的签名绕过

最近在研究 Quartz 任务调度监控方案时,发现商业产品 QuartzDesk 的 License 校验存在一个典型的设计漏洞:用于验证签名的公钥证书竟然直接从 License XML 文件中读取。本文完整记录了从反编译发现端倪、到定位校验逻辑、再到成功复现攻击的全过程,并深入剖析了"信任锚自引用"这一通用反模式的原理与危害。文章最后给出了两种正确的 License 校验设计方案和可落地的自检标准。全程有码有真相,Java 开发者、涉及授权机制设计的架构师不可错过。

toolsmith的博客 483

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Notepad-- 跨平台文本编辑器新手指南:从安装到批量替换、文件对比一步到位

同一个工程今天用 Windows 改,明天要在国产 UOS 或 macOS 上继续,还得换一套编辑器?notepad--(Ndd)是一款覆盖 Windows、Linux、macOS 的跨平台文本编辑器,内置语法高亮、目录级批量查找替换和文件差异对比。这篇带你从零把它跑起来,再把最常用的三件事——跨文件批量替换、两文件差异比对、行编辑——各做一遍,全程大概 10 分钟。 ## 先跑起来:最短编译安

gitblog_00974的博客 439
上一篇: Pkcs7Detache 数字签名、验签
下一篇: 国产SM4数据加密和解密
java_sso_yw
博客等级 码龄5年 79粉丝 11原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值