diff --git a/.gitignore b/.gitignore index 44c2c55..d0346be 100644 --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,5 @@ /.DS_Store src/test/java/com/sunyard/sydapi/sample/*.* *.p7 +~$* /pack/ diff --git a/doc/.gitignore b/doc/.gitignore deleted file mode 100644 index d84edaa..0000000 --- a/doc/.gitignore +++ /dev/null @@ -1 +0,0 @@ -~$* diff --git a/doc/java接口说明文档.docx b/doc/java接口说明文档.docx deleted file mode 100644 index 44e1704..0000000 Binary files a/doc/java接口说明文档.docx and /dev/null differ diff --git a/doc/上清所对接JAVA接口文档.pdf b/doc/上清所对接JAVA接口文档.pdf new file mode 100644 index 0000000..5962fe9 Binary files /dev/null and b/doc/上清所对接JAVA接口文档.pdf differ diff --git a/kit.json b/kit.json new file mode 100644 index 0000000..b840b6d --- /dev/null +++ b/kit.json @@ -0,0 +1,90 @@ +{ + "vars": { + "version": "%project.git_branch_version%", + "out_path": "./pack" + }, + "clear": [ + { + "func": "rm", + "path": "%out_path%" + }, + { + "func": "rm", + "path": "./logs" + } + ], + "init": [ + { + "func": "mkdir", + "path": "%out_path%" + }, + { + "func": "mkdir", + "path": "%out_path%/jar" + }, + { + "func": "mkdir", + "path": "%out_path%/jar/dependences" + }, + { + "func": "mkdir", + "path": "%out_path%/doc" + } + ], + "gen" : [{ + "cmd" : "dproto" + }], + "build": [ + { + "cmd": "clear" + }, + { + "cmd": "init" + }, + { + "shell": "mvn package -DskipTests", + "check": "BUILD SUCCESS" + }, + { + "func": "cp", + "from": "./target/sydapi4j.jar", + "to": "%out_path%/jar/sydapi4j.jar" + }, + { + "func": "cp", + "from": "./target/sydapi4j-jar-with-dependencies.jar", + "to": "%out_path%/jar/sydapi4j-jar-with-dependencies.jar" + }, + + { + "shell" : "mvn dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=%out_path%/jar/dependences", + "check": "BUILD SUCCESS" + }, + { + "func": "cp", + "from": "./doc", + "to": "%out_path%/doc" + }, + { + "func": "cp", + "from": "./src/test/java/sample", + "to": "%out_path%/sample" + }, + { + "func": "cp", + "from": "./说明.txt", + "to": "%out_path%/说明.txt" + }, + { + "func": "zip", + "from": "%out_path%/*", + "to": "%out_path%/sydapi-%version%.%project.git_commit_hash%.zip", + "vc" : "12M" + }, + { + "func": "open", + "path": "%out_path%/" + } + ] + +} diff --git a/pom.xml b/pom.xml index faee038..7bfa8ba 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.sunyard sydapi4j - 1.0.20220402 + 1.0.20220712 jar sydapi4j @@ -72,7 +72,7 @@ com.sunyard proto - 1.0-20220412 + 1.0-20220804 diff --git a/public.cmd b/public.cmd deleted file mode 100644 index cfb0d92..0000000 --- a/public.cmd +++ /dev/null @@ -1,7 +0,0 @@ -:: 自动打包为发布格式 -:: 准备文件夹 -:: rd /s/q ./public -:: md ./public - -:: 获取版本 -node public.script/index.js \ No newline at end of file diff --git a/public.script/color.js b/public.script/color.js deleted file mode 100644 index afe1468..0000000 --- a/public.script/color.js +++ /dev/null @@ -1,31 +0,0 @@ - -// console.log('\x1B[36m%s\x1B[0m', info); //cyan -// console.log('\x1B[33m%s\x1b[0m:', path); //yellow -var styles = { - 'bold' : ['\x1B[1m', '\x1B[22m'], - 'italic' : ['\x1B[3m', '\x1B[23m'], - 'underline' : ['\x1B[4m', '\x1B[24m'], - 'inverse' : ['\x1B[7m', '\x1B[27m'], - 'strikethrough' : ['\x1B[9m', '\x1B[29m'], - 'white' : ['\x1B[37m', '\x1B[39m'], - 'grey' : ['\x1B[90m', '\x1B[39m'], - 'black' : ['\x1B[30m', '\x1B[39m'], - 'blue' : ['\x1B[34m', '\x1B[39m'], - 'cyan' : ['\x1B[36m', '\x1B[39m'], - 'green' : ['\x1B[32m', '\x1B[39m'], - 'magenta' : ['\x1B[35m', '\x1B[39m'], - 'red' : ['\x1B[31m', '\x1B[39m'], - 'yellow' : ['\x1B[33m', '\x1B[39m'], - 'whiteBG' : ['\x1B[47m', '\x1B[49m'], - 'greyBG' : ['\x1B[49;5;8m', '\x1B[49m'], - 'blackBG' : ['\x1B[40m', '\x1B[49m'], - 'blueBG' : ['\x1B[44m', '\x1B[49m'], - 'cyanBG' : ['\x1B[46m', '\x1B[49m'], - 'greenBG' : ['\x1B[42m', '\x1B[49m'], - 'magentaBG' : ['\x1B[45m', '\x1B[49m'], - 'redBG' : ['\x1B[41m', '\x1B[49m'], - 'yellowBG' : ['\x1B[43m', '\x1B[49m'] -}; - -module.exports = styles - diff --git a/public.script/index.js b/public.script/index.js deleted file mode 100644 index 67ce273..0000000 --- a/public.script/index.js +++ /dev/null @@ -1,269 +0,0 @@ -const l = require("./log") -const os = require("os"); -const fs = require('fs'); -const path = require('path'); -const util = require('util'); -const { exec } = require('child_process') - - -function sync( cmds , options = {}){ - - if ( options.detached ) { - throw "sync 不支持 detached" - } - - options = Object.assign({ - // cwd : os.tmpdir(), - encoding: 'buffer' - }, options) - - // 支持多命令 - let cmd = cmds - - // win 乱码问题 - let encode = "win32" === os.platform() ? 'cp936' : "utf-8" - - - - return new Promise(function (resolve, reject) { - let process = exec( cmd , options , function (e, stdout, stderr) { - // console.log( e, - // iconv.decode( stdout, 'cp936'), - // iconv.decode( stderr, 'cp936') - // ) - - if ( e ) { - reject( e ) - } else { - - - resolve( stdout.toString() , stderr.toString() ) - // resolve({ - // pid : process.pid, - // exitCode : process.exitCode, - // stdout : stdout.toString(), - // stderr : stderr.toString() - // }) - } - }) - console.log( "process", process.pid ) - - }) -} - - - -var version = "" -const project_path = path.join(__dirname, "../") -const out_path = path.join(project_path, "public") - -// 用户文档 -const man = "说明.txt" - -function prepareDir(){ - - return new Promise(function (cbok, cberr) { - if ( fs.existsSync( out_path ) ){ - l.i("存在旧文件,清空旧文件") - } - - sync("rd /s/q .\\public").catch(function (reason) { - - // pass - - }).finally(function () { - - l.i("创建新文件") - fs.mkdirSync( out_path ) - fs.mkdirSync( path.join( out_path, "jar" )) - fs.mkdirSync( path.join( out_path, "jar", "dependences")) - - // fs.mkdirSync( path.join( out_path, "doc" )) - // fs.mkdirSync( path.join( out_path, "html" )) - // fs.mkdirSync( path.join( out_path, "sample" )) - l.i("目录准备完成") - cbok() - - }) - - }) -} - - -function mvn(){ - l.i("调用 maven 打包,可能需要好几分钟。") - return new Promise(function (cbok, cberr) { - sync('mvn package -DskipTests').then(function (value, error) { - - if ( error ) { - throw error - - } - - l.d( value ) - if ( value.indexOf("BUILD SUCCESS") < 0 ){ - throw new Error("请检查 maven package 命令") - } - - // 移动文件到发布目录 - fs.renameSync(path.join(project_path, "target", "sydapi4j-jar-with-dependencies.jar") - , path.join(out_path, "jar", "sydapi4j-jar-with-dependencies.jar")) - - - fs.renameSync(path.join(project_path, "target", "sydapi4j.jar") - , path.join(out_path, "jar", "sydapi4j.jar")) - - cbok() - - }) - }) -} - -function doc(){ - return sync('mvn javadoc:javadoc').then(function (value, error) { - - l.d( value ) - // if ( value.indexOf("BUILD SUCCESS") < 0 ){ - // throw new Error("请检查 maven doc 命令") - // } - - }).catch(function (reason) { - l.d("忽略文档生成错误") - }) - -} - -function zipjar(){ - return sync("7z a .\\public\\sydapi-"+ version +".zip .\\public\\jar\\").then(function (value, error) { - - l.d( value ) - if ( value.indexOf("Everything is Ok") < 0 ){ - throw new Error("请检查 7z 命令") - } - - }) -} - - -function zipsample(){ - return sync("7z a .\\public\\sydapi-"+ version +".zip .\\src\\test\\java\\com\\sunyard\\sydapi\\sample").then(function (value, error) { - - l.d( value ) - if ( value.indexOf("Everything is Ok") < 0 ){ - throw new Error("请检查 7z 命令") - } - - }) -} - -function zipdoc(){ - return sync("7z a .\\public\\sydapi-"+ version +".zip " + man).then(function (value, error) { - - l.d( value ) - if ( value.indexOf("Everything is Ok") < 0 ){ - throw new Error("请检查 7z 命令") - } - - }) -} - - -function dependencies(){ - return sync('mvn dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=./public/jar/dependences').then(function (value, error) { - - l.d( value ) - if ( value.indexOf("BUILD SUCCESS") < 0 ){ - throw new Error("请检查 maven dependencies 命令") - } - - }) - -} - -async function main() { - - l.i("项目目录 : " + project_path ) - - sync('git status').then(function (value, error) { - - l.d( value ) - - if ( value.indexOf("Command failed") > 0 ){ - throw new Error("请检查 git 命令") - } - - if ( value.indexOf("Changes not staged for commit") > 0){ - throw new Error("项目有文件未保存") - } - - if ( value.indexOf("Changes to be committed") > 0 ){ - throw new Error("项目有文件未提交") - } - - - // 匹配分支,获取前两位版本 - var r = /^On branch dev-(?\S+)$/gm.exec(value) - l.i( r.groups.version ) - version = r.groups.version - - return sync('git log -1') - - }).then(function (value) { - - l.d( value ) - var r = /^commit\s(?\S+)$/gm.exec(value) - l.i( r.groups.id ) - - // 缩短 HASH - var short = r.groups.id.substr(0, 6) - version += "." + short - - l.i("目前版本: " + version ) - - return prepareDir() - - }).then(function (value) { - - return mvn() - - }).then(function (value) { - - return dependencies() - - }).then(function (value) { - - var pom = fs.readFileSync("pom.xml", { encoding : "UTF-8" }) - var head = pom.indexOf("") - var tail = pom.indexOf("") + 15 - - var dependencies = pom.substring( head, tail ) - fs.writeFileSync( path.join( out_path, "jar", "dependences.xml") , dependencies ) - - }).then(function (value) { - - return zipjar() - - }).then(function (value) { - - return zipsample() - - }).then(function (value) { - - return zipdoc() - - }).then(function () { - - l.i("打包完成!") - sync('cd .\\public && start .') - - }).catch(function (reason) { - - l.e( reason ) - - }) -} - -main() - - - diff --git a/public.script/log.js b/public.script/log.js deleted file mode 100644 index 22ac094..0000000 --- a/public.script/log.js +++ /dev/null @@ -1,31 +0,0 @@ -const style = require("./color") -const info = style.green -const error = style.red -const debug = style.cyan - - -const l = { - - o : console.log, - - i : function ( msg ) { - console.log('%s%s%s', info[0], msg , info[1]); - }, - - d : function ( msg ) { - console.log('%s%s%s', debug[0], msg , debug[1]); - }, - - e : function ( msg ) { - console.log('%s%s%s', error[0], msg , error[1]); - }, -} - -l.show = function () { - - l.i("info") - l.d("debug") - l.e("error") -} - -module.exports = l \ No newline at end of file diff --git a/release.cmd b/release.cmd deleted file mode 100644 index 4ab9f3d..0000000 --- a/release.cmd +++ /dev/null @@ -1,3 +0,0 @@ -7z a ./target/sydapi4j.jar racal.sunyard.main.version -7z a ./target/sydapi4j-sources.jar racal.sunyard.main.version -7z a ./target/sydapi4j-jar-with-dependencies.jar racal.sunyard.main.version \ No newline at end of file diff --git a/release.txt b/release.txt deleted file mode 100644 index d0a8f7c..0000000 --- a/release.txt +++ /dev/null @@ -1,5 +0,0 @@ -v1.11 版本 -- 修正不规范接口 GenerateRandom 返回值更改为 String 类型。老版本为 bool 类型,仅于活性检测。 - -v1.12 版本 -- 新增编押验押接口/人行定制接口。 \ No newline at end of file diff --git a/src/main/java/com/sunyard/MutiThreadHander.java b/src/main/java/com/sunyard/MutiThreadHander.java new file mode 100644 index 0000000..6b11ad8 --- /dev/null +++ b/src/main/java/com/sunyard/MutiThreadHander.java @@ -0,0 +1,109 @@ +package com.sunyard; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * 管理多线程间对象 + * 类似 ThreadLocal + * @param + */ +public class MutiThreadHander { + + private static class Handler { + private T obj = null; + private long creatAt = System.currentTimeMillis(); + private long lastGetAt = System.currentTimeMillis(); + + public Handler(T obj) { + this.obj = obj; + } + + public T getObj() { + return obj; + } + + public long getCreatAt() { + return creatAt; + } + + public long getLastGetAt() { + return lastGetAt; + } + } + private final Map handers = new HashMap(); + private ScheduledExecutorService gcThread = Executors.newScheduledThreadPool(1); + + private long maxLiveMillis = 8 * 3600 * 1000; + private long maxIdleMillis = 3600 * 1000; + private long checkEveryMillis = 5 * 60 * 1000; + + public MutiThreadHander() { + gcThread.scheduleWithFixedDelay(new Runnable() { + @Override + public void run() { + try { + if ( handers.size() <= 0 ) { + return; + } + + long now = System.currentTimeMillis(); + Iterator>it = handers.entrySet().iterator(); + while ( it.hasNext() ){ + Map.Entry entry = it.next(); + + // check maxLiveMillis + if ( entry.getValue().getCreatAt() - now > maxLiveMillis ){ + synchronized ( handers ){ + it.remove(); + } + } + + // check maxIdleMillis + if ( entry.getValue().getLastGetAt() - now > maxIdleMillis ){ + synchronized ( handers ){ + it.remove(); + } + } + } + } catch ( Exception e) { + e.printStackTrace(); + } + } + }, checkEveryMillis, checkEveryMillis, TimeUnit.MILLISECONDS ); + } + + + + protected T initialValue() { + return null; + } + + public void clear(){ + synchronized ( handers ) { + handers.remove( Thread.currentThread() ); + } + } + + public void set(T obj){ + synchronized ( handers ) { + handers.put( Thread.currentThread() , new Handler(obj)); + } + } + + public T get(){ + synchronized ( handers ) { + Handler hander = handers.get( Thread.currentThread() ); + if ( null == hander ) { + T o = initialValue(); + hander = new Handler( o ); + handers.put( Thread.currentThread(), hander ); + } + return (T) hander.getObj(); + } + } +} diff --git a/src/main/java/com/sunyard/SydApiException.java b/src/main/java/com/sunyard/SydApiException.java index ea60670..4b822e3 100644 --- a/src/main/java/com/sunyard/SydApiException.java +++ b/src/main/java/com/sunyard/SydApiException.java @@ -13,82 +13,92 @@ public class SydApiException extends RuntimeException{ return retCode; } - - public void transMsg(){ - switch (this.retCode){ + private static String transMsg(int code){ + String msg = "未定义的错误"; + switch (code){ case -1: case -2: case -3: - this.msg = "网络错误"; + msg = "网络错误"; break; case -4: - this.msg = "返回包的序列号有误"; + msg = "返回包的序列号有误"; break; case -5: - this.msg = "返回包的命令码有误"; + msg = "返回包的命令码有误"; break; case -6: - this.msg = "输出缓冲区预留太小"; + msg = "输出缓冲区预留太小"; break; case -25: - this.msg = "输入的 HASH 值长度应该为 32 个字节"; + msg = "输入的 HASH 值长度应该为 32 个字节"; break; case -26: - this.msg = "用户标识超长(应该<=16) "; + msg = "用户标识超长(应该<=16) "; break; case -27: - this.msg = "数据类型不合法 "; + msg = "数据类型不合法 "; break; case 33: - this.msg = "检索的数据或密钥不存在"; + msg = "检索的数据或密钥不存在"; break; case 4: - this.msg = "DER 编码格式错误(公钥) "; + msg = "DER 编码格式错误(公钥) "; break; case 21: - this.msg = "输入的数据格式错误 "; + msg = "输入的数据格式错误 "; break; case 19: - this.msg = "数据解密错(C3) "; + msg = "数据解密错(C3) "; break; case 2: - this.msg = "签名验证错误 "; + msg = "签名验证错误 "; break; case 129: - this.msg = "没有该指令"; + msg = "没有该指令"; break; case 0x8006 : { - this.msg = "输入的数据格式错误"; + msg = "输入的数据格式错误"; break; } case 32770: - this.msg = "签名验证错误(P7) "; + msg = "签名验证错误(P7) "; break; case 32773: - this.msg = "证书不可信"; + msg = "证书不可信"; break; case 32884: - this.msg = "证书或签名数据的格式错"; + msg = "证书或签名数据的格式错"; break; case 36868: - this.msg = "DN 所指向的实体不存在"; + msg = "DN 所指向的实体不存在"; break; case 40000: this.msg = "输入的大数据处理异常"; + break; + case 56300: this.msg = "证书导入错误"; + break; + case 56307: this.msg = "证书删除错误"; + break; default: - this.msg = "未定义的错误"; + msg = "未定义的错误"; } + return msg; + } + + public void transMsg(){ + this.msg = transMsg( this.retCode ); } public SydApiException(int retCode) { @@ -98,9 +108,9 @@ public class SydApiException extends RuntimeException{ } - public SydApiException(String msg, int ret){ - super("SydApiException(" +"code ="+ String.format(" %d", ret) + " : "+"msg ="+ (null == msg ? "未定义的错误" : msg) +")" ); - this.retCode = ret; + public SydApiException(String msg, int retCode){ + super("SydApiException(" + String.format("%04X", retCode) + ":" + ( null == msg ? transMsg(retCode) : msg ) + ")" ); + this.retCode = retCode; if (null == msg || "".equals(msg)){ transMsg(); }else { @@ -124,7 +134,7 @@ public class SydApiException extends RuntimeException{ sb.append(Integer.toHexString(this.retCode)); sb.append(" ) "); sb.append(" msg = "); - sb.append(this.msg); + sb.append(msg); return sb.toString(); } } diff --git a/src/main/java/com/sunyard/inf/SydCryptionApi.java b/src/main/java/com/sunyard/inf/SydCryptionApi.java index 94fbfe4..4a5f9c9 100644 --- a/src/main/java/com/sunyard/inf/SydCryptionApi.java +++ b/src/main/java/com/sunyard/inf/SydCryptionApi.java @@ -3,6 +3,7 @@ package com.sunyard.inf; import com.sunyard.RetWrap; import java.io.UnsupportedEncodingException; +import java.util.List; /** * 对称加解密相关接口 @@ -273,6 +274,9 @@ interface SydSYMApi { */ byte[] SYMEncryptData(int nAlg, String seesionKey, int fullmode, byte[] pINdata); + + List SYMEncryptDecryptBatchData(int nAlg, String[] seesionKey, int fullmode, List pINdata); + /** * 用输入的会话密钥,对指定报文数据进行加密处理。 * diff --git a/src/main/java/com/sunyard/inf/SydSVApi.java b/src/main/java/com/sunyard/inf/SydSVApi.java index efbe412..a49a9da 100644 --- a/src/main/java/com/sunyard/inf/SydSVApi.java +++ b/src/main/java/com/sunyard/inf/SydSVApi.java @@ -60,8 +60,8 @@ interface SydAttachedSVApi { * @param orgData 要签名的信息 * @return 签名结果 */ - String SM2SignC(int flag, String privateKey, byte[] publicKey, byte[] orgData); - String SM2SignC(int flag, String pUserID, String privateKey, byte[] publicKey, byte[] orgData); + byte[] SM2SignC(int flag, String privateKey, byte[] publicKey, byte[] orgData); + byte[] SM2SignC(int flag, String pUserID, String privateKey, byte[] publicKey, byte[] orgData); /** * SM2 私钥签名 * @param pUserID 使用者的 ID,最大长度为 16 位数字,右对齐。 @@ -142,7 +142,7 @@ interface SydAttachedSVApi { int nOrgDataType, byte[] publicKey, byte[] orgData, - String sign + byte[] sign ); diff --git a/src/main/java/com/sunyard/inf/customize/SydHAApi.java b/src/main/java/com/sunyard/inf/customize/SydHAApi.java index 7517298..ed45c12 100644 --- a/src/main/java/com/sunyard/inf/customize/SydHAApi.java +++ b/src/main/java/com/sunyard/inf/customize/SydHAApi.java @@ -117,9 +117,16 @@ public interface SydHAApi { * @param nOrgDataType 签名数据类型,SydApi.DATA_ORIGIN(1) 原始数据 SydApi.DATA_HASH(0) : hash 后的类型 * @param publicKey 公钥串,DER编码,HEX格式 * @param orgData 待签名的原始数据,“签名数据类型”为 0 时:HASH 值。“签名数据类型”为 1 时:要签名的信息 - * @param base64Sign 签名数据 (DER 编码 + Base64 编码) + * @param sign S+R * @return 验签是否通过 */ + public boolean SM2Verify( + int nOrgDataType, + byte[] publicKey, + byte[] orgData, + byte[] sign + ); + public boolean SM2Verify( int nOrgDataType, byte[] publicKey, diff --git a/src/main/java/com/sunyard/inf/customize/SydSDNXApiImpl.java b/src/main/java/com/sunyard/inf/customize/SydSDNXApiImpl.java deleted file mode 100644 index 9959469..0000000 --- a/src/main/java/com/sunyard/inf/customize/SydSDNXApiImpl.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.sunyard.inf.customize; - -import com.sunyard.SydApiException; -import com.sunyard.cert.X509; -import com.sunyard.proto.Packet; -import com.sunyard.proto.PacketSection; -import com.sunyard.proto.Util; -import com.sunyard.trans.PacketSN; -import racal.sunyard.main.SydApi4j; -import racal.sunyard.main.proto.Proto8003; -import racal.sunyard.main.proto.Proto8004; -import racal.sunyard.main.proto.Proto8012; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -public class SydSDNXApiImpl extends SydApi4j implements SydSDNXApi { - - - public String nakedSign(byte[] orgData, String sCertDN) { - Proto8003 proto = new Proto8003(); //pset.getProtocolReqRender("75"); - byte[] dn = new byte[256]; - byte[] s = null; - try { - s = sCertDN.getBytes("GBK"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - - System.arraycopy(s, 0, dn, 0, s.length); - - // 填充数据 - HashMap packet = new HashMap(); - HashMap data = new HashMap(); - packet.put("data", data); - PacketSN sn = PacketSN.gen(); - packet.put("header", sn.getSn().array()); - data.put("signatureDataType$option", 1); - data.put("DN", dn); - data.put("data", orgData); - // 渲染发送 - ByteBuffer bb = proto.rend(packet); - - synchronized (this) { - - - // 响应解析 - bb = syncRead(syncSend(bb)); - } - - - Packet p = proto.parse(bb); - Map ret = p.toMap(); - - if ( - !Arrays.equals(sn.getSn().array(), ((PacketSection) ret.get("header")).getBytes()) - ) { - throw new SydApiException("包序号不匹配", -4); - } - ret = (Map) ret.get("data"); - PacketSection error = (PacketSection) ret.get("error"); - byte[] be = error.getBytes(); - if ( - (0 != (be[0] ^ be[1]))) { - - throw new SydApiException(error.getInfo(), error.autoInt()); - - } - - return Util.encodeBase64(((PacketSection) ret.get("signature")).getBytes()); - //return ((PacketSection) ret.get("signature")).getBytes(); - } - - @Override - public boolean SYD_NakedVerify(byte[] orgData, String sign, String organizationNum) { - Proto8004 proto = new Proto8004(); //pset.getProtocolReqRender("75"); - - byte[] dn = new byte[256]; - byte[] s = null; - - - // 填充数据 - HashMap packet = new HashMap(); - HashMap data = new HashMap(); - packet.put("data", data); - PacketSN sn = PacketSN.gen(); - packet.put("header", sn.getSn().array()); - data.put("signatureDataType$option", 2); - data.put("organizationNum", organizationNum); - data.put("data", orgData); - data.put("signature", Util.decodeBase64(sign)); - data.put("returnSign$option", 0); - // 渲染发送 - ByteBuffer bb = proto.rend(packet); - - synchronized (this) { - - - // 响应解析 - bb = syncRead(syncSend(bb)); - } - - Packet p = proto.parse(bb, packet); - Map ret = p.toMap(); - - if ( - !Arrays.equals(sn.getSn().array(), ((PacketSection) ret.get("header")).getBytes()) - ) { - throw new SydApiException("包序号不匹配", -4); - } - ret = (Map) ret.get("data"); - PacketSection error = (PacketSection) ret.get("error"); - byte[] be = error.getBytes(); - if ((0 != (be[0] ^ be[1]))) { - - throw new SydApiException(error.getInfo(), error.autoInt()); - } - return true; - } - - @Override - public X509 SYD_Get_X509_CertInfo_HA(String bNumber, byte[] orgData, String sign) { - - Proto8012 proto = new Proto8012(); //pset.getProtocolReqRender("75"); - - - // 填充数据 - HashMap packet = new HashMap(); - HashMap data = new HashMap(); - packet.put("data", data); - PacketSN sn = PacketSN.gen(); - packet.put("header", sn.getSn().array()); - data.put("originData", orgData); - data.put("signData", sign.getBytes()); - data.put("flag$option", 2); - data.put("organizationNum", bNumber); - // 渲染发送 - ByteBuffer bb = proto.rend(packet); - - synchronized (this) { - - - // 响应解析 - bb = syncRead(syncSend(bb)); - } - - Packet p = proto.parse(bb, packet); - Map ret = p.toMap(); - - if ( - !Arrays.equals(sn.getSn().array(), ((PacketSection) ret.get("header")).getBytes()) - ) { - throw new SydApiException("包序号不匹配", -4); - } - ret = (Map) ret.get("data"); - PacketSection error = (PacketSection) ret.get("error"); - byte[] be = error.getBytes(); - if ((0 != (be[0] ^ be[1]))) { - - throw new SydApiException(error.getInfo(), error.autoInt()); - } - - PacketSection info = (PacketSection) ret.get("info"); - - byte[] pCertInfo = info.getBytes(); -// X509 cinfo = new X509(); -// cinfo.setIssuer(Util.toCleanString(pCertInfo, 0, 257)); -// cinfo.setSerialNumber(Util.toCleanString(pCertInfo, 257, 65)); -// cinfo.setSubject(Util.toCleanString(pCertInfo, 257 + 65, 257)); -// cinfo.setNotBefore(Util.toCleanString(pCertInfo, 257 + 65 + 257, 15)); -// cinfo.setNotAfter(Util.toCleanString(pCertInfo, 257 + 65 + 257 + 15, 15)); -// byte[] blen = new byte[]{pCertInfo[257 + 65 + 257 + 15 + 15], pCertInfo[257 + 65 + 257 + 15 + 16]}; -// int len = Util.b2i(blen); -// byte[] pem = new byte[len]; -// System.arraycopy(pCertInfo, 257 + 65 + 257 + 15 + 17, pem, 0, len); -// String pp = new String(pem); - // 解析证书 - return GetX509CertInfo(new String(pCertInfo)); - } - - -} diff --git a/src/main/java/racal/sunyard/main/SydApi4j.java b/src/main/java/racal/sunyard/main/SydApi4j.java index 36ba6f2..7ed188a 100644 --- a/src/main/java/racal/sunyard/main/SydApi4j.java +++ b/src/main/java/racal/sunyard/main/SydApi4j.java @@ -641,6 +641,7 @@ public class SydApi4j implements SydApi { byte[] dn = new byte[256]; byte[] s = null; try { + sCertDN = DnUtil.verifyDn( sCertDN ); s = sCertDN.getBytes("GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); @@ -2073,7 +2074,119 @@ public class SydApi4j implements SydApi { data.put("msg", pInData); packet.put("data", data); - return repackEncrypt(packet); + return repackEncrypt( packet ); + } + + + public List SYMEncryptDecryptBatchData(int nAlg, String[] seesionKey, int fullmode, List pINdata) { + + int batchSize = pINdata.size(); + if ( batchSize < 1 || batchSize > 10 ) { + throw new IllegalArgumentException("批量数量错误"); + } + + if ( seesionKey.length != pINdata.size() ) { + throw new IllegalArgumentException("密钥和数据数量不匹配"); + } + + if ( 0x0 != (byte) (nAlg & 0x1) ){ + // 解密 + for ( byte[]d : pINdata ) { + if ( d.length > 1040 ) { + throw new IllegalArgumentException("批量单数数据超长 1040"); + } + } + } else { + // 加密 + for ( byte[]d : pINdata ) { + if ( d.length > 1024 ) { + throw new IllegalArgumentException("批量单数数据超长 1024"); + } + } + } + + ByteBuffer bb = ByteBuffer.allocate(10 * 1024); + PacketSN sn = PacketSN.gen(); + bb.put( new byte[2] ); + bb.put( sn.getSn().array() ); + bb.put( "E0".getBytes() ); + bb.put( (byte) 0x34 ); // 批量加解密 + bb.put( (byte) batchSize ); // 批量数 + bb.put( (byte) ( 0x30 + nAlg) ); // 密钥模式 + bb.put( (byte) ( 0x31) ); // ECB + bb.put( (byte) ( 0x30) ); // ZEK + + // 填充多个密钥 + for ( String key : seesionKey ) { + bb.put( key.getBytes() ); + } + + bb.put( (byte) ( 0x30) ); // 输入消息类型二进制 + bb.put( (byte) ( 0x30) ); // 输出消息类型二进制 + + bb.put( (byte) ( 0x30 + fullmode) ); // 填充模式 + bb.put( "0000".getBytes() ); // 填充字符 + bb.put( (byte) ( 0x32) ); // 填充类型 + + // iv 暂未支持 + // P 长度暂未支持 + + + // 填充多个消息数据长度 + for ( byte[] data : pINdata ) { + bb.put( String.format("%03X", data.length).getBytes() ); + } + + // 填充多个消息数据 + for ( byte[] data : pINdata ) { + bb.put( data ); + } + + // 重新计算长度 + int len = bb.position(); + len -= 2; + byte[] lenArray = new byte[ 2 ]; + lenArray[0] = (byte)((len >> 8) & 0xFF); + lenArray[1] = (byte)( len & 0xFF); + + bb.put( 0, (byte)((len >> 8) & 0xFF) ); + bb.put( 1, (byte)( len & 0xFF) ); + + // 通信 + synchronized (this) { + // 响应解析 + bb = syncRead(syncSend(bb)); + } + + bb.flip(); + bb.position( 12 ); + byte[] code = new byte[2]; + bb.get( code ); + + int retCode = Integer.valueOf( new String( code ) ); + if ( 0 != retCode ) { + throw new SydApiException( retCode ); + } + + // 跳过输出模式 + bb.get(); + + // 获取 N 个长度 + int[] lens = new int[ batchSize ]; + for ( int i = 0; i < batchSize; i++ ){ + byte[] iLenArray = new byte[3]; + bb.get( iLenArray ); + lens[ i ] = Integer.valueOf( new String( iLenArray ), 16 ); + } + + Listret = new ArrayList(); + // 获取 N 个长度的数据 + for ( int l : lens ) { + byte[] d = new byte[ l ]; + bb.get(d); + ret.add( d ); + } + return ret; } @@ -3762,6 +3875,13 @@ public class SydApi4j implements SydApi { // 测试通过 public String SM2GetPrivateKeyC(String privateKeyTag) { + if ( privateKeyTag.length() < 16 ) { + privateKeyTag = "0000000000000000" + privateKeyTag; + privateKeyTag = privateKeyTag.substring( privateKeyTag.length() -16 ); + privateKeyTag += "00000000001"; + } + + ProtoQP proto = new ProtoQP(); HashMap packet = new HashMap(); HashMap data = new HashMap(); @@ -4008,13 +4128,13 @@ public class SydApi4j implements SydApi { * @param orgData 要签名的信息 * @return 签名结果 */ - public String SM2SignC(int flag, String privateKey, byte[] publicKey, byte[] orgData) { + public byte[] SM2SignC(int flag, String privateKey, byte[] publicKey, byte[] orgData) { return SM2SignC(flag, "1234567812345678", privateKey, publicKey, orgData); } // 测试通过 @Override - public String SM2SignC(int flag, String uid, String privateKey, byte[] publicKey, byte[] orgData) { + public byte[] SM2SignC(int flag, String uid, String privateKey, byte[] publicKey, byte[] orgData) { Proto74 proto = new Proto74(); @@ -4055,7 +4175,7 @@ public class SydApi4j implements SydApi { byte[] s = new byte[a]; bb.get(s, 0, a); - return SYMUtil.derSign2Base64Sign(s); + return Util.decodeBase64( SYMUtil.derSign2Base64Sign(s) ); } @@ -4226,6 +4346,17 @@ public class SydApi4j implements SydApi { return ((PacketSection) ret.get("signature")).getString(); } + @Override + public boolean SM2Verify( + int nOrgDataType, + byte[] publicKey, + byte[] orgData, + byte[] sign + ) { + String certNo = "1234567812345678"; + return SM2Verify(certNo, nOrgDataType, publicKey, orgData, sign); + } + @Override public boolean SM2Verify( int nOrgDataType, @@ -4234,9 +4365,10 @@ public class SydApi4j implements SydApi { String base64Sign ) { String certNo = "1234567812345678"; - return SM2Verify(certNo, nOrgDataType, publicKey, orgData, base64Sign); + return SM2Verify(certNo, nOrgDataType, publicKey, orgData, Util.decodeBase64(base64Sign) ); } + @Override public String SM2Sign( int nOrgDataType, @@ -4333,7 +4465,7 @@ public class SydApi4j implements SydApi { // 测试通过 @Override - public boolean SM2Verify(String certNo, int nOrgDataType, byte[] publicKey, byte[] orgData, String base64Sign) { + public boolean SM2Verify(String certNo, int nOrgDataType, byte[] publicKey, byte[] orgData, byte[] sign) { if (certNo.length() > 32) { certNo = certNo.substring(0, 32); @@ -4341,7 +4473,7 @@ public class SydApi4j implements SydApi { Proto75 proto = new Proto75(); //pset.getProtocolReqRender("75"); - byte[] sign = SYMUtil.base64Sign2DerSign(base64Sign); + sign = SYMUtil.base64Sign2DerSign( Util.encodeBase64(sign) ); // 填充数据 HashMap packet = new HashMap(); @@ -10567,6 +10699,7 @@ public class SydApi4j implements SydApi { } public String attachedSignSoft(byte[] orgData, String sCertDN) throws UnsupportedEncodingException { + sCertDN = DnUtil.verifyDn( sCertDN ); String pk = this.GetDNPublicKey( SydApi.FOR_SIGN, sCertDN.getBytes("GBK") ); try { byte[] hash = this.SM3Hash( pk, orgData ); diff --git a/src/test/java/com/sunyard/sydapi/loadrunner/raw/Actions.java b/src/test/java/com/sunyard/sydapi/loadrunner/raw/Actions.java new file mode 100644 index 0000000..50f6557 --- /dev/null +++ b/src/test/java/com/sunyard/sydapi/loadrunner/raw/Actions.java @@ -0,0 +1,75 @@ +package com.sunyard.sydapi.loadrunner.raw; + +/* + * LoadRunner Java script. (Build: _build_number_) + * + * Script Description: + * + */ + +import lrapi.lr; +import racal.sunyard.main.SydApi4j; +import racal.sunyard.main.SydApiBuilder; +import com.sunyard.proto.Util; +import com.sunyard.SydApi; + +public class Actions +{ + + private static final String inHexData = "67c6697351ff4aec29cdbaabf2fbe346"; + + private static String pk ; + private static String sk ; + private SydApi api; + + + + public int init() throws Throwable { + SydApiBuilder builder = new SydApiBuilder().setIp("192.168.1.123"); + api = builder.build(); + + this.pk = api.SM2GetPublicKeyC("123", 0 ); + this.sk = api.SM2GetPrivateKeyC("123"); + + return 0; + }//end of init + + + public int action() throws Throwable { + lr.start_transaction("auto");//设置事务开始点 + + try { + + System.out.println("begin SYD_Sign_P1"); + byte[] sign = this.api.SM2SignC( 0 , sk, Util.hexString2Bytes(pk), Util.hexString2Bytes(inHexData) ); + System.out.println("sign=" + Util.bytes2HexString( sign )); + + System.out.println("begin SYD_Verify_P1"); + boolean pass = api.SM2Verify(1, Util.hexString2Bytes(pk), Util.hexString2Bytes(inHexData), sign ); + System.out.println("验签结果 " + pass); + System.out.println("end SYD_Verify_P1"); + + } finally { + lr.end_transaction("auto", lr.AUTO);//设置事务结束点 + } + + return 0; + }//end of action + + + public int end() throws Throwable { + return 0; + }//end of end + + + public static void main(String[] args) throws Throwable { + + Actions actions = new Actions(); + actions.init(); + actions.action(); + actions.end(); + } + +} + + diff --git a/src/test/java/com/sunyard/sydapi/loadrunner/raw_uid/Actions.java b/src/test/java/com/sunyard/sydapi/loadrunner/raw_uid/Actions.java new file mode 100644 index 0000000..89ffd23 --- /dev/null +++ b/src/test/java/com/sunyard/sydapi/loadrunner/raw_uid/Actions.java @@ -0,0 +1,76 @@ +package com.sunyard.sydapi.loadrunner.raw_uid; + +/* + * LoadRunner Java script. (Build: _build_number_) + * + * Script Description: + * + */ + +import lrapi.lr; +import racal.sunyard.main.SydApi4j; +import racal.sunyard.main.SydApiBuilder; +import com.sunyard.proto.Util; +import com.sunyard.SydApi; + +public class Actions +{ + + private static final String inHexData = "67c6697351ff4aec29cdbaabf2fbe346"; + private static final String uid = "8765432187654321"; + + private static String pk ; + private static String sk ; + private SydApi api; + + + + public int init() throws Throwable { + SydApiBuilder builder = new SydApiBuilder().setIp("192.168.1.123"); + api = builder.build(); + + this.pk = api.SM2GetPublicKeyC("123", 0 ); + this.sk = api.SM2GetPrivateKeyC("123"); + + return 0; + }//end of init + + + public int action() throws Throwable { + lr.start_transaction("auto");//设置事务开始点 + + try { + + System.out.println("begin SYD_Sign_P1"); + byte[] sign = this.api.SM2SignC( 0, uid , sk, Util.hexString2Bytes(pk), Util.hexString2Bytes(inHexData) ); + System.out.println("sign=" + Util.bytes2HexString( sign )); + + System.out.println("begin SYD_Verify_P1"); + boolean pass = api.SM2Verify( uid, 1, Util.hexString2Bytes(pk), Util.hexString2Bytes(inHexData), sign ); + System.out.println("验签结果 " + pass); + System.out.println("end SYD_Verify_P1"); + + } finally { + lr.end_transaction("auto", lr.AUTO);//设置事务结束点 + } + + return 0; + }//end of action + + + public int end() throws Throwable { + return 0; + }//end of end + + + public static void main(String[] args) throws Throwable { + + Actions actions = new Actions(); + actions.init(); + actions.action(); + actions.end(); + } + +} + + diff --git a/src/test/java/com/sunyard/sydapi/test/ABCNorthBranch.java b/src/test/java/com/sunyard/sydapi/test/ABCNorthBranch.java deleted file mode 100644 index 4cf1c69..0000000 --- a/src/test/java/com/sunyard/sydapi/test/ABCNorthBranch.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.sunyard.sydapi.test; - -import com.sunyard.RetWrap; -import com.sunyard.SydApi; -import com.sunyard.proto.Util; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import racal.sunyard.main.SydApi4j; - -import java.io.UnsupportedEncodingException; - -import static com.sunyard.sydapi.util.PrintUtil.printByteArray; -import static com.sunyard.sydapi.util.PrintUtil.printRetWrap; - -/** - * 农行北分海淀支行-军队资金集中收付系统 - */ -public class ABCNorthBranch { - - SydApi4j api; - - // SM2密钥索引 - String SM2PrivateKeyTag = "111111111111115100000000001"; - // SM2公钥 - String SM2PublicKey = null; - // SM2私钥 - String SM2PrivateKey = null; - - // SM4密钥索引 - String SM4PrivateKeyTag = "000000000000000100011111111"; - // SM4密钥 - String SM4Key = null; - - - @Before - public void before() { - System.setProperty("com.sunyard.sydapi4j.debug", "true"); - api = (SydApi4j) new SydApi4j().connect("61.164.40.82", 8889, null, 5000); - - SM2PublicKey = api.SM2GetPublicKeyC(SM2PrivateKeyTag); - SM2PrivateKey = api.SM2GetPrivateKeyC(SM2PrivateKeyTag); - - - SM4Key = new String((byte[]) api.readKey(SM4PrivateKeyTag).get("key")); - - System.out.println("=========================================密钥获取完成========================================="); - } - - @After - public void after() { - try { - this.api.disconnect(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - // A4 - @Test - public void testComposeKey() { - String[] strs = {"583034303438393445374238444531323942344646344546393838394535364132", "583934443335443836454631463332313344353543343738323246383744333835"}; - RetWrap rw = api.composeKey("000", strs); - - printRetWrap(rw); - } - - - // 测试通过 - // 74 - @Test - public void testSM2SignC2() { - String thisOrgData = "FFFFFFFFFFFFFFFF"; - - String s = api.SM2SignC(1, SM2PrivateKeyTag, Util.hexString2Bytes(SM2PublicKey), thisOrgData.getBytes()); - System.out.println(s); - } - - // 测试通过 - // 74 - @Test - public void testSM2SignC3() { - String thisOrgData = "FFFFFFFFFFFFFFFF"; - - String s = api.SM2SignC(0, SM2PrivateKey, Util.hexString2Bytes(SM2PublicKey), thisOrgData.getBytes()); - System.out.println(s); - } - - // 75 - @Test - public void testSM2SignAndVerify() { - String orgData = "11111111111111"; - - // 这里,不管是签名还是验签,都需要在外部做一次hash。 - byte[] hash = api.SM3Hash(SM2PublicKey, orgData.getBytes()); - - /** - * 用私钥签名(外部私钥) - * @param nOrgDataType 签名数据类型,0 : hash 1 : 原数据 - * @param privateKey LMK34-35 下加密的私钥 - * @param orgData “签名数据类型”为 0 时:HASH 值。“签名数据类型”为 1 时:要签名的信息 - * @return 签名的 base64 编码 - */ - String s = api.SM2Sign(SydApi.DATA_HASH, Util.hexString2Bytes(SM2PrivateKey), hash); - - // 这里的签名结果已经符合条件了,不需要做转换 - System.out.println("签名结果: " + s); - System.out.println("decBase64:" + Util.bytes2HexString(Util.decodeBase64(s))); - /** - * 用指定的公钥对指定的原始数据进行数字签名验证(PKCS#1) - * @param nOrgDataType 签名数据类型,SydApi.DATA_ORIGIN(1) 原始数据 SydApi.DATA_HASH(0) : hash 后的类型 - * @param publicKey 公钥串,DER编码,HEX格式 - * @param orgData 待签名的原始数据,“签名数据类型”为 0 时:HASH 值。“签名数据类型”为 1 时:要签名的信息 - * @param base64Sign 签名数据 (DER 编码 + Base64 编码) - * @return 验签是否通过 - */ - boolean b = api.SM2Verify(SydApi.DATA_HASH, Util.hexString2Bytes(SM2PublicKey), hash, s); - System.out.println("验签结果: " + b); - } - - - // 测试通过 - // 75 - @Test - public void testSM2Verify3() { - - String thisOrgData = "FFFFFFFFFFFFFFFF"; - - String s = api.SM2SignC(1, SM2PrivateKeyTag, Util.hexString2Bytes(SM2PublicKey), thisOrgData.getBytes()); - - System.out.println(s); - boolean b = api.SM2Verify(Util.hexString2Bytes(SM2PublicKey), thisOrgData.getBytes(), s); - System.out.println(b); - } - - // 测试通过 - // E0 - @Test - public void testSM4EncryptDataCBC() { - String msg = "1111111111111111111111"; - byte[] bytes = api.SM4EncryptDataCBC(0, SM4Key, 0, 0, msg.getBytes()); - printByteArray(bytes); - - } - - // 测试通过 - // E0 - @Test - public void testSM4DecryptDataCBC() { - String msg = "11111111111"; - byte[] bytes = api.SM4EncryptDataCBC(0, SM4Key, 0, 0, msg.getBytes()); - - byte[] bytes1 = api.SM4DecryptDataCBC(0, SM4Key, 0, 0, bytes); - - printByteArray(bytes1, false); - } - - // 测试通过 - // E0 - @Test - public void testSM4EncryptFileDataCBC() { - - String inFilePath = "C:\\Users\\edgar\\Desktop\\fsdownload\\test\\in1.txt"; - String outFilePath = "C:\\Users\\edgar\\Desktop\\fsdownload\\test\\in2.txt"; - boolean b = api.SM4EncryptFileDataCBC(0, SM4Key, 0, 0, inFilePath, outFilePath); - System.out.println(b); - } - - - // 测试通过 - // E0 - @Test - public void testSM4DecryptFileDataCBC() throws UnsupportedEncodingException { - - String outFilePath = "C:\\Users\\edgar\\Desktop\\fsdownload\\test\\in2.txt"; - String outFilePath2 = "C:\\Users\\edgar\\Desktop\\fsdownload\\test\\out1.txt"; - boolean b = api.SM4DecryptFileDataCBC(0, SM4Key, 0, 0, outFilePath, outFilePath2); - System.out.println(b); - } - - // LF - @Test - public void testReadKey() { - RetWrap retWrap = api.readKey(SM4PrivateKeyTag); - printRetWrap(retWrap); - } - - // QQ - @Test - public void testSM2GetPublicKeyC3() { - - String s = api.SM2GetPublicKeyC(SM2PrivateKeyTag); - System.out.println(s); - } - - // QP - @Test - public void testSM2GetPrivateKeyC() { - String s = api.SM2GetPrivateKeyC(SM2PrivateKeyTag); - System.out.println(s); - } - -} diff --git a/src/test/java/com/sunyard/sydapi/test/Shanqing.java b/src/test/java/com/sunyard/sydapi/test/Shanqing.java new file mode 100644 index 0000000..b0799a0 --- /dev/null +++ b/src/test/java/com/sunyard/sydapi/test/Shanqing.java @@ -0,0 +1,415 @@ +package com.sunyard.sydapi.test; + +import com.sunyard.RetWrap; +import com.sunyard.SydApi; +import com.sunyard.cert.X509; +import com.sunyard.proto.Util; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import racal.sunyard.main.SydApi4j; + +import java.io.UnsupportedEncodingException; + + +/** + * 上清例子 + */ +public class Shanqing { + + SydApi4j api; + + @Before + public void before() { + // 通过设置debug的属性开启debug,如果不设置则默认不打开 + System.setProperty("com.sunyard.sydapi4j.debug", "true"); + api = (SydApi4j) new SydApi4j().connect("192.168.0.200", 8889, null, 1000); + } + + @After + public void after() { + try { + this.api.disconnect(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * 流程演示 + */ + @Test + public void testProcess() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = new byte[2 * 1024 * 1024]; + + // 签名 + String sign = api.attachedSign(orgData, dn); + System.out.println("签名结果: " + sign); + + // 生成数字信封 + RetWrap retWrap = api.generateDEByDn(dn, sign.getBytes()); + byte[] cipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + System.out.println("数字信封: " + new String(cipherKey)); + + // 解密数字信封 + RetWrap retWrap1 = api.decryptDEByDN(dn, cipherKey); + byte[] oData = (byte[]) retWrap1.get("oData"); + System.out.println("原数据: " + retWrap1.get("oData")); + + // 验签 + RetWrap verify = api.attachedVerifyAndGetAll(oData); + if (verify != null) { + System.out.println("x509公钥: " + Util.bytes2HexString(((X509) verify.get("x509")).getPubKey())); + System.out.println("签名原数据: " + Util.bytes2HexString((byte[]) (verify.get("oData")))); + } + + } + + // + // 测试通过 + // 73 + @Test + public void testSM2ConfirmSessionKeyC() { + + String userId = "8012"; + byte[] data = "12343242".getBytes(); + + // 通过用户id获取公钥 + String pk = api.SM2GetPublicKeyC(userId, SydApi.FOR_ENCRYPT); + + // 生成数字信封 + RetWrap retWrap = api.SM2GenSessionKey(pk); + printRetWrap(retWrap); + String cipherKey = (String) retWrap.get(SydApi.RET_CIPHER_KEY); + String sessionKey = (String) retWrap.get(SydApi.RET_SESSION_KEY); + String kcv = (String) retWrap.get(SydApi.RET_KCV); + + // 使用生成的对称密钥加密数据 + byte[] dataEnc = api.SYMEncryptData(SydApi.NALG_SM4, sessionKey, data); + + // 解密数字信封 + RetWrap retWrap1 = api.SM2ConfirmSessionKeyC(userId, cipherKey); + printRetWrap(retWrap1); + sessionKey = (String) retWrap1.get(SydApi.RET_SESSION_KEY); + kcv = (String) retWrap1.get(SydApi.RET_KCV); + + // 使用解密出来的对称密钥解密数据 + byte[] bytes1 = api.SYMDecryptData(SydApi.NALG_SM4, sessionKey, dataEnc); + System.out.println("解密后的数据:" + new String(bytes1)); + } + + + @Test + public void testDetachedSignAndVerify1() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + String orgData = "111111213323143243243"; + + + String sign = api.attachedSign(orgData.getBytes(), dn); + System.out.println("签名结果: " + sign); + System.out.println("签名结果 hex : " + Util.bytes2HexString(Util.decodeBase64(sign))); + + boolean verify = api.attachedVerify(sign); + System.out.println("验签结果: " + verify); + Assert.assertTrue(verify); + } + + + @Test + public void testDetachedSignAndVerify2() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + String orgData = "111111213323143243243"; + + + String sign = api.attachedSignSoft(orgData.getBytes(), dn); + System.out.println("签名结果: " + sign); + System.out.println("签名结果 hex: " + Util.bytes2HexString(Util.decodeBase64(sign))); + + boolean verify = api.attachedVerify(sign); + System.out.println("验签结果: " + verify); + Assert.assertTrue(verify); + } + + + @Test + public void testDetachedSignAndVerify3() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = new byte[3 * 1024]; + + String sign = api.attachedSign(orgData, dn); + System.out.println("签名结果: " + sign); + System.out.println("签名结果 hex: " + Util.bytes2HexString(Util.decodeBase64(sign))); + + boolean verify = api.attachedVerify(sign); + System.out.println("验签结果: " + verify); + Assert.assertTrue(verify); + } + + @Test + public void testDetachedSignAndVerify8() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = new byte[8 * 1024]; + + String sign = api.attachedSign(orgData, dn); + System.out.println("签名结果: " + sign); + System.out.println("签名结果 hex: " + Util.bytes2HexString(Util.decodeBase64(sign))); + + boolean verify = api.attachedVerify(sign); + System.out.println("验签结果: " + verify); + Assert.assertTrue(verify); + } + + // 测试通过 + // 8018 + @Test + public void testAttachedSignAndVerify() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + String orgData = "111111213323143243243"; + String sign = api.attachedSign(orgData.getBytes(), dn); + System.out.println("签名结果: " + sign); + System.out.println("签名结果 hex : " + Util.bytes2HexString(Util.decodeBase64(sign))); + + boolean verify = api.attachedVerify(sign); + System.out.println("验签结果: " + verify); + } + + @Test + public void testAttachedSignAndVerifyGetX509() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = "111111213323143243243".getBytes(); + String sign = api.attachedSign(orgData, dn); + System.out.println("签名结果: " + sign); + + + X509 verify = api.attachedVerifyAndGetX509(sign); + System.out.println("验签结果: " + Util.bytes2HexString(verify.getPubKey())); + } + + @Test + public void testAttachedSignAndVerifyRD() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + String orgData = "111111213323143243243"; + String sign = api.attachedSign(orgData.getBytes(), dn); + System.out.println("签名结果: " + sign); + + byte[] verify = api.attachedVerifyRD(sign); + System.out.println("验签结果: " + Util.bytes2HexString(verify)); + } + + @Test + public void testAttachedSignAndVerifyGetAll() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = "111111213323143243243".getBytes(); + String sign = api.attachedSign(orgData, dn); + System.out.println("签名结果: " + sign); + + RetWrap verify = api.attachedVerifyAndGetAll(sign); + if (verify != null) { + System.out.println("x509公钥: " + Util.bytes2HexString(((X509) verify.get("x509")).getPubKey())); + System.out.println("签名原数据: " + verify.get("oData")); + } + } + + @Test + public void testAttachedSignAndVerifyGetAll8k() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = new byte[ 8 * 1024 ]; + String sign = api.attachedSign(orgData, dn); + System.out.println("签名结果: " + sign); + + RetWrap verify = api.attachedVerifyAndGetAll(sign); + if (verify != null) { + System.out.println("x509公钥: " + Util.bytes2HexString(((X509) verify.get("x509")).getPubKey())); + System.out.println("签名原数据: " + verify.get("oData")); + } + } + + + @Test + public void testAttachedSignAndVerifyGetX509C() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = "111111213323143243243".getBytes(); + byte[] sign = api.attachedSignC(orgData, dn); + System.out.println("签名结果: " + sign); + + X509 verify = api.attachedVerifyAndGetX509(sign); + System.out.println("验签结果: " + Util.bytes2HexString(verify.getPubKey())); + } + + @Test + public void testAttachedSignAndVerifyRDC() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + String orgData = "111111213323143243243"; + byte[] sign = api.attachedSignC(orgData.getBytes(), dn); + System.out.println("签名结果: " + sign); + + byte[] verify = api.attachedVerifyRD(sign); + System.out.println("验签结果: " + Util.bytes2HexString(verify)); + } + + @Test + public void testAttachedSignAndVerifyGetAllC() { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = "111111213323143243243".getBytes(); + byte[] sign = api.attachedSignC(orgData, dn); + System.out.println("签名结果: " + sign); + + + RetWrap verify = api.attachedVerifyAndGetAll(sign); + if (verify != null) { + System.out.println("x509公钥: " + Util.bytes2HexString(((X509) verify.get("x509")).getPubKey())); + System.out.println("签名原数据: " + verify.get("oData")); + } + } + + @Test + public void testDecryptDE54k12() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] oData = new byte[4 * 1024]; + + RetWrap retWrap = api.generateDEByDnHsm(dn, oData); + byte[] CipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + byte[] sessionKey = (byte[]) retWrap.get(SydApi.RET_SESSION_KEY); + printRetWrap(retWrap); + + RetWrap retWrap1 = api.decryptDEByDNSoft(dn, new String(CipherKey)); + printRetWrap(retWrap1); + byte[] deData = (byte[]) retWrap1.get("oData"); + Assert.assertArrayEquals(deData, oData); + } + + @Test + public void testDecryptDE54k21() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] oData = new byte[4 * 1024]; + + RetWrap retWrap = api.generateDEByDnSoft(dn, oData); + byte[] CipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + byte[] sessionKey = (byte[]) retWrap.get(SydApi.RET_SESSION_KEY); + printRetWrap(retWrap); + + RetWrap retWrap1 = api.decryptDEByDNHsm(dn, new String(CipherKey)); + printRetWrap(retWrap1); + byte[] deData = (byte[]) retWrap1.get("oData"); + Assert.assertArrayEquals(deData, oData); + } + + + @Test + public void testDecryptDE54k() throws UnsupportedEncodingException { + + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] oData = new byte[4 * 1024]; + + RetWrap retWrap = api.generateDEByDn(dn, oData); + byte[] CipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + byte[] sessionKey = (byte[]) retWrap.get(SydApi.RET_SESSION_KEY); + printRetWrap(retWrap); + + RetWrap retWrap1 = api.decryptDEByDN(dn, CipherKey); + printRetWrap(retWrap1); + + } + + + @Test + public void testDecryptDE54kr() throws UnsupportedEncodingException { + String dn = "CN=YCCA@黄金交易所@Zhuangj@1,OU=Individual-2,OU=YCCA,O=CFCA OCA1,C=CN"; + byte[] oData = new byte[4 * 1024]; + + RetWrap retWrap = api.generateDEByDn(dn, oData); + byte[] CipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + byte[] sessionKey = (byte[]) retWrap.get(SydApi.RET_SESSION_KEY); + printRetWrap(retWrap); + + RetWrap retWrap1 = api.decryptDEByDN(dn, CipherKey); + printRetWrap(retWrap1); + } + + + @Test + public void testDecryptDE520M() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] oData = new byte[20 * 1024 * 1024]; + + RetWrap retWrap = api.generateDEByDn(dn, oData); + byte[] CipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + byte[] sessionKey = (byte[]) retWrap.get(SydApi.RET_SESSION_KEY); + printRetWrap(retWrap); + + RetWrap retWrap1 = api.decryptDEByDN(dn, CipherKey); + printRetWrap(retWrap1); + } + + @Test + public void testDecryptDE58k() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] oData = new byte[8 * 1024]; + + RetWrap retWrap = api.generateDEByDn(dn, oData); + byte[] CipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + byte[] sessionKey = (byte[]) retWrap.get(SydApi.RET_SESSION_KEY); + printRetWrap(retWrap); + + RetWrap retWrap1 = api.decryptDEByDN(dn, CipherKey); + printRetWrap(retWrap1); + } + + @Test + public void testDecryptDE5() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] oData = "00001111222233".getBytes(); + + RetWrap retWrap = api.generateDEByDn(dn, oData); + byte[] CipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + byte[] sessionKey = (byte[]) retWrap.get(SydApi.RET_SESSION_KEY); + printRetWrap(retWrap); + + RetWrap retWrap1 = api.decryptDEByDN(dn, CipherKey); + printRetWrap(retWrap1); + } + + + // 测试通过 + // 76 + @Test + public void testSM3Hash() { + String orgData = "FFFFFFFFFFFFFFFF"; + + byte[] hash = api.SM3Hash(orgData.getBytes()); + + System.out.println("hash:" + Util.bytes2HexString(hash)); + } + + + // =============================工具方法============================================== + + public static void printRetWrap(RetWrap rw) { + printRetWrap(rw, false); + } + + /** + * 输出 + * + * @param rw + */ + public static void printRetWrap(RetWrap rw, boolean flag) { + for (String s : rw.keySet()) { + + Object o = rw.get(s); + if (o instanceof String) { + System.out.println(s + ":" + o); + } else if (o instanceof byte[]) { + if (flag) { + System.out.println(s + ": " + Util.bytes2HexString((byte[]) o)); + } else { + System.out.println(s + ": " + new String((byte[]) o)); + } + } else { + System.out.println(s + ":" + o); + } + } + } +} diff --git a/src/test/java/com/sunyard/sydapi/test/TestBatchData.java b/src/test/java/com/sunyard/sydapi/test/TestBatchData.java new file mode 100644 index 0000000..c14d640 --- /dev/null +++ b/src/test/java/com/sunyard/sydapi/test/TestBatchData.java @@ -0,0 +1,29 @@ +package com.sunyard.sydapi.test; + + +import com.sunyard.proto.Util; +import racal.sunyard.main.SydApi4j; + +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; + +public class TestBatchData { + public static void main(String[] args) throws UnsupportedEncodingException { + + System.setProperty("com.sunyard.sydapi4j.debug", "true"); + SydApi4j.SYD_Set_Parameter_HA("unkown", "192.168.0.200", 8889, 3000); + + SydApi4j api = (SydApi4j) new SydApi4j();//.connect("wuyong.fullstack.club" , 8889, null,1000); + + + String[] keys = new String[]{"SK000000000000000000A00000000"}; + List pINdata = new ArrayList(); + pINdata.add("12345678".getBytes()); + + List datas = api.SYMEncryptDecryptBatchData(0x8, keys, 1, pINdata); + +// boolean pass = api.SM2Verify( 1, Util.hexString2Bytes(pk), Util.hexString2Bytes(inHexData), sign ); + } +} diff --git a/src/test/java/com/sunyard/sydapi/test/TestHT.java b/src/test/java/com/sunyard/sydapi/test/TestHT.java index 4e4d6d9..b7fb9ab 100644 --- a/src/test/java/com/sunyard/sydapi/test/TestHT.java +++ b/src/test/java/com/sunyard/sydapi/test/TestHT.java @@ -23,9 +23,8 @@ public class TestHT { @Before public void before() { // 通过设置debug的属性开启debug,如果不设置则默认不打开 -// System.setProperty("com.sunyard.sydapi4j.debug", "true"); + System.setProperty("com.sunyard.sydapi4j.debug", "true"); api = (SydApi4j) new SydApi4j().connect("172.16.18.59", 8889, null, 1000); -// api = (SydApi4j) new SydApi4j().connect("192.168.0.66", 8889, null, 1000); } @After @@ -108,32 +107,31 @@ public class TestHT { String orgData = "111111213323143243243"; - String sign = api.attachedSign(orgData.getBytes(), dn); + String sign = api.detachedSign(1, orgData.getBytes(), dn); System.out.println("签名结果: " + sign); System.out.println("签名结果 hex : " + Util.bytes2HexString(Util.decodeBase64(sign))); - boolean verify = api.attachedVerify(sign); + boolean verify = api.detachedVerify(1, orgData.getBytes(), sign); System.out.println("验签结果: " + verify); Assert.assertTrue(verify); } - @Test public void testDetachedSignAndVerify2() throws UnsupportedEncodingException { - String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + // Dn 反转问题 + String dn = "CN=YCCA@黄金交易所@Zhuangj@1,OU=Individual-2,OU=YCCA,O=CFCA OCA1,C=CN"; String orgData = "111111213323143243243"; - String sign = api.attachedSignSoft(orgData.getBytes(), dn); + String sign = api.detachedSign(1, orgData.getBytes(), dn); System.out.println("签名结果: " + sign); - System.out.println("签名结果 hex: " + Util.bytes2HexString(Util.decodeBase64(sign))); + System.out.println("签名结果 hex : " + Util.bytes2HexString(Util.decodeBase64(sign))); - boolean verify = api.attachedVerify(sign); + boolean verify = api.detachedVerify(1, orgData.getBytes(), sign); System.out.println("验签结果: " + verify); Assert.assertTrue(verify); } - @Test public void testDetachedSignAndVerify3() throws UnsupportedEncodingException { String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; @@ -300,6 +298,7 @@ public class TestHT { @Test public void testDecryptDE54k() throws UnsupportedEncodingException { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; byte[] oData = new byte[4 * 1024]; @@ -310,6 +309,7 @@ public class TestHT { RetWrap retWrap1 = api.decryptDEByDN(dn, CipherKey); printRetWrap(retWrap1); + } diff --git a/src/test/java/com/sunyard/sydapi/test/TestICBC.java b/src/test/java/com/sunyard/sydapi/test/TestICBC.java new file mode 100644 index 0000000..d450897 --- /dev/null +++ b/src/test/java/com/sunyard/sydapi/test/TestICBC.java @@ -0,0 +1,121 @@ +package com.sunyard.sydapi.test; + + +import com.sunyard.RetWrap; +import com.sunyard.SydApi; +import com.sunyard.proto.Util; +import racal.sunyard.main.SydApi4j; + +import java.io.UnsupportedEncodingException; +import java.util.Arrays; + +public class TestICBC { + public static void main(String[] args) throws UnsupportedEncodingException { + + + SydApi4j.SYD_Set_Parameter_HA("unkown", "172.16.17.162", 8889 , 1000); + + SydApi4j api = (SydApi4j) new SydApi4j();//.connect("wuyong.fullstack.club" , 8889, null,1000); + + + RetWrap r = api.SYD_SM2GenKeyPair(); + System.out.println( r.get("publicKey") ); + System.out.println( r.get("privateKey") ); + +// System.out.println("\n\n----- 获取公钥 () -----"); +// String pk = api.SYD_SM2_Get_Id_PublicKey_HA("1234", 0); +// System.out.print("\r\n公钥 : "); +// System.out.println( pk ); +// +// +//// pk = api.SYD_SM2_Get_Dn_PublicKey_HA("C=CN,O=Sunyard,OU=8001,CN=8001".getBytes("GBK"), 0); +//// System.out.print("\r\n公钥 : "); +//// System.out.println( pk ); +// +// +// // 签名 + String data="MainBody>1015570000408702018091900000000012018-09-19T10:13:391015570000408702015970000397542018-09-1900000001123456,测试"; + final String testPubKey = "0342000480C7E165DB8CF019509CE359C4FE06535275F5F63ADDC3955721FA4802BDC8701661554096BBC190916F39073C3763C8BEF6ABDF7A042C9F1D12B6BD6E5E2614"; +// System.out.println("\n\n----- SM2 算法签名 (原始数据) -----"); +// String sign = api.SYD_SM2_Sign_HA( +// "1234", +// SydApi.DATA_ORIGIN, +// Util.hexString2Bytes(testPubKey), +// data.getBytes() +// ); +// System.out.print("\n\n----- SM2 算法签名 结果: "); +// System.out.println( sign ); +// +// +// +// +// +// System.out.println("\n\n----- SM2 算法验签 (原始数据) -----"); +// boolean SM2VerifyRet = api.SYD_SM2_Verify_HA( +// SydApi.DATA_ORIGIN, +// Util.hexString2Bytes(testPubKey), data.getBytes() , sign); +// if (SM2VerifyRet){ +// System.out.println("验签通过"); +// }else{ +// System.err.println("验签失败"); +// throw new RuntimeException("验签失败"); +// } + + + +// // 签名验签 2 +// System.out.println("\n\n----- 签名验签 2 -----"); +// String sign2 = api.SYD_SM2_DetachedSign_HA( data.getBytes() , "C=CN,O=Sunyard,OU=8001,CN=8001"); +// System.out.println( sign2 ); + + +// String sign2 = "MIICpQYKKoEcz1UGAQQCAqCCApUwggKRAgEBMQ4wDAYIKoEcz1UBgxEFADAMBgoqgRzPVQYBBAIBoIIByTCCAcUwggFooAMCAQICCDyTAAAAAAAlMAwGCCqBHM9VAYN1BQAwJjELMAkGA1UEBhMCQ04xFzAVBgNVBAMMDlN1bnlhcmRTTTJSb290MB4XDTE3MDUxNzAyNTI0NFoXDTIyMDcyNTAyNTI0NFowPTELMAkGA1UEBhMCQ04xEDAOBgNVBAoMB1N1bnlhcmQxDTALBgNVBAsMBDgwMDExDTALBgNVBAMMBDgwMDEwWTATBgcqhkjOPQIBBggqgRzPVQGCLQNCAAQ+2joQe3zDXMAFx/vwu05rQ6B+4U42BgPSLsoqYAstD6AwVdQA0SQDAPVGSLhJ0T9QszD/FDUbVkWxNoaCCmW7o2cwZTAOBgNVHQ8BAf8EBAMCAMAwEwYDVR0lBAwwCgYIKwYBBQUHAwEwHwYDVR0jBBgwFoAU93/arv8hxtk6eq2g+6z+AqVO1cEwHQYDVR0OBBYEFAMWZaY2AwaQTNiFLpsa0dyCzBZ6MAwGCCqBHM9VAYN1BQADSQAwRgIhAIl2ZHGfln5hedcousARzZ2yeUjUbxSFMmhMmr5t6Q6nAiEAvqYX/KpIcvnPyB/Yiil+oq6DFdVM6P3vDxBhU/8taXExgaAwgZ0CAQEwMjAmMQswCQYDVQQGEwJDTjEXMBUGA1UEAwwOU3VueWFyZFNNMlJvb3QCCDyTAAAAAAAlMAwGCCqBHM9VAYMRBQAwDQYJKoEcz1UBgi0BBQAERzBFAiATwLIYiylt7xHmBkH6EclrchClxzLlKWC5guxxzkr58gIhANSw+owu8cyypdJtHGrGqjSiB1BVzGva+irUHelx/GbC"; +// sign2 = "MIID7gYKKoEcz1UGAQQCAqCCA94wggPaAgEBMQ4wDAYIKoEcz1UBgxEFADAMBgoqgRzPVQYBBAIBoIIC2jCCAtYwggJ6oAMCAQICBUACgAF0MAwGCCqBHM9VAYN1BQAwYTELMAkGA1UEBhMCQ04xMDAuBgNVBAoMJ0NoaW5hIEZpbmFuY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEgMB4GA1UEAwwXQ0ZDQSBBQ1MgVEVTVCBTTTIgT0NBMzEwHhcNMTcxMTE2MDY1NDQ1WhcNMjIxMTE2MDY1NDQ1WjCBgzELMAkGA1UEBhMCQ04xHDAaBgNVBAoME0NGQ0EgVEVTVCBTTTIgT0NBMzExDjAMBgNVBAsMBVNIQ1BFMRkwFwYDVQQLDBBPcmdhbml6YXRpb25hbC0xMSswKQYDVQQDDCIwNTFA5LiK5rW356Wo5o2u5Lqk5piT5omAQEFBQUFBQUA4MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEYPA9UQRL/ZaThEN0nc3SwkOHw4hPDXG9hZeKiBnNdhgPy1EtX4My2bpNFpYMmQ0nvkJUM4qpJrF7MSqEws6rLaOB+TCB9jA/BggrBgEFBQcBAQQzMDEwLwYIKwYBBQUHMAGGI2h0dHA6Ly9vY3NwdGVzdC5jZmNhLmNvbS5jbjo4MC9vY3NwMB8GA1UdIwQYMBaAFATHvPlZAWk+jDQ2IGIYPN68tbsMMAwGA1UdEwEB/wQCMAAwNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovLzIxMC43NC40Mi4zL09DQTMxL1NNMi9jcmwxLmNybDAOBgNVHQ8BAf8EBAMCBsAwHQYDVR0OBBYEFKJnS7XYRDWG9eqXtSzUZXK+De2/MB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDBDAMBggqgRzPVQGDdQUAA0gAMEUCIGaSRoaUSpoH4lW3at1ABluiNwFDH21jHesHmy0F5gjqAiEA0sUykW9E36F3qQ91YDvasQg8EnOMp1idhgt6pq/NUAYxgdgwgdUCAQEwajBhMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSAwHgYDVQQDDBdDRkNBIEFDUyBURVNUIFNNMiBPQ0EzMQIFQAKAAXQwDAYIKoEcz1UBgxEFADANBgkqgRzPVQGCLQEFAARHMEUCIQDH3ePzq4nYJ8pAodJyqPKqCQuQwmOpyj/rWcDILzFj2gIgUW5c9W6jD7u91opMcDwaw4aNEvEtGX6ks5XDIMIkUjI="; +// +// +// +// boolean pass = api.SYD_SM2_DetachedVerify_HA( "0000000000000002018091810000086272018-09-17T19:06:39CC00".getBytes(), sign2 ); +// System.out.println( pass ); +// +// // 获取公钥 +// X509 x = api.SYD_Get_X509_CertInfo_HA( "0000000000000002018091810000086272018-09-17T19:06:39CC00".getBytes(), sign2 ); +// System.out.println( Util.bytes2HexString( x.getPubKey() ) ); + + byte[]ttt = new byte[40960]; + Arrays.fill(ttt, (byte) 0x88); + String sign2 = api.SYD_SM2_Sign_HA( + "1234", + SydApi.DATA_HASH, + Util.hexString2Bytes("0342000480C7E165DB8CF019509CE359C4FE06535275F5F63ADDC3955721FA4802BDC8701661554096BBC190916F39073C3763C8BEF6ABDF7A042C9F1D12B6BD6E5E2614"), + ttt + ); + System.out.print("\n\n----- SM2 算法签名 结果: "); + System.out.println( sign2 ); + + System.out.println( api.SYD_SM2_Verify_HA( + SydApi.DATA_HASH, + Util.hexString2Bytes("0342000480C7E165DB8CF019509CE359C4FE06535275F5F63ADDC3955721FA4802BDC8701661554096BBC190916F39073C3763C8BEF6ABDF7A042C9F1D12B6BD6E5E2614"), + ttt , + sign2 + ) ); + + + + String sign3 = api.SYD_SM2_Sign_HA( + "1234", + SydApi.DATA_ORIGIN, + Util.hexString2Bytes("0342000480C7E165DB8CF019509CE359C4FE06535275F5F63ADDC3955721FA4802BDC8701661554096BBC190916F39073C3763C8BEF6ABDF7A042C9F1D12B6BD6E5E2614"), + "1015570000408702018091900000000012018-09-19T10:13:391015570000408702015970000397542018-09-1900000001123456,测试".getBytes() + ); + System.out.print("\n\n----- SM2 算法签名 结果: "); + System.out.println( sign3 ); + + System.out.println( api.SYD_SM2_Verify_HA( + SydApi.DATA_ORIGIN, + Util.hexString2Bytes("0342000480C7E165DB8CF019509CE359C4FE06535275F5F63ADDC3955721FA4802BDC8701661554096BBC190916F39073C3763C8BEF6ABDF7A042C9F1D12B6BD6E5E2614"), + "1015570000408702018091900000000012018-09-19T10:13:391015570000408702015970000397542018-09-1900000001123456,测试".getBytes() , + sign3 + ) ); + + } +} diff --git a/src/test/java/com/sunyard/sydapi/test/TestPKCS7.java b/src/test/java/com/sunyard/sydapi/test/TestPKCS7.java index 5b507b4..b6f9693 100644 --- a/src/test/java/com/sunyard/sydapi/test/TestPKCS7.java +++ b/src/test/java/com/sunyard/sydapi/test/TestPKCS7.java @@ -1,4 +1,4 @@ -package com.sunyard.sydapi.sample; +package com.sunyard.sydapi.test; import com.sunyard.SydApi; @@ -15,7 +15,7 @@ public class TestPKCS7 { // 连接加密机 // SydApi4j api = (SydApi4j) new SydApi4j().connect("172.16.17.162", 8889, null, 1000); - SydApi4j.SYD_Set_Parameter_HA("unkown", "192.168.0.100", 8889, 1000); + SydApi4j.SYD_Set_Parameter_HA("unkown", "172.16.18.59", 8889, 1000); SydApi4j api = (SydApi4j) new SydApi4j(); try { diff --git a/src/test/java/com/sunyard/sydapi/test/TestSDNXApi.java b/src/test/java/com/sunyard/sydapi/test/TestSDNXApi.java deleted file mode 100644 index 8ea2dee..0000000 --- a/src/test/java/com/sunyard/sydapi/test/TestSDNXApi.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.sunyard.sydapi.test; - -import com.sunyard.SydApi; -import com.sunyard.cert.X509; -import com.sunyard.inf.customize.SydSDNXApiImpl; -import racal.sunyard.main.SydApi4j; - -public class TestSDNXApi { - - private static final String testCertNo = "C=cn,O=CFCA TEST CA,OU=NCS2,OU=Enterprises,CN=041@Z402451000010@ShanDong@00000001"; - //private static final String testCertNo = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; - //private static final String testCertNo = "C=CN,O=Sunyard,OU=8001,CN=8001"; - //private static final String testData = "1015570000408702018091900000000012018-09-19T10:13:391015570000408702015970000397542018-09-1900000001123456,测试"; - private static final String testData = "0000000000000002019022310000129102019-02-23T09:29:19CC00"; - private static final String testUser = "201597"; - //private static final String testUser = "8001"; - //private static final String testUser = "402030000011"; - - public static void main(String[] args) { - - - SydApi api = null; - System.out.println("\n\n----- connect -----"); - - // 建议从配置文件读取配置 - - // 单服务器测试使用 -// PoolManager.INSTANCE.createPool("default", "{\n" + -// " \"mode\" : \"solo\", // (必填)\n" + -// " \"oipc\" : \"com.sunyard.pool4sydapi.SydApiSDNXInPool\", " + -// " \"ip\" : \"172.16.18.71\", // (必填)\n" + -// " \"port\": 8889, // (必填)【数字】\n" + -// " \"pwd\": \"\", // 没有就不填写此项\n" + -// " \"timeout\": 1000 //【数字】不限超时时间就不填写此项\n" + -// "}"); - - - // // 推荐配置 -// PoolManager.INSTANCE.createPool("default", "{\n" + -// " \"mode\" : \"round-robin\", // (必填)\n" + -// " \"oipc\" : \"com.sunyard.pool4sydapi.SydApiSDNXInPool\", // (必填)\n" + -// " \"ips\" : [ // (必填)\n" + -// " \"172.16.18.69\",\n" + -// " \"172.16.18.70\"\n" + -// " ],\n" + -// " \"port\": 8889, //(必填)【数字】\n" + -// " \"pwd\": \"\", //【数字】没有就不填写此项\n" + -// " \"timeout\": 1000 , //【数字】【数字】链接和响应超时时限,不限超时时间就不填写此项\n" + -// " \"connectTimeout\" : 1000, //【数字】【数字】链接超时时限,如果没有传递,但是存在 timeout 就等于 timeout 的值\n" + -// " \"waitRecvTimeout\" : 1000, //【数字】【数字】响应超时时限,如果没有传递,但是存在 timeout 就等于 timeout 的值\n" + -// " \"maxContinuousErrorTime\" : 3, //【数字】 单台加密机连续出错次数\n" + -// " \"recoveryTime\" : 300000, //【数字】 恢复时间,单位毫秒,默认 5 分钟,最大 2^63\n" + -// " \"keepAlive\" : 1, //【数字】 保持链接个数,默认是链接池个数的一半\n" + -// " \"maxAliveTime\" : 300000000, //【数字】 最大生存时间\n" + -// " \"maxIdleTime\" : 300000 , //【数字】 最大空闲时间,默认 5 分钟,最大 2^63\n" + -// " \"checkMode\" : \"before/after/deamon\", // 链接检测模式,使用前/使用后/后台轮询\n" + -// " \"checkGap\" : 300000 // 后台轮询检测间隔\n" + -// "}"); - - // 自定义配置 -// PoolManager.INSTANCE.createPool("default", "{\n" + -// " \"mode\" : \"weighted-round-robin\", // (必填)\n" + -// " \"oipc\" : \"com.sunyard.pool4sydapi.SydApiSDNXInPool\", // (必填)\n" + -// " \"ips\" : { // (必填)\n" + -// " \"172.16.18.69\" : 1,\n" + -// " \"172.16.18.70\" : 3\n" + -// " },\n" + -// " \"port\": 8889, //(必填)【数字】\n" + -// " \"pwd\": \"\", //【数字】没有就不填写此项\n" + -// " \"timeout\": 1000 , //【数字】【数字】链接和响应超时时限,不限超时时间就不填写此项\n" + -// " \"connectTimeout\" : 1000, //【数字】【数字】链接超时时限,如果没有传递,但是存在 timeout 就等于 timeout 的值\n" + -// " \"waitRecvTimeout\" : 1000, //【数字】【数字】响应超时时限,如果没有传递,但是存在 timeout 就等于 timeout 的值\n" + -// " \"maxContinuousErrorTime\" : 3, //【数字】 单台加密机连续出错次数\n" + -// " \"recoveryTime\" : 300000, //【数字】 恢复时间,单位毫秒,默认 5 分钟,最大 2^63\n" + -// " \"keepAlive\" : 1, //【数字】 保持链接个数,默认是链接池个数的一半\n" + -// " \"maxAliveTime\" : 300000000, //【数字】 最大生存时间\n" + -// " \"maxIdleTime\" : 300000 , //【数字】 最大空闲时间,默认 5 分钟,最大 2^63\n" + -// " \"checkMode\" : \"before/after/deamon\", // 链接检测模式,使用前/使用后/后台轮询\n" + -// " \"checkGap\" : 300000 // 后台轮询检测间隔\n" + -// "}"); - - - try { - - - //热备模式连接 - SydApi4j.SYD_Set_Parameter_HA("unkown", "122.224.86.107", 8889, 1000); - api = new SydApi4j(); - - - // 链接池和负载均衡模式 - //api = (SydSDNXApiImpl) PoolManager.INSTANCE.getPool().get().getOrigin(); - - System.out.println("连接加密机成功"); - } catch (Exception e) { - e.printStackTrace(); - } - - - try { - - - //用证书DN签名 - //case1(api); - - //根据机构号验签,上传并返回证书内容,并更新机构号 - case2(api); - - - //裸签名 - //case3(api); - - //验签 - //case4(api); - - } finally { - System.out.println("\n\n----- disconnect -----"); - api.disconnect(); - } - - System.out.println("执行结束\n\n"); - } - - public static void case1(SydSDNXApiImpl api) { - - System.out.println("\n\n----- 签名 基础接口原始数据模式 -----"); - String sign = api.detachedSign(SydApi4j.DATA_ORIGIN, testData.getBytes(), testCertNo); - System.out.println("\t签名结果: " + sign); - - - } - - //需要上传验签结果,测试的时候签名和验签不能同时进行,签名以后要删除数据库数据才可以验签(仅限测试可以这样操作) - public static void case2(SydApi api) { - - System.out.println("\n\n----- 验签 ,上传并返回证书内容,并更新机构号 -----"); - - String sign = "MIIEYQYKKoEcz1UGAQQCAqCCBFEwggRNAgEBMQ4wDAYIKoEcz1UBgxEFADAMBgoqgRzPVQYBBAIBoIIDUjCCA04wggLyoAMCAQICBUCEF1MkMAwGCCqBHM9VAYN1BQAwXDELMAkGA1UEBhMCQ04xMDAuBgNVBAoMJ0NoaW5hIEZpbmFuY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEbMBkGA1UEAwwSQ0ZDQSBBQ1MgU00yIE9DQTMxMB4XDTE4MDExNzAxMTExMFoXDTIzMDExNzAxMTExMFowgYIxCzAJBgNVBAYTAkNOMRswGQYDVQQKDBJDRkNBIEFDUyBTTTIgT0NBMzExDjAMBgNVBAsMBVNIQ1BFMRkwFwYDVQQLDBBPcmdhbml6YXRpb25hbC0xMSswKQYDVQQDDCIwNTFA5LiK5rW356Wo5o2u5Lqk5piT5omAQEFBQUFBQUAxMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEz79HajSQLou2kkL6n26pCKkcKcbHTWR6MbArRQruWY+WDiyPhRaYLU4W6d8wBTDTOS6T5dCtSNZBxeb5qoeeNaOCAXYwggFyMGwGCCsGAQUFBwEBBGAwXjAoBggrBgEFBQcwAYYcaHR0cDovL29jc3AuY2ZjYS5jb20uY24vb2NzcDAyBggrBgEFBQcwAoYmaHR0cDovL2NybC5jZmNhLmNvbS5jbi9vY2EzMS9vY2EzMS5jZXIwHwYDVR0jBBgwFoAUCNjRJsRIfZzsrJjp8X9iuYDOqUUwDAYDVR0TAQH/BAIwADBIBgNVHSAEQTA/MD0GCGCBHIbvKgEEMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuY2ZjYS5jb20uY24vdXMvdXMtMTQuaHRtMDsGA1UdHwQ0MDIwMKAuoCyGKmh0dHA6Ly9jcmwuY2ZjYS5jb20uY24vb2NhMzEvU00yL2NybDcyLmNybDAOBgNVHQ8BAf8EBAMCBsAwHQYDVR0OBBYEFIzDvi38AZLlWA/Wqfk93ZPe7qNgMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDBDAMBggqgRzPVQGDdQUAA0gAMEUCICDVyelEL86xbj0mAeMl3knQD0n2QKERtni/e82bQz/nAiEAjq5SKIaVJu9T/lkds3QQfgLpBX65Rwj2Scgc7cC2dVcxgdMwgdACAQEwZTBcMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRswGQYDVQQDDBJDRkNBIEFDUyBTTTIgT0NBMzECBUCEF1MkMAwGCCqBHM9VAYMRBQAwDQYJKoEcz1UBgi0BBQAERzBFAiEA03ogUebmqNyLjD5/OXr4gSdVQfqp3yqrVVPgRmGPy1QCIBkHrzpSxw/ZPloL+t1GHlEp2rW7qVgy966/lQqE7UVH"; - X509 x509 = api.SYD_Get_X509_CertInfo_HA(testData.getBytes(), sign); - System.out.println("验签结果" + x509); - } - - - public static void case3(SydSDNXApiImpl api) { - - System.out.println("\n\n----- 裸签名 -----"); - String sign = api.nakedSign(testData.getBytes(), testCertNo); - System.out.println("签名结果 " + sign); - } - - public static void case4(SydSDNXApiImpl api) { - - System.out.println("\n\n----- 裸签名 -----"); - String sign = api.nakedSign(testData.getBytes(), testCertNo); - System.out.println("签名结果 " + sign); - //String sign = "dFOUuU+JVNEZO8494MV+xtPuMVhEjnXlilHlymK9Cz/jQ3m+lRKTbv4tfyo5Eb7MM7lqQi6cdwKZ/CLnkOa+Vsye4DDYYSweqsraLwdtrVcc1sw2KDHeJUao2SXIhdhgxSw+puiOCDq/4FsJADdnYprIp+GSLfjj7tuhbBBb0JCV6rnTutIozq2QDPQKEspzMxQ2TtbVQezfL3uMA5GuYNdJYz4eAasQtxTQS5dhe3/CaWbjBeL2kKhsvuMbP6wsx2HeuXvaf99OEBkyXq2fFPJtuU7WB4SIYKN1wI0BK/IMa0ULj1Q1SBakd5+iO8ckrokJJ6E2JH3Nd/mT+5DdRg=="; - - System.out.println("\n\n----- 验签 -----"); - boolean pass = api.SYD_NakedVerify(testData.getBytes(), sign, testUser); - System.out.println("验签结果 " + pass); - } -} diff --git a/src/test/java/com/sunyard/sydapi/test/TestXJ.java b/src/test/java/com/sunyard/sydapi/test/TestXJ.java deleted file mode 100644 index 7dc0181..0000000 --- a/src/test/java/com/sunyard/sydapi/test/TestXJ.java +++ /dev/null @@ -1,457 +0,0 @@ -package com.sunyard.sydapi.test; - -import com.sunyard.RetWrap; -import com.sunyard.SydApi; -import com.sunyard.cert.X509; -import com.sunyard.proto.Util; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import racal.sunyard.main.SydApi4j; - -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.io.IOException; - -/** - * 新疆联通政务云 - */ -public class TestXJ { - - SydApi4j api; - - @Before - public void before() { - // 通过设置debug的属性开启debug,如果不设置则默认不打开 - System.setProperty("com.sunyard.sydapi4j.debug", "true"); - api = (SydApi4j) new SydApi4j().connect("192.168.0.100", 8889, null, 1000); - } - - @After - public void after() { - try { - this.api.disconnect(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - // 测试通过 - // 8003 - @Test - public void testSYD_NakedSign() { - String dn = "C=CN,O=Sunyard,OU=8001,CN=8001"; - byte[] bytes = api.SYD_NakedSign("111".getBytes(), dn); - System.out.println(Util.bytes2HexString(bytes)); - } - - // 测试通过 - // 8004 - @Test - public void testSYD_NakedVerify() { - String dn = "C=CN,O=Sunyard,OU=8001,CN=8001"; - String orgData = "111"; - byte[] bytes = api.SYD_NakedSign(orgData.getBytes(), dn); - String sign = Util.bytes2HexString(bytes); - System.out.println(sign); - - boolean b = api.SYD_NakedVerify(orgData.getBytes(), bytes, dn); - System.out.println(b); - } - - // 测试通过 - // 6C - @Test - public void testNetSign() { - String sn = "1004282451"; - String s = api.netSign(sn, "111".getBytes()); - System.out.println(s); - } - - // 测试通过 - // 6D - @Test - public void testNetVerify() { - String sn = "1004282451"; - String data = "111"; - String s = api.netSign(sn, data.getBytes()); - - boolean b = api.netVerify(sn, data.getBytes(), s); - System.out.println(b); - } - - // 测试通过 - // 80 - @Test - public void testSM2SignCustomized() { - String sn = "1004282452"; - String s = api.SM2SignCustomized(sn, "111".getBytes()); - System.out.println(s); - } - - // 测试通过 - // 81 - @Test - public void testSM2VerifyCustomized() { - String sn = "1004282451"; - String data = "111"; - String s = api.SM2SignCustomized(sn, data.getBytes()); - - boolean b = api.SM2VerifyCustomized(sn, data.getBytes(), s); - System.out.println(b); - } - - // 测试通过 - // 74 - @Test - public void testSM2SignC() { - String userId = "1111111111111113"; - String certNo = "1234567812345678"; - String thisPublicKey = "03420004549B6A1A09A5D0D9432C6829D443F85ED8785340FC1AB14118BB7637830C808F7A888DF0C4F988EA6FF2EE6C76ECD00C4B7CEC92CC8EA365F8EA291041CAB231"; - String thisOrgData = "FFFFFFFFFFFFFFFF"; - - String s = api.SM2SignC(userId, certNo, 1, Util.hexString2Bytes(thisPublicKey), thisOrgData.getBytes()); - System.out.println(s); - } - - // 测试通过 - // 75 - @Test - public void testSM2Verify() { - - String userId = "1111111111111113"; - String certNo = "1234567812345678"; - String thisPublicKey = "03420004549B6A1A09A5D0D9432C6829D443F85ED8785340FC1AB14118BB7637830C808F7A888DF0C4F988EA6FF2EE6C76ECD00C4B7CEC92CC8EA365F8EA291041CAB231"; - String thisOrgData = "FFFFFFFFFFFFFFFF"; - - String s = api.SM2SignC(userId, certNo, 1, Util.hexString2Bytes(thisPublicKey), thisOrgData.getBytes()); - - System.out.println(s); - boolean b = api.SM2Verify(certNo, 1, Util.hexString2Bytes(thisPublicKey), thisOrgData.getBytes(), s); - System.out.println(b); - } - - // 测试通过 - // 8005 - @Test - public void testSYD_DetachedSign() { - - String orgData = "3214312341243214"; - String DN = "C=CN,O=Sunyard,OU=8001,CN=8001"; - String s = api.SYD_DetachedSign(orgData.getBytes(), DN); - System.out.println(s); - } - - // 测试通过 - // 8006 - @Test - public void testSYD_DetachedVerify() { - String orgData = "3214312341243214"; - String DN = "C=CN,O=Sunyard,OU=8001,CN=8001"; - String sign = api.SYD_DetachedSign(orgData.getBytes(), DN); - System.out.println("签名结果" + sign); - - boolean b = api.SYD_DetachedVerify(orgData.getBytes(), sign); - System.out.println("验签结果:" + b); - } - - // 测试通过 - // 8005 - @Test - public void testSm3AndDetachedSign() { - String publicKey = "0342000469DE3847DD6A66DA96DB8F2DCFA32E10E680FF2EF4A592079E7C3A44320BB15084E7CA9782A39B6E28F07C04FE00D68958A2605921E71712D56C1E4435A39FA5"; - String orgData = "FFFFFFFFFFFFFFFF"; - String testCertNo = "C=CN,O=Sunyard,OU=8001,CN=8001"; - - String sign = api.sm3AndDetachedSign(orgData.getBytes(), publicKey, testCertNo); - System.out.println("签名结果: " + sign); - - boolean b = api.sm3AndDetachedVerify(orgData.getBytes(), publicKey, sign); - System.out.println("验签结果:" + b); - } - - - // 测试通过 - // 8005 - @Test - public void testDetachedSign() { - String publicKey = "0342000469DE3847DD6A66DA96DB8F2DCFA32E10E680FF2EF4A592079E7C3A44320BB15084E7CA9782A39B6E28F07C04FE00D68958A2605921E71712D56C1E4435A39FA5"; - String orgData = "FFFFFFFFFFFFFFFF"; - String testCertNo = "C=CN,O=Sunyard,OU=8001,CN=8001"; - - byte[] hash = api.SM3Hash(publicKey, orgData.getBytes()); - - String sign = api.detachedSign( - SydApi.DATA_HASH, - hash, - testCertNo - ); - - System.out.println("\t签名结果: " + sign); - - boolean verify = api.detachedVerify( - SydApi.DATA_HASH, - hash, - sign - ); - - System.out.println("\t验签结果: " + verify); - } - - // 测试通过 - // 72 - @Test - public void testSM2GenSessionKey() { - - String pk="034200041CD47354867E12B9D138F098413C47D42EDEB2AD402EAB431C0C7AC2FE2D6DE9C67273C643C709F2A749188941B7FA7F9FF14F8E7D19316936DB4D4954FF3819"; - - RetWrap retWrap = api.SM2GenSessionKey(pk); - printRetWrap(retWrap); - } - - // 测试通过 - // 73 - @Test - public void testSM2ConfirmSessionKeyC() { - - String userId = "1111111111111147"; - - String pk="0342000422C4FC907E0BEC600C2070D675EFB65EAE3A628260FF5461DD5F8133CF7CF98530EF392D016B6487BA6148E9AC27BDD4E8D7404A310CB09335F50AEF00ADB068"; - - RetWrap retWrap = api.SM2GenSessionKey(pk); - printRetWrap(retWrap); - - String cipherKey = (String) retWrap.get("CipherKey"); - - RetWrap retWrap1 = api.SM2ConfirmSessionKeyC(userId, cipherKey); - printRetWrap(retWrap1); - } - - // 测试通过 - // E0 - @Test - public void testSYMEncryptData() { - String sessionKey = "XF356BCBA3204F6E6F356BCBA3204F6E6"; - String pInData = "1111111111111111"; - - byte[] bytes = api.SYMEncryptData(3,sessionKey, pInData.getBytes()); - byte[] bytes1 = api.SYMDecryptData(3, sessionKey, bytes); - System.out.println(new String(bytes1)); - } - - // 测试通过 - // E0 - @Test - public void testEncDecData() { - - String msg = "1111111111111111111111"; - - String key = "X3C9003C47A13379011733681ABB4A4D0"; - - byte[] bytes = api.SYMEncryptDataCBC(1, key, msg.getBytes()); - - System.out.println("输出为: " + Util.bytes2HexString(bytes)); - - byte[] bytes1 = api.SYMDecryptDataCBC(1, key, bytes); - System.out.println("明文:" + new String(bytes1)); - } - - // 测试通过 - // 6B - @Test - public void testDecryptDE() { - String sn = "1004282452"; - RetWrap retWrap = api.generateDE(sn, (byte) 0x30); - String sessionKey = (String) retWrap.get("SessionKey"); - String CipherKey = (String) retWrap.get("CipherKey"); - String KCV = (String) retWrap.get("KCV"); - - RetWrap retWrap1 = api.decryptDE(sn, CipherKey); - printRetWrap(retWrap1); - } - - // 测试通过 - // 7E - @Test - public void testSYD_SM2_Get_Dn_PublicKey_HA() { - String dn = "C=CN,O=Sunyard,OU=8001,CN=8001"; - String s = api.SYD_SM2_Get_Dn_PublicKey_HA(dn.getBytes(), 0); - System.out.println(s); - } - - // 测试通过 - // 6E - @Test - public void testGetX509SN() { - String dn = "C=CN,ST=ZJ,L=HZ,O=SUNYARD,OU=123456,CN=111"; - String s = api.getX509SN(0, dn.getBytes()); - System.out.println(s); - } - - // 测试通过 - // 7E - @Test - public void testGetDNPublicKey() { - String dn = "C=CN,O=Sunyard,OU=8001,CN=8001"; - String s = api.GetDNPublicKey(0, dn.getBytes()); - System.out.println(s); - } - - // 测试通过 - // QQ - @Test - public void testSM2GetPublicKeyC() { - String userId = "1111111111111117"; - - String s = api.SM2GetPublicKeyC(userId, 0); - System.out.println(s); - } - - // 测试通过 - // 8016 - @Test - public void testGetX509CertInfo() { - - String pCert = "-----BEGIN CERTIFICATE-----\u0007MIIC1jCCAnqgAwIBAgIFQAKAAXQwDAYIKoEcz1UBg3UFADBhMQswCQYDVQQGEwJD\u0007TjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y\u0007aXR5MSAwHgYDVQQDDBdDRkNBIEFDUyBURVNUIFNNMiBPQ0EzMTAeFw0xNzExMTYw\u0007NjU0NDVaFw0yMjExMTYwNjU0NDVaMIGDMQswCQYDVQQGEwJDTjEcMBoGA1UECgwT\u0007Q0ZDQSBURVNUIFNNMiBPQ0EzMTEOMAwGA1UECwwFU0hDUEUxGTAXBgNVBAsMEE9y\u0007Z2FuaXphdGlvbmFsLTExKzApBgNVBAMMIjA1MUDkuIrmtbfnpajmja7kuqTmmJPm\u0007iYBAQUFBQUFBQDgwWTATBgcqhkjOPQIBBggqgRzPVQGCLQNCAARg8D1RBEv9lpOE\u0007Q3SdzdLCQ4fDiE8Ncb2Fl4qIGc12GA/LUS1fgzLZuk0WlgyZDSe+QlQziqkmsXsx\u0007KoTCzqsto4H5MIH2MD8GCCsGAQUFBwEBBDMwMTAvBggrBgEFBQcwAYYjaHR0cDov\u0007L29jc3B0ZXN0LmNmY2EuY29tLmNuOjgwL29jc3AwHwYDVR0jBBgwFoAUBMe8+VkB\u0007aT6MNDYgYhg83ry1uwwwDAYDVR0TAQH/BAIwADA2BgNVHR8ELzAtMCugKaAnhiVo\u0007dHRwOi8vMjEwLjc0LjQyLjMvT0NBMzEvU00yL2NybDEuY3JsMA4GA1UdDwEB/wQE\u0007AwIGwDAdBgNVHQ4EFgQUomdLtdhENYb16pe1LNRlcr4N7b8wHQYDVR0lBBYwFAYI\u0007KwYBBQUHAwIGCCsGAQUFBwMEMAwGCCqBHM9VAYN1BQADSAAwRQIgZpJGhpRKmgfi\u0007Vbdq3UAGW6I3AUMfbWMd6webLQXmCOoCIQDSxTKRb0TfoXepD3VgO9qxCDwSc4yn\u0007WJ2GC3qmr81QBg==\u0007-----END CERTIFICATE-----\u0007"; - X509 x509 = api.GetX509CertInfo(pCert); - - String path = "E:\\work\\sunyard\\证书\\sm2.q\\sm2.q.enc.crt.pem"; - X509 x509_1 = api.GetX509CertInfo(getCertStr(path)); - } - - // 测试通过 - // 8017 - @Test - public void testGetX509CertFileC() { - String userId = "8001"; - - String s = api.GetX509CertFileC(userId, 0); - System.out.println(s); - } - - // 测试通过 - // E2 - @Test - public void testSM2GenKeyPair() { - RetWrap retWrap = api.SM2GenKeyPair(); - printRetWrap(retWrap, true); - } - - // 测试通过 - // QN - @Test - public void testSYD_SM2GenKeyPair() { - RetWrap retWrap = api.SYD_SM2GenKeyPair(); - printRetWrap(retWrap); - } - - // 测试通过 - // 77 - @Test - public void testSM2Encrypt() { - String publicKey = "03420004C51A40A094B6A14500B2980603D68CA263FF1BA238AFB17BB8B791C5F444465A749B68B4584C83E7BEF66DE2446177E14DBE0F32691F54B1636CC73334A1A94D"; - String orgData = "FFFFFFFFFFFFFFFF"; - String s = api.SM2Encrypt(Util.hexString2Bytes(publicKey), orgData.getBytes()); - - System.out.println("encData: " + s); - } - - // 测试通过 - // 78 - @Test - public void testSM2DecryptC() { - String certId = "1111111111111122"; - String publicKey = "0342000469DE3847DD6A66DA96DB8F2DCFA32E10E680FF2EF4A592079E7C3A44320BB15084E7CA9782A39B6E28F07C04FE00D68958A2605921E71712D56C1E4435A39FA5"; - String orgData = "FFFFFFFFFFFFFFFF"; - String s = api.SM2Encrypt(Util.hexString2Bytes(publicKey), orgData.getBytes()); - - byte[] bytes = api.SM2DecryptC(certId, s); - - System.out.println("decData:" + new String(bytes)); - } - - // 测试通过 - // 76 - // 带公钥 - @Test - public void testSM3Hash() { - String publicKey = "0342000469DE3847DD6A66DA96DB8F2DCFA32E10E680FF2EF4A592079E7C3A44320BB15084E7CA9782A39B6E28F07C04FE00D68958A2605921E71712D56C1E4435A39FA5"; - String orgData = "FFFFFFFFFFFFFFFF"; - - byte[] hash = api.SM3Hash(publicKey, orgData.getBytes()); - - System.out.println("hash:" + Util.bytes2HexString(hash)); - } - - // 测试通过 - // 76 - // 不带公钥 - @Test - public void testSM3Hash2() { - String orgData = "FFFFFFFFFFFFFFFF"; - - byte[] hash = api.SM3Hash(orgData.getBytes()); - - System.out.println("hash:" + Util.bytes2HexString(hash)); - } - - // 工具方法 - // ========================================== - - public static void printRetWrap(RetWrap rw) { - printRetWrap(rw, false); - } - - /** - * 输出 - * @param rw - */ - public static void printRetWrap(RetWrap rw, boolean flag) { - for (String s : rw.keySet()) { - - Object o = rw.get(s); - if (o instanceof String) { - System.out.println(s + ":" + o); - } else if (o instanceof byte[]) { - if (flag) { - System.out.println(s + ": " + Util.bytes2HexString((byte[]) o)); - } else { - System.out.println(s + ": " + new String(Util.hexString2Bytes(Util.bytes2HexString((byte[]) o)))); - } - } else { - System.out.println(s + ":" + o); - } - } - } - - // 获取证书 - public String getCertStr(String path) { - - BufferedInputStream bis = null; - try { - bis = new BufferedInputStream(new FileInputStream(path)); - - StringBuilder str = new StringBuilder(); - - int len = 0; - - while ((len = bis.read()) != -1) { - str.append((char) len); - } - - return str.toString(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (bis != null) { - try { - bis.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - return null; - } -} diff --git a/src/test/java/lrapi/lr.java b/src/test/java/lrapi/lr.java new file mode 100644 index 0000000..dab1220 --- /dev/null +++ b/src/test/java/lrapi/lr.java @@ -0,0 +1,14 @@ +package lrapi; + +public class lr { + + public static String AUTO = "AUTO"; + + public static void start_transaction(String t) { + System.out.println("start_transaction" + t); + } + + public static void end_transaction(String t, String type) { + System.out.println("end_transaction" + t); + } +} diff --git a/src/test/java/sample/Sample.java b/src/test/java/sample/Sample.java new file mode 100644 index 0000000..a25022e --- /dev/null +++ b/src/test/java/sample/Sample.java @@ -0,0 +1,54 @@ +package sample; + +import com.sunyard.RetWrap; +import com.sunyard.SydApi; +import com.sunyard.cert.X509; +import com.sunyard.proto.Util; +import racal.sunyard.main.SydApi4j; + +import java.io.UnsupportedEncodingException; + + +/** + * 上清例子 + */ +public class Sample { + + public static void main(String[] args) throws UnsupportedEncodingException { + + // 通过设置debug的属性开启debug,如果不设置则默认不打开 + System.setProperty("com.sunyard.sydapi4j.debug", "true"); + // 单台加密机 + SydApi api = new SydApi4j().connect("192.168.0.200", 8889, null, 1000); + + try { + String dn = "C=CN,O=CFCA OCA1,OU=YCCA,OU=Individual-2,CN=YCCA@黄金交易所@Zhuangj@1"; + byte[] orgData = new byte[2 * 1024 * 1024]; + + // 签名 + String sign = api.attachedSign(orgData, dn); + System.out.println("签名结果: " + sign); + + // 生成数字信封 + RetWrap retWrap = api.generateDEByDn(dn, sign.getBytes()); + byte[] cipherKey = (byte[]) retWrap.get(SydApi.RET_CIPHER_KEY); + System.out.println("数字信封: " + new String(cipherKey)); + + // 解密数字信封 + RetWrap retWrap1 = api.decryptDEByDN(dn, cipherKey); + byte[] oData = (byte[]) retWrap1.get("oData"); + System.out.println("原数据: " + retWrap1.get("oData")); + + // 验签 + RetWrap verify = api.attachedVerifyAndGetAll(oData); + if (verify != null) { + System.out.println("x509公钥: " + Util.bytes2HexString(((X509) verify.get("x509")).getPubKey())); + System.out.println("签名原数据: " + Util.bytes2HexString((byte[]) (verify.get("oData")))); + } + } finally { + if (null != api) { + api.disconnect(); + } + } + } +} diff --git a/增加依赖说明.txt b/增加依赖说明.txt deleted file mode 100644 index 5dcd767..0000000 --- a/增加依赖说明.txt +++ /dev/null @@ -1,8 +0,0 @@ - - -本次新增以下依赖 -bcpkix-jdk15on-1.65.jar - 安全依赖组件 -bcprov-jdk15on-1.65.jar - 安全依赖组件 -hutool-all-5.8.4.M1.jar - 工具组件 - -jar/dependences.xml 所有依赖 Maven 格式说明 diff --git a/说明.txt b/说明.txt index add23db..db3f428 100644 --- a/说明.txt +++ b/说明.txt @@ -3,9 +3,10 @@ sydapi(1.12) 签名验签使用的 jar - jar - sydapi4j.jar SDK 无依赖(依赖外置) - sydapi4j-jar-with-dependencies.jar 依赖内置,用于快速测试 - - dependences.xml 所有依赖 Maven 格式说明 - dependences 所有依赖 - - groovy-all-2.3.2 通信协议支持 - - jcommander-1.30 命令行支持 - - proto-1.0-20220412 通信协议支持 + - groovy-all-2.4.15 通信协议支持 + - proto-1.0-20220804 通信协议支持 - alf4j-api-1.7.10 日志接口 + - bcpkix-jdk15on-1.65.jar - 安全依赖组件 + - bcprov-jdk15on-1.65.jar - 安全依赖组件 + - hutool-all-5.8.4.M1.jar - 工具组件