1 Star 1 Fork 1

user_1512076 / PCNGateway-Java-SDK

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

SDK调用参考

Java语言SDK

框架及秘钥支持

JAVA语言SDK目前支持官网所有的框架和秘钥组合应用的调用

具体如下:

框架 秘钥上传 秘钥托管
secp256r1 secp256k1 SM2 secp256r1 secp256k1 SM2
Fabric 支持 支持 支持 支持
FISCO-BCOS 支持 支持 支持 支持
XuperChain 支持 支持
CITA 支持
  • fabric框架应用使用secp256r1、SM2 秘钥的秘钥托管和秘钥上传两种模式;
  • FISCO-BCOS框架应用使用secp256k1、SM2 秘钥的秘钥托管和秘钥上传两种模式;
  • XuperChain框架应用使用SM2 秘钥的秘钥托管和秘钥上传两种模式;
  • CITA框架应用使用SM2 秘钥的秘钥托管模式;

1. 调用前准备

应用参数

应用参数是用户在参与应用成功之后在应用详情页面获取,或者由本地设置的一些参数,具体包含以下参数

  • 节点网关接口地址: 参与的城市节点的节点网关的调用地址
  • 用户编号: 用户的编号
  • 应用编号: 参与的应用的编号
  • 应用公钥: 用户参与成功之后下载的应用公钥
  • 应用私钥: 托管类型应用再参与成功之后由BSN生成的应用公钥,非托管应用为在参与应用时上传的公钥所对应的私钥
  • Https证书: 调用https网关接口时使用的https证书

2. 准备调用

项目引用

将V1.2.0版本中bsn-sdk-java-jar-with-dependencies.jar引用到项目中

导入sdk包

Fabric 需要引入下面的包

import com.bsnbase.sdk.client.fabric.FabricClient
import com.bsnbase.sdk.entity.config.Config

FISCO-BCOS 需要引入下面的包

import com.bsnbase.sdk.client.fiscobcos.FiscobcosClient
import com.bsnbase.sdk.entity.config.Config

XuperChain 需要引入下面的包

import com.bsnbase.sdk.client.xuperChain.XuperClient
import com.bsnbase.sdk.entity.config.Config

初始化config

可以初始化一个存储所有配置的对象,这些具体的配置信息应当由调用者根据各自的项目配置或者读取之后,在调用时传入,
在config的Init方法中实现了获取一个App基础信息的操作,该操作请不要频繁的调用,该接口将占用您的TPS和流量,可以在项目使用一个静态对象存储config在需要时使用。
其中,应用私钥、节点网关公钥为pem中具体内容, com.bsnbase.sdk.util.common.Common提供根据路径获取内容方法, Common.readLocalFile参数为pem存储目录的绝对路径, Common.readFile参数为pem存储目录的相对路径, 或者直接填入pem内容。 证书存储目录是磁盘的绝对路径。可以通过修改util.keystore中的实现修改子用户证书的存储方式。

	api:="" //节点网关地址
	userCode:="" //用户编号
	appCode :="" //应用编号
	puk :="" //应用应用内容
	prk :="" //应用私钥内容
	mspDir:="" //证书存储目录

初始化Config

使用已经生成的配置对象,调用以下代码可以创建一个Config对象,用来调用节点网关

	Config config = new Config();
	config.setAppCode(appCode );
	config.setUserCode(userCode);
	config.setPrk(prkStr)
	config.setApi(api);
	config.setPuk(pukStr);
	config.setMspDir(cert);
	config.initConfig(config);

调用接口

每一个网关接口已经封装了请求和响应的参数对象,只需要赋值就可直接调用,方法内已经实现了签名和验签的操作。
以下为注册子用户的调用操作,其他类似。

//初始化config。
public void initConfig() throws IOException {
    Config config = new Config();
    config.setAppCode("app0001202004161020152918451");
    config.setUserCode("USER0001202004151958010871292");
    config.setApi("http://192.168.1.43:17502");
    config.setPrk(Common.readFile("cert/private_key.pem"));
    config.setPuk(Common.readFile("cert/public_Key.pem"));
    config.setMspDir("D:/test");
    config.initConfig(config);
}
//调用用户注册接口
public void userRegister() {
    try {
        initConfig(); //这里为示例,实际使用中,值需在程序生命周期内调用一次即可
    } catch (IOException e) {
        e.printStackTrace();
        return ;
    }
    ReqUserRegister register = new ReqUserRegister();
    register.setName("test19");
    register.setSecret("123456");
    try {
        UserService.userRegister(register);
    } catch(GlobalException g) {
        g.printStackTrace();
    }catch (IOException e) {
        e.printStackTrace();
        return;
    }
}

3.一些其他说明

非托管应用的用户身份证书的说明

由于Fabric框架的非托管的应用在调用网关进行交易的时候所需要的用户证书需要用户自己生成,其流程是:注册用户->登记用户证书 。在登记用户证书的操作中,会由本地生成一对秘钥,然后通过秘钥导出证书的CSR文件(证书申请文件),调用用户证书 登记接口获取一个有效的证书,使用该证书才能在通过托管应用交易处理接口中正常的发起交易。 需要注意的是在CSR文件中设置CN时,并不直接是注册的Name,而是由Name和AppCode拼接的名称,格式为Name@AppCode 。 该操作是在KeyEscrowFabrickeyEscrowNoRegister方法中实现的。 而FISCO-BCOS框架的非托管应用在进行交易时只需要在本地生成一对符合框架算法的密钥对即可,无需其他操作。

证书的存储 是通过 util.keystore的方法中实现的,该方法只存储本地文件形式的证书,如果需要其 他形式的证书存储方式。是需要实现具体的接口即可,详细请参考具体的代码。

关于加密

为方便在进行数据交易的上链操作中对数据进行加密解密,SDK中实现了对称加密AESDES和一种非对称加密SM2算法
其中对称加密为AES具体调用如下


		String prk="";//私钥
        String content="";//加密内容
        System.out.println("加密后的密文为:"+AESEncode(encodeRules,content));
        System.out.println("解密后的明文为:"+AESDncode(encodeRules,AESEncode(encodeRules,content)));
    /*
     * 加密
     * 1.构造密钥生成器KeyGenerator
     * 2.根据ecnodeRules规则初始化密钥生成器
     * 3.产生密钥
     * 4.创建和初始化密码器
     * 5.内容加密
     * 6.返回字符串
     */
    public static String AESEncode(String encodeRules,String content){
        try {
            
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
           
            SecretKey original_key=keygen.generateKey();
            byte [] raw=original_key.getEncoded();
           
            SecretKey key=new SecretKeySpec(raw, "AES");
            
            Cipher cipher=Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte [] byte_encode=content.getBytes("utf-8");
            byte [] byte_AES=cipher.doFinal(byte_encode);
            String AES_encode=new String(new BASE64Encoder().encode(byte_AES));
            return AES_encode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 解密
     * 解密过程:
     * 1.同加密1-4步
     * 2.将加密后的字符串反纺成byte[]数组
     * 3.将加密内容解密
     */
    public static String AESDncode(String encodeRules,String content){
        try {
            KeyGenerator keygen=KeyGenerator.getInstance("AES");
            keygen.init(128, new SecureRandom(encodeRules.getBytes()));
            SecretKey original_key=keygen.generateKey();
            byte [] raw=original_key.getEncoded();
            SecretKey key=new SecretKeySpec(raw, "AES");
            Cipher cipher=Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte [] byte_content= new BASE64Decoder().decodeBuffer(content);
            /*
             * 解密
             */
            byte [] byte_decode=cipher.doFinal(byte_content);
            String AES_decode=new String(byte_decode,"utf-8");
            return AES_decode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

非对称加密SM2,具体如下,在该方法中同时实现了SM2的签名和验签

非对称加密中由公钥加密,私钥进行解密

	puk := ``//公钥
	prik := ``//私钥
	String src = "加密字符串";
    System.out.println("原文UTF-8转hex:" + Util.byteToHex(src.getBytes()));
    String SM2Enc = SM2Enc(puk, src);//加密
    String SM2Dec = SM2Dec(prik, SM2Enc);//私钥解密
	

关于秘钥生成

在BSN中,fabric框架的密钥格式为ECDSAsecp256r1曲线,而fisco-bcos框架的密钥格式为SM2 在用户参与非托管应用时需要生成对应格式的密钥并上传。
下面介绍这两种密钥的生成,秘钥的生成是使用openssl生成的,其中SM2秘钥的生成需要openssl1.1.1及以上版本

注:以下命令是在linux环境下执行的

1. ECDSA(secp256r1)的密钥生成
  • 生成私钥
openssl ecparam -name prime256v1 -genkey -out key.pem
  • 导出公钥
openssl ec -in key.pem -pubout -out pub.pem
  • 导出pkcs8格式私钥

由于部分语言中使用pkcs8格式的密钥比较方便,可以使用下面的命令导出pkcs8格式私钥
在本sdk中使用的私钥即为pkcs8格式

openssl pkcs8 -topk8 -inform PEM -in key.pem -outform PEM -nocrypt -out key_pkcs8.pem

通过以上命令可以生成三个文件
key.pem :私钥
pub.pem :公钥
key_pkcs8.pem :pkcs8格式私钥

2. ECDSA(secp256k1)的密钥生成
  • 生成私钥
openssl ecparam -name secp256k1 -genkey -out key.pem
  • 导出公钥
openssl ec -in key.pem -pubout -out pub.pem
  • 导出pkcs8格式私钥

由于部分语言中使用pkcs8格式的密钥比较方便,可以使用下面的命令导出pkcs8格式私钥 在本sdk中使用的私钥即为pkcs8格式

openssl pkcs8 -topk8 -inform PEM -in key.pem -outform PEM -nocrypt -out key_pkcs8.pem

通过以上命令可以生成三个文件 key.pem :私钥 pub.pem :公钥 key_pkcs8.pem :pkcs8格式私钥

3.SM2格式秘钥生成

首先需要检查openssl的版本是否支持SM2格式秘钥生成,可以使用下面的命令

openssl ecparam -list_curves | grep SM2

如果输出以下内容,则表示支持,

SM2       : SM2 curve over a 256 bit prime field

否则需要去官网下载1.1.1或者以上版本, 这是使用的为1.1.1d版本,
官网下载地址:https://www.openssl.org/source/openssl-1.1.1d.tar.gz

  • 生成私钥
openssl ecparam -genkey -name SM2 -out sm2PriKey.pem
  • 导出公钥
openssl ec -in sm2PriKey.pem -pubout -out sm2PubKey.pem
  • 导出pkcs8格式私钥

由于部分语言中使用pkcs8格式的密钥比较方便,可以使用下面的命令导出pkcs8格式私钥
在本sdk中使用的私钥即为pkcs8格式

openssl pkcs8 -topk8 -inform PEM -in sm2PriKey.pem -outform pem -nocrypt -out sm2PriKeyPkcs8.pem

通过以上命令可以生成三个文件
sm2PriKey.pem :私钥
sm2PubKey.pem :公钥
sm2PriKeyPkcs8.pem :pkcs8格式私钥

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

bsn javasdk Github镜像 PCNGateway-Java-SDK https://github.com/BSNDA/PCNGateway-Java-SDK 展开 收起
Java
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/dayudada/pcngateway-java-sdk.git
git@gitee.com:dayudada/pcngateway-java-sdk.git
dayudada
pcngateway-java-sdk
PCNGateway-Java-SDK
master

搜索帮助