Commit a2dec19c by 陶然

init

parents
################################################################################
# 此 .gitignore 文件已由 Microsoft(R) Visual Studio 自动创建。
################################################################################
/.vs
/obj/Debug
/bin/Debug
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Njzj.Bocoms.Openapis
{
internal static class Configs
{
internal static string APIGW_URL_ADDRESS = "https://open.test.bankcomm.com:9443/uat";//"https://117.184.192.242:9443";
/// <summary>
/// APP_ID:通过内管查看详情,可获取对应的组织机构、接入方式、公钥等信息;APP管理中查看
/// </summary>
internal static string APP_ID = "appozhjz202305110002";
/// <summary>
/// 主机构号
/// </summary>
internal static string ORG_ID = "1000078265";
/// <summary>
/// 子机构号
/// </summary>
internal static string SUB_ORG_ID = "1000078266";
/// <summary>
/// MY_PRIVATE_KEY:RSA私钥,可以通过sdk包下面bin文件夹里面的工具生成一对公私钥
/// </summary>
internal static string MY_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDEu3hCLeQXcWmi+wXaaM0HSJkRxFb/lQl8GU69UiRmf0zI4Xh7/cPBXdm/CWS5SzzTRCQJh23/USxPuyB//wWHgkqUASj12B4mMdx+/KGFmgrAFCy4CBhE2+O4AaiKWuZ8Gpmv+NUseNhy/kyzdNrmqikffr1vM7q1emJ8Y9OihGIAB8toT6b9I/iL93yLUXNLe0ELIIJ1+mmr7j0GvAMZQKL2IrfJ4MCRqg0Ioj2Ql1ckrkmIjgMKZQ1ryzrzcllq5YeaOM8fM3gff9Ntn06N2fsbpZFnGzokNpZkBX8wsLwOHBLM25RxvMPWH9UwWBXkklNHe57PN9G7qtvMMOnPAgMBAAECggEAMeTNuhMDbwKfZOs+78Z2gStjTsM5wTYeIrAUbSVg//G3Gpc8RE32kJrpt259chTnxzjX3ubO+dqvX0U5F90onNZpbaHhrn/yHYO1xSrzF/waT96N/NpotUYDOc6J3RTysXTZl2yHO/EmC/v8neK8BZYQOeGdz48SAiaYxa1XpjZ0QAUX3rCjf9qjkTKux0TZTBk67PcIb+Gwqk4nRWhc0i3yXW4Xw8Z8UJeABgtsOZ16Nv95K7jA836sF+gf4chLGDl8J9Y7Ciz/FpJPksa6Ysoo6jMW9WkggGsNEOwTK6SfYWqIER+NozWG5F4jOlAmdc3zlteOdM3Z9kiYHdlsmQKBgQD78RpE3AEFIC6dgO5isbBeSRNZJUHOp/H49cJgwtk3DiDuN/hLh8Lw3priFiOSlioFRmv6VkQVRQJ38pCbXacc04d34joNy0zXVWFtaaZlureRz74tTbi9Dp1x123NIJ/i/jiJLBdrXfmkNaQpyzfsrIC1vrFpaA5RWKcooZrgzQKBgQDH5rUX9q6tcB/UE3zNfJsNE/yw1QFSAIzcKE3vxWifjbURdVJXpvNoXWkTivwxEbhBDpyAhtUngpN+Ac/3ZP88hY21v+AHmgq9/65z++Wbptg9JfPpGti7kA132D76OfaGca3C1kt1A4Kl+177P52Nx9uAWbANEw+02Dd147pFCwKBgAbzT9Y2e5C4opCVzf3LCSKQwYfkDzy0RWio3wPsXDG4og/wW1k6FZavjXZPRgv1OJOMrc3qM1ai4L6OYo7mtoWFEGeuRgu7YBNQt69dCsojrIzJPmXhjwcoMA/D8bOHAuIwQT8HiF3d6dUt5amBgbl1yNc6u4o85Kg52eK1EqDBAoGARmbZNpRZVpnbi8xFMvWEgemdIAYUjfXFpi/Hqv8iZrb4oypnkpkotoPXYtubEAkGlFr6AUX7Qgv5t/IZdS6ruXvruavW0baNu/aVUSHQ7q2nEHoSWfFrjTshkyiknWnWiej1Yl4oexB+bciG3gO8kFdn1d9AYoppCK7xcWJ/kpsCgYEA2se5A7Oa6JsWmpil+kRSyijoynEnC4IGVEIzboYcBxlyxfpHtwS2zOdXkhIpjd2cqg08BGFcSxot8CaxCOBcRJsI+N+3lok6VffaZDRjttr+NdY/qc7OCmVCx1lJlJ2+WL0Zitv1DV84WqUY2XpQOHvvcmGfuEXtyfkxD1rSJUE=";
/// <summary>
/// APIGW_PUBLIC_KEY:网关公钥
/// </summary>
internal static string APIGW_PUBLIC_KEY =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxSJrF8T/5rKB4NnwMjIxUer+ELf1PQXO2GSdZ/fvuQCclOR9tBlNWL4jFOftebeL+bvMVOJ+JHm/aSes1AN8YNIDGiFUpF6aDkSCaLynDdjK/mQTWhSNa2fO0GGO+ywOBTdYUjVjVtzJ48bbyG3NSylf1EdnBWnMpFa8qpXJXR4ELpVpMkPDC+93HBAlxEgUjhcIJlP5VdKIiudsmhE2T07qtpIQSuE5hntXP6X6GKJReCk+yek2QJITvIBq3cHPw8KDsHHCs7MaR81KI3onJRWyqFtTfVYTiKsd9EcYSxv+Gx5MOF8B/P4iJCD8uzx0FrqoB3k5OYGcz4tXs+h+9wIDAQAB";
/// <summary>
/// 1.1 账单核销结果查询
/// </summary>
internal static string WriteOffResultRequestV2 = "/api/iifssmartbooking/writeOffResult/v2";
/// <summary>
/// 1.2 账单查询
/// </summary>
internal static string QueryContractOrderRequestV2 = "/api/iifssmartbooking/queryContractOrder/v2";
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{10E1820E-308D-434E-BA2E-6550B28A5446}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Njzj.Bocoms.Openapis</RootNamespace>
<AssemblyName>Njzj.Biz.Bocoms.Openapis.V4.5</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\k5-njzj\appextend\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="BouncyCastle.Crypto, Version=1.8.8.0, Culture=neutral, PublicKeyToken=0e99375e54769942">
<SpecificVersion>False</SpecificVersion>
<HintPath>Sdk\Dll\BouncyCastle.Crypto.dll</HintPath>
</Reference>
<Reference Include="Kivii.Common.V4.5, Version=5.6.2023.4000, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\k5-njzj\packages\Kivii.Common.5.6.2023.4000\lib\net45\Kivii.Common.V4.5.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Kivii.Core.V4.5, Version=5.6.2023.4140, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\k5-njzj\packages\Kivii.Core.5.6.2023.4140\lib\net45\Kivii.Core.V4.5.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Configs.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Sdk\BizContent.cs" />
<Compile Include="Sdk\BocomApiException.cs" />
<Compile Include="Sdk\BocomDecryptResponse.cs" />
<Compile Include="Sdk\BocomDownloadEncryptRequest.cs" />
<Compile Include="Sdk\BocomDownloadRequest.cs" />
<Compile Include="Sdk\BocomEncrypt.cs" />
<Compile Include="Sdk\BocomEncryptRequest.cs" />
<Compile Include="Sdk\BocomRequest.cs" />
<Compile Include="Sdk\BocomResponse.cs" />
<Compile Include="Sdk\BocomUploadEncryptRequest.cs" />
<Compile Include="Sdk\BocomUploadRequest.cs" />
<Compile Include="Sdk\DefaultBocomClient.cs" />
<Compile Include="Sdk\request\AddContractOrderRequestV2.cs" />
<Compile Include="Sdk\request\BJPTBlCustAccountQueryRequestV1.cs" />
<Compile Include="Sdk\request\FileUploadRequestV1.cs" />
<Compile Include="Sdk\request\HmdLoanStatusListFileDownloadRequestV1.cs" />
<Compile Include="Sdk\request\IntegralExchangeCheckRequestV1.cs" />
<Compile Include="Sdk\request\IntegralExchangeCreateUrlRequestV1.cs" />
<Compile Include="Sdk\request\QueryContractOrderRequestV2.cs" />
<Compile Include="Sdk\request\ScfCreateUrlRequestV1.cs" />
<Compile Include="Sdk\request\WriteOffResultRequestV2.cs" />
<Compile Include="Sdk\response\AddContractOrderResponseV2.cs" />
<Compile Include="Sdk\response\BJPTBlCustAccountQueryResponseV1.cs" />
<Compile Include="Sdk\response\FileDownloadResponseV1.cs" />
<Compile Include="Sdk\response\FileUploadResponseV1.cs" />
<Compile Include="Sdk\response\IntegralExchangeCheckResponseV1.cs" />
<Compile Include="Sdk\response\IntegralExchangeCreateUrlResponseV1.cs" />
<Compile Include="Sdk\response\IntegralExchangeNotifyResponseV1.cs" />
<Compile Include="Sdk\response\QueryContractOrderResponseV2.cs" />
<Compile Include="Sdk\response\ScfCreateUrlResponseV1.cs" />
<Compile Include="Sdk\response\WriteOffResultResponseV2.cs" />
<Compile Include="Sdk\security\crypt\AESCryptor.cs" />
<Compile Include="Sdk\security\crypt\RSACryptor.cs" />
<Compile Include="Sdk\security\crypt\SM2Cryptor.cs" />
<Compile Include="Sdk\security\crypt\SM4Cryptor.cs" />
<Compile Include="Sdk\security\digest\SHA256Digest.cs" />
<Compile Include="Sdk\security\digest\SM3Digest.cs" />
<Compile Include="Sdk\security\keygen\AESKeyGen.cs" />
<Compile Include="Sdk\security\keygen\SM2KeyGen.cs" />
<Compile Include="Sdk\security\keygen\SM4KeyGen.cs" />
<Compile Include="Sdk\security\sign\RSASignature.cs" />
<Compile Include="Sdk\security\sign\SM2Signature.cs" />
<Compile Include="Sdk\utils\ApiUtils.cs" />
<Compile Include="Sdk\utils\BocomConstants.cs" />
<Compile Include="Sdk\utils\BocomHashMap.cs" />
<Compile Include="Sdk\utils\BocomSignature.cs" />
<Compile Include="Sdk\utils\FileItem.cs" />
<Compile Include="Sdk\utils\HttpRequestParamsUtils.cs" />
<Compile Include="Sdk\utils\KeyGeneratorUtils.cs" />
<Compile Include="Sdk\utils\TrustAllCertificatePolicy.cs" />
<Compile Include="Sdk\utils\WebUtils.cs" />
<Compile Include="Transforms\RestfulTest.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Content Include="Sdk\Dll\BouncyCastle.Crypto.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectView>ProjectFiles</ProjectView>
</PropertyGroup>
</Project>
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Njzj.Biz.Bocoms.Openapis.V4.5")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Njzj.Biz.Bocoms.Openapis.V4.5")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("10e1820e-308d-434e-ba2e-6550b28a5446")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
namespace Com.Bocom.OpenApi
{
public interface BizContent
{
}
}
\ No newline at end of file
using System;
namespace Com.Bocom.OpenApi
{
public class BocomApiException : Exception
{
private static long serialVersionUID = 1982151499949623380L;
private int errCode;
private string errMsg;
public BocomApiException()
{
}
public BocomApiException(string message)
{
errMsg = message;
}
public BocomApiException(int errCode, string errMsg)
: base(errCode + ":" + errMsg)
{
this.errCode = errCode;
this.errMsg = errMsg;
}
public BocomApiException(string message, Exception e) : base(message, e)
{
errMsg = message;
}
public BocomApiException(int errCode, String errMsg, Exception e) : base(errCode + ":" + errMsg, e)
{
this.errCode = errCode;
this.errMsg = errMsg;
}
public int GetErrCode()
{
return errCode;
}
public string GetErrMsg()
{
return errMsg;
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
namespace Com.Bocom.OpenApi
{
[Serializable]
[DataContract]
public class BocomDecryptResponse : BocomResponse
{
private string decryptKey;
/**
* @return the decrptKey
*/
public string getDecryptKey()
{
return decryptKey;
}
/**
* @param decrptKey
* the decrptKey to set
*/
public void setDecryptKey(string decryptKey)
{
this.decryptKey = decryptKey;
}
public string decrypt(string data, string encryptType, string key, string charset)
{
return BocomEncrypt.SymmetricalDecrypt(data, encryptType, key, charset);
}
}
}
\ No newline at end of file
namespace Com.Bocom.OpenApi
{
public abstract class BocomDownloadEncryptRequest<T> : BocomRequest<T> where T : BocomResponse
{
private string downloadPath;
private string hashCode;
public string GetDownloadPath()
{
return downloadPath;
}
/// <summary>
///
/// </summary>
/// <param name="downloadPath">the downloadPath to set</param>
public void SetDownloadPath(string downloadPath)
{
this.downloadPath = downloadPath;
}
public abstract string getEncryptKey();
public abstract string getEncryptPolicy();
public string getHashCode()
{
return hashCode;
}
public abstract string GetEncryptType();
public void SetHashCode(string hashCode)
{
this.hashCode = hashCode;
}
}
}
\ No newline at end of file
namespace Com.Bocom.OpenApi
{
public abstract class BocomDownloadRequest<T> : BocomRequest<T> where T : BocomResponse
{
private string downloadPath;
public string GetDownloadPath()
{
return downloadPath;
}
/// <summary>
///
/// </summary>
/// <param name="downloadPath">the downloadPath to set</param>
public void SetDownloadPath(string downloadPath)
{
this.downloadPath = downloadPath;
}
}
}
\ No newline at end of file
using System.IO;
using Com.Bocom.OpenApi.Security.Crypt;
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
public class BocomEncrypt
{
private static RSACryptor.RSAFromPkcs8 rsaCryptor =
new RSACryptor.RSAFromPkcs8();
/// <summary>
/// 对称加密,仅支持AES256和SM4。
/// </summary>
/// <param name="plainText"></param>
/// <param name="encryptType"></param>
/// <param name="secretKey"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string SymmetricalEncrypt(string plainText, string encryptType, string secretKey, string charset)
{
if (BocomConstants.ENCRYPT_TYPE_RSA_AND_AES == encryptType)
{
return AESCryptor.Encrypt(plainText, secretKey, charset);
}
if (BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4 == encryptType)
{
return SM4Cryptor.Encrypt(plainText, secretKey, charset);
}
throw new BocomApiException("对称加密仅支持AES256和SM4!");
}
/// <summary>
/// 对称解密,仅支持AES256和SM4。
/// </summary>
/// <param name="cipherText"></param>
/// <param name="encryptType"></param>
/// <param name="secretKey"></param>
/// <param name="charset"></param>
/// <returns></returns>
/// <exception cref="BocomApiException"></exception>
public static string SymmetricalDecrypt(string cipherText, string encryptType, string secretKey, string charset)
{
if (BocomConstants.ENCRYPT_TYPE_RSA_AND_AES == encryptType)
{
return AESCryptor.Decrypt(cipherText, secretKey, charset);
}
if (BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4 == encryptType)
{
return SM4Cryptor.Decrypt(cipherText, secretKey, charset);
}
throw new BocomApiException("对称解密仅支持AES256和SM4!");
}
/// <summary>
/// 非对称加密,仅支持RSA和SM2。
/// </summary>
/// <param name="plainText"></param>
/// <param name="encryptType"></param>
/// <param name="publicKey"></param>
/// <param name="charset"></param>
/// <returns></returns>
/// <exception cref="BocomApiException"></exception>
public static string AsymmetricalEncrypt(string plainText, string encryptType, string publicKey, string charset)
{
if (BocomConstants.ENCRYPT_TYPE_RSA_AND_AES == encryptType)
{
return rsaCryptor.EncryptData(plainText, publicKey, charset);
}
if (BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4 == encryptType)
{
return SM2Cryptor.Encrypt(plainText, publicKey, charset);
}
throw new BocomApiException("非对称加密仅支持RSA和SM2!");
}
/// <summary>
///
/// </summary>
/// <param name="cipherText"></param>
/// <param name="encryptType"></param>
/// <param name="privateKey"></param>
/// <param name="charset"></param>
/// <returns></returns>
public static string AsymmetricalDecrypt(string cipherText, string encryptType, string privateKey,
string charset)
{
if (BocomConstants.ENCRYPT_TYPE_RSA_AND_AES == encryptType)
{
return rsaCryptor.DecryptData(cipherText, privateKey, charset);
}
if (BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4 == encryptType)
{
return SM2Cryptor.Decrypt(cipherText, privateKey, charset);
}
throw new BocomApiException("非对称解密仅支持RSA和SM2!");
}
public static byte[] EncryptFile(FileStream fi, string cryptKey, string encryptType)
{
if (BocomConstants.ENCRYPT_TYPE_RSA_AND_AES == encryptType)
{
return AESCryptor.EncryptFile(fi, cryptKey);
}
if (BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4 == encryptType)
{
// SM2加密(缺省)
return null;
}
return null;
}
public static byte[] DecryptFile(FileStream fi, string cryptKey, string encryptType)
{
if (BocomConstants.ENCRYPT_TYPE_RSA_AND_AES == encryptType)
{
return AESCryptor.DecryptFile(fi, cryptKey);
}
if (BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4 == encryptType)
{
// SM2加密(缺省)
return null;
}
return null;
}
}
}
\ No newline at end of file
namespace Com.Bocom.OpenApi
{
public abstract class BocomEncryptRequest<T> : BocomRequest<T> where T : BocomResponse
{
public abstract string GetEncryptPolicy();
public abstract string Encrypt(string data, string key, string encryptType);
public abstract string GetEncryptKey();
public abstract string GetEncryptType();
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
namespace Com.Bocom.OpenApi
{
public abstract class BocomRequest<T> where T : BocomResponse
{
private string serviceUrl;
public string GetServiceUrl()
{
return serviceUrl;
}
public void SetServiceUrl(string value)
{
serviceUrl = value;
}
private BizContent bizContent;
public BizContent GetBizContent()
{
return bizContent;
}
public void SetBizContent(BizContent value)
{
bizContent = value;
}
private Dictionary<string, string> extraParams = new Dictionary<string, string>();
public Dictionary<string, string> GetExtraParams()
{
return extraParams;
}
public abstract Type GetResponseClass();
public abstract bool IsNeedEncrypt();
public abstract Type GetBizContentClass();
//abstract public Dictionary<string, string> getExtraParameters();
/**
* @return POST or GET
*/
public abstract string GetMethod();
// abstract public string getEncrpytKey();
// abstract public string getEncrpytPolicy();
// abstract public FileItem getFileItem();
// abstract public void setHashCode(string hashCode);
// abstract public string getDownloadPath();
// abstract public string getEncrpytType();
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
namespace Com.Bocom.OpenApi
{
[Serializable]
[DataContract]
public class BocomResponse
{
[DataMember] private string biz_state = "P";
[DataMember] private string rsp_code = "";
[DataMember] private string rsp_msg = "";
[DataMember] private string ref_msg_id;
public string GetRefMsgId()
{
return ref_msg_id;
}
public void SetRefMsgId(string value)
{
ref_msg_id = value;
}
public string GetRspCode()
{
return rsp_code;
}
public void SetRspCode(string value)
{
rsp_code = value;
}
public string GetRspMsg()
{
return rsp_msg;
}
public void SetRspMsg(string value)
{
rsp_msg = value;
}
/**
* @return 报文成功级别标识;非业务级别成功标识
*/
public bool IsSuccess()
{
return biz_state.Equals("S");
}
public string GetBizState()
{
return biz_state;
}
public void SetBizState(string state)
{
biz_state = state;
}
}
}
\ No newline at end of file
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
public abstract class BocomUploadEncryptRequest<T> : BocomRequest<T> where T : BocomResponse
{
public abstract FileItem GetFileItem();
public abstract string GetEncryptKey();
public abstract string GetEncryptPolicy();
public abstract string GetEncryptType();
}
}
\ No newline at end of file
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
public abstract class BocomUploadRequest<T> : BocomRequest<T> where T : BocomResponse
{
public abstract FileItem GetFileItem();
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Njzj.Bocoms.Openapis.Sdk.request
{
internal class AddContractOrderRequestV2
{
}
}
using System;
using System.Runtime.Serialization;
using Com.Bocom.OpenApi.Response;
using Com.Bocom.OpenApi.Security.KeyGen;
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
namespace Request
{
public class BJPTBlCustAccountQueryRequestV1 : BocomEncryptRequest<BJPTBlCustAccountQueryResponseV1>
{
private string encryptType = BocomConstants.ENCRYPT_TYPE_RSA_AND_AES;
private string encryptKey = AESKeyGen.GenAES256Key();
public override Type GetResponseClass()
{
return typeof(BJPTBlCustAccountQueryResponseV1);
}
public override bool IsNeedEncrypt()
{
return true;
}
public override string GetMethod()
{
return "POST";
}
public override Type GetBizContentClass()
{
return typeof(BlCustAccountQueryRequestV1Biz);
}
[DataContract]
public class BlCustAccountQueryRequestV1Biz : BizContent
{
[DataMember]
public string req_usercode { get; set; }
[DataMember]
public string field1 { get; set; }
[DataMember]
public string cust_idno { get; set; }
[DataMember]
public string balance_account { get; set; }
[DataMember]
public string cust_erpid { get; set; }
[DataMember]
public string field2 { get; set; }
}
public override string GetEncryptPolicy()
{
return BocomConstants.ENCRYPT_POLICY_TYPE_CONTENT;
}
public override string GetEncryptType()
{
return encryptType;
}
public void setEncryptType(string encryptType)
{
if (encryptType.Equals(BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4))
{
this.encryptType = encryptType;
encryptKey = SM4KeyGen.GenSM4Key();
}
}
public override string Encrypt(string data, string key, string encryptType)
{
string cipher;
try
{
cipher = BocomEncrypt.SymmetricalEncrypt(data, encryptType, key, BocomConstants.CHARSET_UTF8);
}
catch (Exception e)
{
throw new Exception("加密字符串[" + data + "]时遇到异常", e);
}
return cipher;
}
public override string GetEncryptKey()
{
return encryptKey;
}
}
}
}
\ No newline at end of file
using System;
using Com.Bocom.OpenApi.Response;
using Com.Bocom.OpenApi.Security.KeyGen;
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
namespace Request
{
public class FileUploadRequestV1 : BocomUploadEncryptRequest<FileUploadResponseV1>
{
/// <summary>
/// 获取响应类
/// </summary>
/// <returns>返回IntegralExchangeCheckResponseV1类对应的响应类类型</returns>
public override Type GetResponseClass()
{
return typeof(FileUploadResponseV1);
}
/// <summary>
/// 是否支持加密(目前sdk只支持对字段进行AES加解密)
/// </summary>
/// <returns>一般返回false</returns>
public override bool IsNeedEncrypt()
{
return true;
}
/// <summary>
/// http发起请求方式(支持GET、POST两种方式)
/// </summary>
/// <returns>一般返回POST</returns>
public override string GetMethod()
{
return "POST";
}
private FileItem fileItem;
public void setFileItem(FileItem f)
{
fileItem = f;
}
public override string GetEncryptType()
{
return BocomConstants.ENCRYPT_TYPE_RSA_AND_AES;
}
public override string GetEncryptPolicy()
{
return BocomConstants.ENCRYPT_POLICY_TYPE_FILE;
}
private string encryptKey = AESKeyGen.GenAES256Key();
public override string GetEncryptKey()
{
return encryptKey;
}
public override FileItem GetFileItem()
{
return fileItem;
}
/// <summary>
/// 获取业务类类型
/// </summary>
/// <returns>返回request类内部定义的BizContent类的类型</returns>
public override Type GetBizContentClass()
{
return null;
}
/* [DataMember]
private FileItem fileItem;
public FileItem FileItem
{
get { return fileItem; }
// set { protocol_no = value; }
}*/
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
using Com.Bocom.OpenApi.Response;
using Com.Bocom.OpenApi.Security.KeyGen;
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
namespace Request
{
public class HmdLoanStatusListFileDownloadRequestV1 : BocomDownloadEncryptRequest<FileDownloadResponseV1>
{
private string encryptKey = AESKeyGen.GenAES256Key();
private string encryptPolicy = "FILE";
private string hashCode;
private string encryptType = "AES";
public override bool IsNeedEncrypt()
{
return true;
}
public override string GetMethod()
{
return "POST";
}
public override Type GetResponseClass()
{
return typeof(FileDownloadResponseV1);
}
public override Type GetBizContentClass()
{
return typeof(HmdLoanStatusListFileDownloadRequestV1Biz);
}
[DataContract]
public class HmdLoanStatusListFileDownloadRequestV1Biz : BizContent
{
//(desc = "联盟商标识")
//@JsonProperty("bv_ode_no")
[DataMember]
public string bv_ode_no { get; set; }
[DataMember]
public string clc_no { get; set; }
//(desc = "备用字段1")
//@JsonProperty("query_date")
[DataMember]
public string query_date { get; set; }
//(desc = "备用字段2")
//@JsonProperty("notify_url")
[DataMember]
public string notify_url { get; set; }
}
public override string getEncryptKey()
{
// TODO Auto-generated method stub
return encryptKey;
}
public override string getEncryptPolicy()
{
// TODO Auto-generated method stub
return encryptPolicy;
}
public string getHashCode()
{
// TODO Auto-generated method stub
return hashCode;
}
public void setHashCode(string hashCode)
{
// TODO Auto-generated method stub
this.hashCode = hashCode;
}
public void setEncryptType(string encryptType)
{
if (encryptType.Equals(BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4))
{
this.encryptType = encryptType;
encryptKey = SM4KeyGen.GenSM4Key();
}
}
public override string GetEncryptType()
{
return encryptType;
}
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
using Com.Bocom.OpenApi.Response;
using Org.BouncyCastle.Bcpg.OpenPgp;
namespace Com.Bocom.OpenApi
{
namespace Request
{
public class IntegralExchangeCheckRequestV1 : BocomRequest<IntegralExchangeCheckResponseV1>
{
/// <summary>
/// 获取响应类
/// </summary>
/// <returns>返回IntegralExchangeCheckResponseV1类对应的响应类类型</returns>
public override Type GetResponseClass()
{
return typeof(IntegralExchangeCheckResponseV1);
}
/// <summary>
/// 是否支持加密(目前sdk只支持对字段进行AES加解密)
/// </summary>
/// <returns>一般返回false</returns>
public override bool IsNeedEncrypt()
{
return false;
}
/// <summary>
/// http发起请求方式(支持GET、POST两种方式)
/// </summary>
/// <returns>一般返回POST</returns>
public override string GetMethod()
{
return "POST";
}
/// <summary>
/// 获取业务类类型
/// </summary>
/// <returns>返回request类内部定义的BizContent类的类型</returns>
public override Type GetBizContentClass()
{
return typeof(IntegralExchangeCheckRequestV1Biz);
}
/// <summary>
/// 内部业务类,封装需要发送给服务端的业务字段
/// </summary>
[DataContract]
public class IntegralExchangeCheckRequestV1Biz : BizContent
{
[DataMember] public string req_usercode { get; set; }
[DataMember] public string doc_id { get; set; }
[DataMember] public string file_name { get; set; }
}
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
using Com.Bocom.OpenApi.Response;
namespace Com.Bocom.OpenApi
{
namespace Request
{
public class IntegralExchangeCreateUrlRequestV1 : BocomRequest<IntegralExchangeCreateUrlResponseV1>
{
/// <summary>
/// 获取响应类
/// </summary>
/// <returns>返回IntegralExchangeCreateUrlRequestV1类对应的响应类类型</returns>
public override Type GetResponseClass()
{
return typeof(IntegralExchangeCreateUrlResponseV1);
}
/// <summary>
/// 是否支持加密(目前sdk只支持对字段进行AES加解密)
/// </summary>
/// <returns>一般返回false</returns>
public override Boolean IsNeedEncrypt()
{
return false;
}
/// <summary>
/// http发起请求方式(支持GET、POST两种方式)
/// </summary>
/// <returns>一般返回POST</returns>
public override string GetMethod()
{
return "POST";
}
/// <summary>
/// 获取业务类类型
/// </summary>
/// <returns>返回request类内部定义的BizContent类的类型</returns>
public override Type GetBizContentClass()
{
return typeof(IntegralExchangeCreateUrlRequestV1Biz);
}
/// <summary>
/// 内部业务类,封装需要发送给服务端的业务字段
/// </summary>
[DataContract]
public class IntegralExchangeCreateUrlRequestV1Biz : BizContent
{
//回调地址url
[DataMember]
public string notify_url { get; set; }
//页面UAL
[DataMember]
public string return_url { get; set; }
//订单编号
[DataMember]
public string order_no { get; set; }
//兑换规则
[DataMember]
public string exchange_rules { get; set; }
//协议编号
[DataMember]
public string protocol_no { get; set; }
}
}
}
}
\ No newline at end of file
using Com.Bocom.OpenApi.Response;
using Com.Bocom.OpenApi.Security.KeyGen;
using Com.Bocom.OpenApi.Utils;
using Kivii.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Com.Bocom.OpenApi
{
public class QueryContractOrderRequestV2 : BocomRequest<QueryContractOrderResponseV2>
{
/// <summary>
/// 获取响应类
/// </summary>
/// <returns>返回QueryContractOrderResponseV2类对应的响应类类型</returns>
public override Type GetResponseClass()
{
return typeof(QueryContractOrderResponseV2);
}
/// <summary>
/// 是否支持加密(目前sdk只支持对字段进行AES加解密)
/// </summary>
/// <returns>一般返回false</returns>
public override bool IsNeedEncrypt()
{
return false;
}
/// <summary>
/// http发起请求方式(支持GET、POST两种方式)
/// </summary>
/// <returns>一般返回POST</returns>
public override string GetMethod()
{
return "POST";
}
public override Type GetBizContentClass()
{
return typeof(QueryContractOrderRequestV2Biz);
}
[DataContract]
public class QueryContractOrderRequestV2Biz : BizContent
{
/// <summary>
/// 机构编号 </summary>
[DataMember]
internal string org_id;
/// <summary>
/// 账单编号 </summary>
[DataMember]
internal string bill_id;
public string getOrgId()
{
return org_id;
}
public void setOrgId(string orgId)
{
this.org_id = orgId;
}
public string getBillId()
{
return bill_id;
}
public void setBillId(string billId)
{
this.bill_id = billId;
}
}
}
}
using System;
using System.Runtime.Serialization;
using Com.Bocom.OpenApi.Response;
using Com.Bocom.OpenApi.Security.KeyGen;
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
namespace Request
{
public class ScfCreateUrlRequestV1 : BocomEncryptRequest<ScfCreateUrlResponseV1>
{
private string encryptType = BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4;
private string encryptKey = SM4KeyGen.GenSM4Key();
public override Type GetResponseClass()
{
return typeof(ScfCreateUrlResponseV1);
}
public override bool IsNeedEncrypt()
{
return true;
}
public override string GetMethod()
{
return "POST";
}
public override Type GetBizContentClass()
{
return typeof(ScfCreateUrlRequestV1Biz);
}
[DataContract]
public class ScfCreateUrlRequestV1Biz : BizContent
{
[DataMember]
public string com_no { get; set; }
}
public override string GetEncryptPolicy()
{
// TODO Auto-generated method stub
return "FIELD";
}
public override string GetEncryptType()
{
// TODO Auto-generated method stub
return encryptType;
}
public override string Encrypt(string data, string key, string encryptType)
{
string cipher;
try
{
cipher = BocomEncrypt.SymmetricalEncrypt(data, encryptType, key, BocomConstants.CHARSET_UTF8);
}
catch (Exception e)
{
throw new Exception("加密字符串[" + data + "]时遇到异常", e);
}
return cipher;
}
public override string GetEncryptKey()
{
return encryptKey;
}
}
}
}
\ No newline at end of file
using Com.Bocom.OpenApi;
using Kivii.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Com.Bocom.OpenApi.QueryContractOrderRequestV2;
namespace Com.Bocom.OpenApi
{
public class WriteOffResultRequestV2 : BocomRequest<WriteOffResultResponseV2>
{
/// <summary>
/// 获取响应类
/// </summary>
/// <returns>返回WriteOffResultResponseV2类对应的响应类类型</returns>
public override Type GetResponseClass()
{
return typeof(WriteOffResultResponseV2);
}
/// <summary>
/// 是否支持加密(目前sdk只支持对字段进行AES加解密)
/// </summary>
/// <returns>一般返回false</returns>
public override bool IsNeedEncrypt()
{
return false;
}
/// <summary>
/// http发起请求方式(支持GET、POST两种方式)
/// </summary>
/// <returns>一般返回POST</returns>
public override string GetMethod()
{
return "POST";
}
public override Type GetBizContentClass()
{
return typeof(WriteOffResultRequestV2Biz);
}
public class WriteOffResultRequestV2Biz : BizContent
{
/// <summary>
/// 机构编号 </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @JsonProperty("org_id") private String orgId;
[Alias("org_id")]
public string orgId { get; set; }
/// <summary>
/// 子机构编号 </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @JsonProperty("sub_org_id") private String subOrgId;
//internal string subOrgId;
[Alias("sub_org_id")]
public string subOrgId { get; set; }
/// <summary>
/// 核销日期 </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @JsonProperty("write_off_dte") private String writeOffDte;
//internal string writeOffDte;
[Alias("write_off_dte")]
public string writeOffDte { get; set; }
/// <summary>
/// 核销编号 </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @JsonProperty("write_off_no") private String writeOffNo;
//internal string writeOffNo;
[Alias("write_off_no")]
public string writeOffNo { get; set; }
/// <summary>
/// 页数 </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @JsonProperty("pageablerequest_pagenum") private String pageablerequestPagenum;
//internal string pageablerequestPagenum;
[Alias("pageablerequest_pagenum")]
public string pageablerequestPagenum { get; set; }
/// <summary>
/// 每页显示数据数 </summary>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @JsonProperty("pageablerequest_pagesize") private String pageablerequestPagesize;
//internal string pageablerequestPagesize;
[Alias("pageablerequest_pagesize")]
public string pageablerequestPagesize { get; set; }
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Njzj.Bocoms.Openapis.Sdk.response
{
internal class AddContractOrderResponseV2
{
}
}
using System.Runtime.Serialization;
namespace Com.Bocom.OpenApi
{
namespace Response
{
[DataContract]
public class BJPTBlCustAccountQueryResponseV1 : BocomDecryptResponse
{
//(desc="备用1")
[DataMember]
public string field1 { get; set; }
//(desc="客户组织机构代码")
[DataMember]
public string cust_id_no { get; set; }
//(desc="客户平台编号")
[DataMember]
public string cust_erp_id { get; set; }
//(desc="借款人结算账户状态")
[DataMember]
public string balance_account_state { get; set; }
//(desc="备用2")
[DataMember]
public string field2 { get; set; }
public string ToString()
{
return "BJPTBlCustAccountQueryResponseV1 [field1=" + field1 + ", custIdno=" + cust_id_no +
", custErpid="
+ cust_erp_id + ", balanceAccountState=" + balance_account_state + ", field2=" + field2 + "]";
}
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
using System.IO;
using Com.Bocom.OpenApi.Security.Digest;
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
namespace Response
{
[Serializable]
[DataContract]
public class FileDownloadResponseV1 : BocomResponse
{
private string filePath;
[DataMember]
public string file_name { get; set; }
[DataMember]
public string file_hashcode { get; set; }
public string GetFilePath()
{
return filePath;
}
public void SetFilePath(string filePath)
{
this.filePath = filePath;
}
public bool isSuccess()
{
if (!IsSuccess())
{
return false;
}
if (!filePath.EndsWith("/") || !filePath.EndsWith("\\"))
{
filePath = filePath + "/";
}
string tempFileName = file_name + ".TMP";
FileItem file = new FileItem(filePath + tempFileName);
try
{
string fileHashcode = SHA256Digest.Digest(filePath + this.file_name);
if (!fileHashcode.Equals(file_hashcode))
{
File.Delete(filePath + file_name);
throw new Exception("Bocom fileHashCode digest not passed.");
}
File.Delete(filePath + tempFileName);
return true;
}
catch (Exception e)
{
throw new Exception("文件重命名失败", e);
}
}
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
namespace Com.Bocom.OpenApi
{
namespace Response
{
[Serializable]
[DataContract]
public class FileUploadResponseV1 : BocomResponse
{
[DataMember]
public string document_id { get; set; }
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
namespace Com.Bocom.OpenApi
{
namespace Response
{
[Serializable]
[DataContract]
public class IntegralExchangeCheckResponseV1 : BocomResponse
{
//订单编号
[DataMember]
public string order_no { get; set; }
//兑换规则 =兑换金额:信用卡积分
[DataMember]
public string exchange_rules { get; set; }
//所用积分
[DataMember]
public string credit_card_points { get; set; }
//换领ISA积分
[DataMember]
public string isa_points { get; set; }
//交易时间
[DataMember]
public string date { get; set; }
//信用卡号
[DataMember]
public string card_no { get; set; }
//交行交易编号
[DataMember]
public string trade_no { get; set; }
//成功标志
[DataMember]
public string flag { get; set; }
public override string ToString()
{
return "order_no: " + order_no + " " + "exchange_rules: " + exchange_rules + " "
+ "credit_card_points: " + credit_card_points + " " + "isa_points: " + isa_points + " "
+ "card_no: " + card_no + " " + "date: " + date + " " + "trade_no: " + trade_no + " "
+ "flag: " + flag + " ";
}
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
namespace Com.Bocom.OpenApi
{
namespace Response
{
[Serializable]
[DataContract]
public class IntegralExchangeCreateUrlResponseV1 : BocomResponse
{
private string decryptKey;
/**
* @return the decrptKey
*/
public string GetDecryptKey()
{
return decryptKey;
}
/**
* @param decrptKey
* the decrptKey to set
*/
public void SetDecryptKey(string decryptKey)
{
this.decryptKey = decryptKey;
}
public string Decrypt(string data, string encryptType, string key, string charset)
{
return BocomEncrypt.SymmetricalDecrypt(data, encryptType, key, charset);
}
//H5页面地址
[DataMember]
public string url { get; set; }
public override string ToString()
{
return "url: " + url + " ";
}
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
namespace Com.Bocom.OpenApi
{
namespace Response
{
[Serializable]
[DataContract]
public class IntegralExchangeNotifyResponseV1 : BocomResponse
{
//订单编号
[DataMember]
public string order_no { get; set; }
//兑换规则 =兑换金额:信用卡积分
[DataMember]
public string exchange_rules { get; set; }
//所用积分
[DataMember]
public string credit_card_points { get; set; }
//换领ISA积分
[DataMember]
public string isa_points { get; set; }
//交易时间
[DataMember]
public string date { get; set; }
//成功标志
[DataMember]
public string flag { get; set; }
//信用卡号
[DataMember]
public string card_no { get; set; }
//交行交易编号
[DataMember]
public string trade_no { get; set; }
//回调地址url
[DataMember]
public string notify_url { get; set; }
//回调地址url
[DataMember]
public string protocol_no { get; set; }
public override string ToString()
{
return "order_no: " + order_no + " " + "exchange_rules: " + exchange_rules + " "
+ "credit_card_points: " + credit_card_points + " " + "isa_points: " + isa_points + " "
+ "card_no: " + card_no + " " + "date: " + date + " " + "flag: " + flag + " "
+ "trade_no: " + trade_no + " " + "notify_url: " + notify_url + " "
+ "protocol_no: " + protocol_no + " ";
}
}
}
}
\ No newline at end of file
using System;
using System.Runtime.Serialization;
namespace Com.Bocom.OpenApi
{
namespace Response
{
[Serializable]
[DataContract]
public class ScfCreateUrlResponseV1 : BocomDecryptResponse
{
/** 二维码 **/
[DataMember]
public string url { get; set; }
public string ToString()
{
return "ScfCreateUrlResponseV1 [url=" + url + "]";
}
}
}
}
\ No newline at end of file
using System;
using System.Linq;
using System.IO;
using System.Text;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Engines;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace Crypt
{
public class AESCryptor
{
/**
* @param sourceContent
* @param cryptKey
* @param charset
* @return
*/
public static string Encrypt(string sourceContent, string cryptKey, string charset)
{
Console.WriteLine(cryptKey);
Console.WriteLine(cryptKey.Length);
KeyParameter kp = new KeyParameter(Convert.FromBase64String(cryptKey));
byte[] bytes;
bytes = Encoding.GetEncoding(charset).GetBytes(sourceContent);
CbcBlockCipher aes = new CbcBlockCipher(new AesEngine());
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new Pkcs7Padding());
cipher.Init(true, kp);
byte[] output = new byte[cipher.GetOutputSize(bytes.Length)];
int len = cipher.ProcessBytes(bytes, 0, bytes.Length, output, 0);
cipher.DoFinal(output, len);
return Convert.ToBase64String(output);
}
/**
* @param content
* @param aesKey
* @return
*/
public static byte[] Encrypt(byte[] content, string aesKey, string charset)
{
KeyParameter kp = new KeyParameter(Convert.FromBase64String(aesKey));
CbcBlockCipher aes = new CbcBlockCipher(new AesEngine());
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new Pkcs7Padding());
cipher.Init(true, kp);
byte[] output = new byte[cipher.GetOutputSize(content.Length)];
int len = cipher.ProcessBytes(content, 0, content.Length, output, 0);
cipher.DoFinal(output, len);
return Encoding.GetEncoding(charset).GetBytes(Convert.ToBase64String(output));
}
/**
* @param encryptContent
* @param cryptKey
* @param charset
* @return
*/
public static string Decrypt(string encryptContent, string cryptKey, string charset)
{
try
{
KeyParameter kp = new KeyParameter(Convert.FromBase64String(cryptKey));
Console.WriteLine("encryptContent : " + encryptContent);
byte[] bytes = Convert.FromBase64String(encryptContent);
CbcBlockCipher aes = new CbcBlockCipher(new AesEngine());
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new Pkcs7Padding());
cipher.Init(false, kp);
byte[] output = new byte[cipher.GetOutputSize(bytes.Length)];
int len = cipher.ProcessBytes(bytes, 0, bytes.Length, output, 0);
int len2;
len2 = cipher.DoFinal(output, len);
byte[] rawData = new byte[len + len2];
Array.Copy(output, 0, rawData, 0, rawData.Length);
string plainData = Encoding.UTF8.GetString(rawData, 0, rawData.Length);
return plainData;
}
catch (Exception e)
{
throw e;
}
}
/**
* @param content
* @param aesKey
* @param charset
* @return
*/
public static byte[] Decrypt(byte[] content, string aesKey, string charset)
{
try
{
KeyParameter kp = new KeyParameter(Convert.FromBase64String(aesKey));
CbcBlockCipher aes = new CbcBlockCipher(new AesEngine());
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new Pkcs7Padding());
cipher.Init(false, kp);
byte[] output = new byte[cipher.GetOutputSize(content.Length)];
int len = cipher.ProcessBytes(content, 0, content.Length, output, 0);
int len2;
len2 = cipher.DoFinal(output, len);
byte[] rawData = new byte[len + len2];
rawData = (byte[]) output.Take(rawData.Length);
string plainData = Encoding.UTF8.GetString(rawData, 0, rawData.Length);
return Encoding.GetEncoding(charset).GetBytes(plainData);
}
catch (Exception e)
{
Console.WriteLine("解密错误,错误信息为:" + e.Message);
}
return null;
}
/**
* @param in
* @param cryptKey
* @return
*/
public static byte[] EncryptFile(Stream fi, string cryptKey)
{
KeyParameter kp = new KeyParameter(Convert.FromBase64String(cryptKey));
byte[] bytes = ToByteArray(fi);
CbcBlockCipher aes = new CbcBlockCipher(new AesEngine());
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new Pkcs7Padding());
cipher.Init(true, kp);
byte[] output = new byte[cipher.GetOutputSize(bytes.Length)];
int len = cipher.ProcessBytes(bytes, 0, bytes.Length, output, 0);
cipher.DoFinal(output, len);
fi.Close();
return output;
}
public static byte[] DecryptFile(Stream fi, string cryptKey)
{
KeyParameter kp = new KeyParameter(Convert.FromBase64String(cryptKey));
byte[] bytes = ToByteArray(fi);
CbcBlockCipher aes = new CbcBlockCipher(new AesEngine());
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new Pkcs7Padding());
cipher.Init(false, kp);
byte[] output = new byte[cipher.GetOutputSize(bytes.Length)];
int len = cipher.ProcessBytes(bytes, 0, bytes.Length, output, 0);
int len2 = cipher.DoFinal(output, len);
byte[] rawData = new byte[len + len2];
Array.Copy(output, 0, rawData, 0, rawData.Length);
return rawData;
}
private static byte[] ToByteArray(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
stream.Close();
return bytes;
}
}
}
}
}
\ No newline at end of file
using System;
using System.Text;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Com.Bocom.OpenApi.Security.KeyGen;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace Crypt
{
public class SM2Cryptor
{
public static string Encrypt(string data, string publicKey, string charset)
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(true,
new ParametersWithRandom(SM2KeyGen.GetECPublicKey(publicKey), new SecureRandom()));
byte[] dataByteArray = Encoding.GetEncoding(charset).GetBytes(data);
return Convert.ToBase64String(sm2Engine.ProcessBlock(dataByteArray, 0, dataByteArray.Length));
}
public static string Decrypt(string encryptedData, string privateKey, string charset)
{
SM2Engine sm2Engine = new SM2Engine();
sm2Engine.Init(false, SM2KeyGen.GetECPrivateKey(privateKey));
byte[] encryptedDataByteArray = Convert.FromBase64String(encryptedData);
return Encoding.GetEncoding(charset).GetString(sm2Engine.ProcessBlock(encryptedDataByteArray, 0,
encryptedDataByteArray.Length));
}
public static void Main(string[] args)
{
string data = "bocom-fobp-zhaozheyang";
//AsymmetricCipherKeyPair keyPair = SM2KeyGen.GenSM2KeyPair();
//string pubKey = SM2KeyGen.GetPublicKeyStr(keyPair);
//string priKey = SM2KeyGen.GetPrivateKeyStr(keyPair);
string pubKey = "02e4c86e0a58a130d3d4c82e7771304e4ba05f9d86c91b044b735d57702122bf12";
string priKey = "009001b7caa52bcc67694b9fdd96d06685878457a97db991a787c51ac0c12eebe7";
string encrypted = SM2Cryptor.Encrypt(data, pubKey, "UTF-8");
Console.WriteLine("密文:" + encrypted);
Console.WriteLine("明文:" + SM2Cryptor.Decrypt(encrypted, priKey, "UTF-8"));
}
}
}
}
}
\ No newline at end of file
using System;
using System.Text;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace Crypt
{
public class SM4Cryptor
{
public static string Encrypt(string data, string secretKey, string charset)
{
KeyParameter keyParameter = new KeyParameter(Convert.FromBase64String(secretKey));
byte[] dataByteArray = Encoding.GetEncoding(charset).GetBytes(data);
// 生成SM4加密器,CBC模式,PKCS7填充
CbcBlockCipher cbcBlockCipher = new CbcBlockCipher(new SM4Engine());
PaddedBufferedBlockCipher paddedBufferedBlockCipher = new PaddedBufferedBlockCipher(cbcBlockCipher, new Pkcs7Padding());
paddedBufferedBlockCipher.Init(true, keyParameter);
// 根据明文长度获取密文长度
byte[] output = new byte[paddedBufferedBlockCipher.GetOutputSize(dataByteArray.Length)];
// 先处理一部分字节
int len = paddedBufferedBlockCipher.ProcessBytes(dataByteArray, 0, dataByteArray.Length, output, 0);
// 再处理末尾凑不够一个分组的字节
paddedBufferedBlockCipher.DoFinal(output, len);
return Convert.ToBase64String(output);
}
public static string Decrypt(string encryptedData, string secretKey, string charset)
{
KeyParameter keyParameter = new KeyParameter(Convert.FromBase64String(secretKey));
byte[] encryptedDataByteArray = Convert.FromBase64String(encryptedData);
// 生成SM4解密器,CBC模式,PKCS7填充
CbcBlockCipher cbcBlockCipher = new CbcBlockCipher(new SM4Engine());
PaddedBufferedBlockCipher paddedBufferedBlockCipher = new PaddedBufferedBlockCipher(cbcBlockCipher, new Pkcs7Padding());
paddedBufferedBlockCipher.Init(false, keyParameter);
// 填充后的明文
byte[] output = new byte[paddedBufferedBlockCipher.GetOutputSize(encryptedDataByteArray.Length)];
// 获取明文的真实长度
int len1 = paddedBufferedBlockCipher.ProcessBytes(encryptedDataByteArray, 0,
encryptedDataByteArray.Length, output, 0);
int len2 = paddedBufferedBlockCipher.DoFinal(output, len1);
// 填充前的明文
byte[] rawDataByteArray = new byte[len1 + len2];
Array.Copy(output, 0, rawDataByteArray, 0, rawDataByteArray.Length);
return Encoding.GetEncoding(charset).GetString(rawDataByteArray);
}
public static void Main(string[] args)
{
string sm4Key = "teFsqfOOV2NMOZs98AKq9w==";
string data = "Today is not a day!";
string encryptedData = SM4Cryptor.Encrypt(data, sm4Key, "UTF-8");
Console.WriteLine("加密后的密文:" + encryptedData);
Console.WriteLine("解密后的原文:" + SM4Cryptor.Decrypt(encryptedData, sm4Key, "UTF-8"));
}
}
}
}
}
\ No newline at end of file
using System;
using System.Security.Cryptography;
using System.IO;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace Digest
{
public class SHA256Digest
{
public static string Digest(string fileName)
{
SHA256 hash = SHA256.Create();
FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
byte[] hashByte = hash.ComputeHash(stream);
stream.Close();
Console.WriteLine("上传文件hashh值:" + BitConverter.ToString(hashByte).Replace("-", "").ToLower());
return BitConverter.ToString(hashByte).Replace("-", "").ToLower();
}
}
}
}
}
\ No newline at end of file
using System;
using System.IO;
using System.Text;
using Org.BouncyCastle.Utilities.Encoders;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace Digest
{
public class SM3Digest
{
private const int SM3_DIGEST_SIZE = 32;
private const int DEFAULT_BUF_SIZE = 65536;
public static string Digest(string fileName)
{
Org.BouncyCastle.Crypto.Digests.SM3Digest sm3Digest = new Org.BouncyCastle.Crypto.Digests.SM3Digest();
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
byte[] buf = new byte[DEFAULT_BUF_SIZE];
int num;
while ((num = fileStream.Read(buf, 0, buf.Length)) > 0)
{
sm3Digest.BlockUpdate(buf, 0, num);
}
byte[] dig = new byte[SM3_DIGEST_SIZE];
sm3Digest.DoFinal(dig, 0);
return Encoding.UTF8.GetString(Hex.Encode(dig));
}
public static void Main(string[] args)
{
try
{
string digStr = SM3Digest.Digest("C:/Users/Administrator/Desktop/test.txt");
Console.WriteLine(digStr);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
}
}
}
}
\ No newline at end of file
using System;
using System.Security.Cryptography;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace KeyGen
{
public class AESKeyGen
{
public static string GenAES256Key()
{
AesCryptoServiceProvider key = new AesCryptoServiceProvider();
key.KeySize = 256;
key.GenerateKey();
return Convert.ToBase64String(key.Key);
}
}
}
}
}
\ No newline at end of file
using System;
using System.Text;
using Org.BouncyCastle.Asn1.GM;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
using Com.Bocom.OpenApi.Security.Crypt;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace KeyGen
{
public class SM2KeyGen
{
public static AsymmetricCipherKeyPair GenSM2KeyPair()
{
// 获取SM2标准中推荐的256bit的质数域的椭圆曲线域参数
X9ECParameters x9ECParameters = GMNamedCurves.GetByOid(GMObjectIdentifiers.sm2p256v1);
ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters);
// 构造EC密钥生成算法参数
ECKeyGenerationParameters ecKeyGenerationParameters =
new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom());
// 初始化EC密钥生成器
IAsymmetricCipherKeyPairGenerator asymmetricCipherKeyPairGenerator =
GeneratorUtilities.GetKeyPairGenerator("EC");
asymmetricCipherKeyPairGenerator.Init(ecKeyGenerationParameters);
return asymmetricCipherKeyPairGenerator.GenerateKeyPair();
}
/// <summary>
/// 从KeyPair对象中得到字符串表示的公钥(Hex编码)。
/// </summary>
/// <param name="keyPair"></param>
/// <returns></returns>
public static string GetPublicKeyStr(AsymmetricCipherKeyPair keyPair)
{
ECPublicKeyParameters publicKey = (ECPublicKeyParameters) keyPair.Public;
return Encoding.UTF8.GetString(Hex.Encode(publicKey.Q.GetEncoded(false)));
}
/// <summary>
/// 从KeyPair对象中得到字符串表示的私钥(Hex编码)。
/// </summary>
/// <param name="keyPair"></param>
/// <returns></returns>
public static string GetPrivateKeyStr(AsymmetricCipherKeyPair keyPair)
{
ECPrivateKeyParameters privateKey = (ECPrivateKeyParameters) keyPair.Private;
return Encoding.UTF8.GetString(Hex.Encode(privateKey.D.ToByteArray()));
}
/// <summary>
/// 公钥字符串(Hex编码)转成ECPublicKeyParameters对象。
/// </summary>
/// <param name="publicKey"></param>
/// <returns></returns>
public static ECPublicKeyParameters GetECPublicKey(string publicKey)
{
X9ECParameters x9ECParameters = GMNamedCurves.GetByOid(GMObjectIdentifiers.sm2p256v1);
ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters);
ECPoint q = x9ECParameters.Curve.DecodePoint(Hex.Decode(Encoding.UTF8.GetBytes(publicKey)));
return new ECPublicKeyParameters(q, ecDomainParameters);
}
/// <summary>
/// 私钥字符串(Hex编码)转成ECPrivateKeyParameters对象。
/// </summary>
/// <param name="privateKey"></param>
/// <returns></returns>
public static ECPrivateKeyParameters GetECPrivateKey(string privateKey)
{
X9ECParameters x9ECParameters = GMNamedCurves.GetByOid(GMObjectIdentifiers.sm2p256v1);
ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters);
BigInteger d = new BigInteger(Hex.Decode(Encoding.UTF8.GetBytes(privateKey)));
return new ECPrivateKeyParameters(d, ecDomainParameters);
}
public static void Main(string[] args)
{
AsymmetricCipherKeyPair keyPair = SM2KeyGen.GenSM2KeyPair();
string pubKey = SM2KeyGen.GetPublicKeyStr(keyPair);
string priKey = SM2KeyGen.GetPrivateKeyStr(keyPair);
Console.WriteLine("公钥:" + pubKey);
Console.WriteLine("公钥位数:" + pubKey.Length);
Console.WriteLine("私钥:" + priKey);
Console.WriteLine("私钥位数:" + priKey.Length);
string plainText = "交通银行软件开发中心";
string encryptedText = SM2Cryptor.Encrypt(plainText, "04d174bced6dab54eae6cb9d4c4794ea77008b4b123663c464084edc04b26da553ec3132b9d44ae5f28522beb0312d178f709d18cf9ad722d8ad0e4431085a2fb0", "UTF-8");
Console.WriteLine("加密后的密文:" + encryptedText);
string decryptedText = SM2Cryptor.Decrypt(encryptedText, "3dea5f72479ef4005e3017e617384d1bf4c66d536204dd44faa4c7075abfb5d5", "UTF-8");
Console.WriteLine("解密后的明文:" + decryptedText);
}
}
}
}
}
\ No newline at end of file
using System;
using System.Security.Cryptography;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace KeyGen
{
public class SM4KeyGen
{
public static string GenSM4Key()
{
AesCryptoServiceProvider key = new AesCryptoServiceProvider();
key.KeySize = 128;
key.GenerateKey();
return Convert.ToBase64String(key.Key);
}
}
}
}
}
\ No newline at end of file
using System;
using System.Text;
using System.Security.Cryptography;
using System.Xml;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using Com.Bocom.OpenApi.Security.Crypt;
using Com.Bocom.OpenApi.Utils;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace Sign
{
public class RSASignature
{
//private static infosecapiLib.infosec icbcCA = new infosecapiLib.infosec();
public static string Sign(string content, string privateKey, string charset)
{
return Sign(content, privateKey, charset, null);
}
public static string Sign(string content, string privateKey, string charset, string password)
{
return RSACryptor.RSAFromPkcs8.SignWithRSASHA256(content, privateKey, charset);
}
public static bool Verify(string content, string publicKey, string charset, string sign)
{
try
{
//byte[] contentBytes = Encoding.GetEncoding(charset).GetBytes(content);
return RSACryptor.RSAFromPkcs8.VerifySHA256(content, sign, publicKey, charset);
}
catch (Exception e)
{
throw new Exception(
"get content charset exception. content: " + content + " charset: " + charset,
e);
}
}
public static string RSAPrivateKeyJava2DotNet(string privateKey)
{
RsaPrivateCrtKeyParameters privateKeyParam =
(RsaPrivateCrtKeyParameters) PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
return string.Format(
"<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
}
/// <summary>
/// RSA私钥格式转换,.net->java
/// </summary>
/// <param name="privateKey">.net生成的私钥</param>
/// <returns></returns>
public static string RSAPrivateKeyDotNet2Java(string privateKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(privateKey);
BigInteger m = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger exp = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
BigInteger d = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
BigInteger p = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
BigInteger q = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
BigInteger dp = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
BigInteger dq = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
BigInteger qinv = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));
RsaPrivateCrtKeyParameters privateKeyParam =
new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);
PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);
byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
return Convert.ToBase64String(serializedPrivateBytes);
}
/// <summary>
/// RSA公钥格式转换,.net->java
/// </summary>
/// <param name="publicKey">.net生成的公钥</param>
/// <returns></returns>
public static string RSAPublicKeyDotNet2Java(string publicKey)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(publicKey);
BigInteger m = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
BigInteger p = new BigInteger(1,
Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
RsaKeyParameters pub = new RsaKeyParameters(false, m, p);
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
return Convert.ToBase64String(serializedPublicBytes);
}
//AES内容解密
public static string DecryptContent(string content, string encryptType, string encryptKey,
string charset)
{
if (encryptType.Equals(BocomConstants.ENCRYPT_TYPE_RSA_AND_AES))
return AesDecrypt(content, encryptKey);
else
throw new Exception("当前不支持该算法类型:encrypeType=" + encryptType);
}
//AES内容加密
public static string EncryptContent(string content, string encryptType, string encryptKey,
string charset)
{
if (encryptType.Equals(BocomConstants.ENCRYPT_TYPE_RSA_AND_AES))
return AesEncrypt(content, encryptKey);
throw new Exception("当前不支持该算法类型:encrypeType=" + encryptType);
}
/// <summary>
///AES加密(加密步骤)
///1,加密字符串得到2进制数组;
///2,将2禁止数组转为16进制;
///3,进行base64编码
/// </summary>
/// <param name="toEncrypt">要加密的字符串</param>
/// <param name="key">密钥</param>
public static string AesEncrypt(string toEncrypt, string key)
{
Byte[] _Key = Convert.FromBase64String(key);
Byte[] _Source = Encoding.UTF8.GetBytes(toEncrypt);
Aes aes = Aes.Create("AES");
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = _Key;
aes.IV = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
ICryptoTransform cTransform = aes.CreateEncryptor();
Byte[] cryptData = cTransform.TransformFinalBlock(_Source, 0, _Source.Length);
string CryptString = Convert.ToBase64String(cryptData);
return CryptString;
}
/// <summary>
/// AES解密(解密步骤)
/// 1,将BASE64字符串转为16进制数组
/// 2,将16进制数组转为字符串
/// 3,将字符串转为2进制数据
/// 4,用AES解密数据
/// </summary>
/// <param name="encryptedSource">已加密的内容</param>
/// <param name="key">密钥</param>
public static string AesDecrypt(string encryptedSource, string key)
{
Byte[] _Key = Convert.FromBase64String(key);
Aes aes = Aes.Create("AES");
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = _Key;
aes.IV = new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
ICryptoTransform cTransform = aes.CreateDecryptor();
Byte[] encryptedData = Convert.FromBase64String(encryptedSource);
Byte[] originalSourceData = cTransform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
string originalString = Encoding.UTF8.GetString(originalSourceData);
return originalString;
}
}
}
}
}
\ No newline at end of file
using System;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Utilities.Encoders;
using Com.Bocom.OpenApi.Security.KeyGen;
namespace Com.Bocom.OpenApi
{
namespace Security
{
namespace Sign
{
public class SM2Signature
{
public static string Sign(string data, string privateKey, string charset)
{
ISigner signer = new SM2Signer();
signer.Init(true, SM2KeyGen.GetECPrivateKey(privateKey));
byte[] dataByteArray = Encoding.GetEncoding(charset).GetBytes(data);
signer.BlockUpdate(dataByteArray, 0, dataByteArray.Length);
return Hex.ToHexString(signer.GenerateSignature());
}
public static bool Verify(string data, string publicKey, string charset, string signature)
{
ISigner signer = new SM2Signer();
signer.Init(false, SM2KeyGen.GetECPublicKey(publicKey));
byte[] dataByteArray = Encoding.GetEncoding(charset).GetBytes(data);
signer.BlockUpdate(dataByteArray, 0, dataByteArray.Length);
return signer.VerifySignature(Hex.Decode(signature));
}
}
}
}
}
\ No newline at end of file
using System;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using Com.Bocom.OpenApi.Security.Sign;
namespace Com.Bocom.OpenApi
{
namespace Utils
{
public class ApiUtils
{
public static Object ParseNotifyJsonWithBocomSign(string notifyStr, string charset, string APIGW_PUBLIC_KEY,
Type T)
{
string bizContentStr;
string sign;
try
{
int indexOfRootStart = notifyStr.IndexOf(BocomConstants.NOTIFY_BIZ_CONTENT)
+ BocomConstants.NOTIFY_BIZ_CONTENT.Length + 2;
int indexOfRootEnd = notifyStr.LastIndexOf(",");
int indexOfSignStart =
notifyStr.LastIndexOf(BocomConstants.SIGN + "\"") + BocomConstants.SIGN.Length + 3;
int indexOfSignEnd = notifyStr.LastIndexOf("\"");
bizContentStr = notifyStr.Substring(indexOfRootStart, indexOfRootEnd - indexOfRootStart);
sign = notifyStr.Substring(indexOfSignStart, indexOfSignEnd - indexOfSignStart);
}
catch (Exception e)
{
throw new Exception("notify_biz_content is not format json. notifyStr :\n" + notifyStr, e);
}
Boolean passed = RSASignature.Verify(bizContentStr, APIGW_PUBLIC_KEY, charset, sign);
if (!passed)
{
throw new Exception("Bocom sign verify not passed.");
}
try
{
//反序列化并返回
BocomResponse response;
MemoryStream ms1 = new MemoryStream(Encoding.GetEncoding(charset).GetBytes(bizContentStr));
using (MemoryStream ms = new MemoryStream(Encoding.GetEncoding(charset).GetBytes(bizContentStr)))
{
DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(T);
response = (BocomResponse) deseralizer.ReadObject(ms) as BocomResponse;
}
return response;
}
catch (Exception e)
{
throw new Exception("notify_biz_content can not transform to defined class. response: " + notifyStr
+ " defined class name: " +
T, e);
}
}
}
}
}
\ No newline at end of file
namespace Com.Bocom.OpenApi
{
namespace Utils
{
public class BocomConstants
{
public static string APP_ID = "app_id";
public static string ENCRYPT_TYPE_SM2_AND_SM4 = "SM2_AND_SM4";
public static string ENCRYPT_TYPE_RSA_AND_AES = "RSA_AND_AES";
public static string FORMAT = "format";
public static string TIMESTAMP = "timestamp";
public static string SIGN = "sign";
public static string APP_AUTH_TOKEN = "app_auth_token";
public static string CHARSET = "charset";
public static string NOTIFY_URL = "notify_url";
public static string RETURN_URL = "return_url";
public static string ENCRYPT_TYPE = "encrypt_type";
public static string IS_ENCRYPT = "is_encrypt";
// -----===-------///
public static string BIZ_CONTENT_KEY = "biz_content";
/** 默认时间格式 **/
public static string DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/** Date默认时区 **/
public static string DATE_TIMEZONE = "GMT+8";
/** UTF-8字符集 **/
public static string CHARSET_UTF8 = "UTF-8";
/** GBK字符集 **/
public static string CHARSET_GBK = "GBK";
public static string FMT_TYPE = "fmt_type";
/** JSON 应格式 */
public static string FORMAT_JSON = "json";
/** XML 应格式 */
public static string FORMAT_XML = "xml";
public static string PASSWORD = "password";
public static string RESPONSE_BIZ_CONTENT = "rsp_biz_content";
/** 消息唯一编号 **/
public static string MSG_ID = "msg_id";
/** sdk版本号在header中的key */
public static string VERSION_HEADER_NAME = "APIGW-VERSION";
/**
* 通知域
*/
public static string NOTIFY_BIZ_CONTENT = "notify_biz_content";
/// <summary>
/// 字段加密。
/// </summary>
public static string ENCRYPT_POLICY_TYPE_FIELD = "FIELD";
/// <summary>
/// 全报文加密。
/// </summary>
public static string ENCRYPT_POLICY_TYPE_CONTENT = "CONTENT";
/// <summary>
/// 文件加密。
/// </summary>
public static string ENCRYPT_POLICY_TYPE_FILE = "FILE";
public static string ENCRYPT_POLICY = "encrypt_policy";
public static string BIZ_CONTENT = "biz_content";
public static string ENCRYPT_KEY = "encrypt_key";
public static string FILE_HASHCODE = "file_hashcode";
public static string FILE_CONTENT = "file_content";
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
namespace Com.Bocom.OpenApi
{
namespace Utils
{
public class BocomHashMap : Dictionary<string, string>
{
private static long serialVersionUID = 8026336190683519216L;
public BocomHashMap() : base()
{
}
public string Put(string key, Object value)
{
string strValue;
if (value == null)
{
strValue = null;
}
else if (value is string)
{
strValue = (string) value;
}
else if (value is int)
{
strValue = Convert.ToString(value);
}
else if (value is long)
{
strValue = Convert.ToString(value);
}
else if (value is float)
{
strValue = Convert.ToString(value);
}
else if (value is Double)
{
strValue = Convert.ToString(value);
}
else if (value is Boolean)
{
strValue = Convert.ToString(value);
}
else if (value is DateTime)
{
string format = BocomConstants.DATE_TIME_FORMAT;
// format.setTimeZone(TimeZone.getTimeZone(BocomConstants.DATE_TIMEZONE));
strValue = Convert.ToString(value);
}
else
{
strValue = Convert.ToString(value);
}
return Put(key, strValue);
}
public string Put(string key, string value)
{
if (key != string.Empty && value != string.Empty)
{
return Put(key, value);
}
return null;
}
}
}
}
\ No newline at end of file
using System;
using Com.Bocom.OpenApi.Security.Sign;
namespace Com.Bocom.OpenApi
{
namespace Utils
{
public class BocomSignature
{
public static string Sign(string encryptType, string content, string privateKey, string charset)
{
if (BocomConstants.ENCRYPT_TYPE_RSA_AND_AES == encryptType)
{
return RSASignature.Sign(content, privateKey, charset);
}
if (BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4 == encryptType)
{
return SM2Signature.Sign(content, privateKey, charset);
}
throw new BocomApiException("仅支持使用RSA和SM2签名!");
}
public static bool Verify(string encryptType, string content, string publicKey, string charset, string signature)
{
if (BocomConstants.ENCRYPT_TYPE_RSA_AND_AES == encryptType)
{
return RSASignature.Verify(content, publicKey, charset, signature);
}
if (BocomConstants.ENCRYPT_TYPE_SM2_AND_SM4 == encryptType)
{
return SM2Signature.Verify(content, publicKey, charset, signature);
}
throw new BocomApiException("仅支持使用RSA和SM2验签!");
}
}
}
}
\ No newline at end of file
using System.IO;
namespace Com.Bocom.OpenApi
{
namespace Utils
{
public class FileItem
{
private string fileName;
private string mimeType;
private byte[] content;
private FileStream fileStream;
/**
* 基于本地文件的构造器。
*
* @param file
* 本地文件
*/
public FileItem(FileStream fileStream)
{
this.fileStream = fileStream;
content = ToByteArray(fileStream);
fileName = GetFileName();
}
/**
* 基于文件绝对路径的构造器。
*
* @param filePath
* 文件绝对路径
*/
public FileItem(string filePath)
{
FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate);
fileName = filePath;
content = ToByteArray(fileStream);
}
public string GetFileName()
{
if (fileName == null && fileStream != null)
{
fileName = fileStream.Name;
}
return fileName;
}
public string GetMimeType()
{
if (mimeType == null)
{
mimeType = GetMimeType(GetContent());
}
return mimeType;
}
public static byte[] ToByteArray(Stream stream)
{
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
stream.Close();
return bytes;
}
/**
* @param filePath
* 文件路径
* @return file bytes
* @throws IOException
* 读取文件错误
*/
public byte[] GetContent()
{
/* if (this.fileName == null && this.fileStream != null )
{
byte[] content = toByteArray(this.fileStream);
this.content = content;
}*/
return content;
}
public static byte[] ToByteArray(FileStream fi)
{
byte[] bytes = new byte[fi.Length];
fi.Read(bytes, 0, bytes.Length);
fi.Close();
return bytes;
}
/**
* 获取文件的真实媒体类型。目前只支持JPG, GIF, PNG, BMP四种图片文件。
*
* @param bytes
* 文件字节流
* @return 媒体类型(MEME-TYPE)
*/
public static string GetMimeType(byte[] bytes)
{
string suffix = GetFileSuffix(bytes);
string mimeType;
if ("JPG".Equals(suffix))
{
mimeType = "image/jpeg";
}
else if ("GIF".Equals(suffix))
{
mimeType = "image/gif";
}
else if ("PNG".Equals(suffix))
{
mimeType = "image/png";
}
else if ("BMP".Equals(suffix))
{
mimeType = "image/bmp";
}
else
{
mimeType = "application/octet-stream";
}
return mimeType;
}
/**
* 获取文件的真实后缀名。目前只支持JPG, GIF, PNG, BMP四种图片文件。
*
* @param bytes
* 文件字节流
* @return JPG, GIF, PNG or null
*/
public static string GetFileSuffix(byte[] bytes)
{
if (bytes == null || bytes.Length < 10)
{
return null;
}
if (bytes[0] == 'G' && bytes[1] == 'I' && bytes[2] == 'F')
{
return "GIF";
}
if (bytes[1] == 'P' && bytes[2] == 'N' && bytes[3] == 'G')
{
return "PNG";
}
if (bytes[6] == 'J' && bytes[7] == 'F' && bytes[8] == 'I' && bytes[9] == 'F')
{
return "JPG";
}
if (bytes[0] == 'B' && bytes[1] == 'M')
{
return "BMP";
}
return null;
}
public FileStream GetFileStream()
{
// TODO Auto-generated method stub
return fileStream;
}
public void SetContent(byte[] encryptContent)
{
content = encryptContent;
}
}
}
}
\ No newline at end of file
using System.Collections.Generic;
namespace Com.Bocom.OpenApi
{
namespace Utils
{
public class HttpRequestParamsUtils
{
static public List<string> apiParamNames = new List<string>()
{
BocomConstants.SIGN, BocomConstants.APP_ID, BocomConstants.CHARSET, BocomConstants.FORMAT,
BocomConstants.ENCRYPT_TYPE, BocomConstants.TIMESTAMP, BocomConstants.MSG_ID
};
}
}
}
\ No newline at end of file
using System.Security.Cryptography;
using System;
namespace Com.Bocom.OpenApi
{
namespace Utils
{
public class KeyGeneratorUtils
{
/// <summary>
/// 随机生成秘钥(对称算法)
/// </summary>
/// <param name="key">秘钥(base64格式)</param>
/// <param name="iv">iv向量(base64格式)</param>
/// <param name="keySize">要生成的KeySize,每8个byte是一个字节,注意每种算法支持的KeySize均有差异,实际可通过输出LegalKeySizes来得到支持的值</param>
public static void CreateSymmetricAlgorithmKey<T>(out string key, out string iv, int keySize)
where T : SymmetricAlgorithm, new()
{
using (T t = new T())
{
t.KeySize = keySize;
t.GenerateIV();
t.GenerateKey();
iv = Convert.ToBase64String(t.IV);
key = Convert.ToBase64String(t.Key);
}
}
}
}
}
\ No newline at end of file
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace Com.Bocom.OpenApi
{
namespace Utils
{
public class TrustAllCertificatePolicy
{
public static void SetCertificatePolicy()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateCalidate;
}
public static bool RemoteCertificateCalidate(object sernder, X509Certificate cert, X509Chain chain,
SslPolicyErrors error)
{
return true;
}
}
}
}
\ No newline at end of file
using Com.Bocom.OpenApi;
using Com.Bocom.OpenApi.Utils;
using Kivii;
using Kivii.Text;
using Kivii.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Njzj.Bocoms.Openapis.Transforms
{
public class QueryContractOrderResponseV2Test : RestfulExecution<QueryContractOrderResponseV2>
{
public override object OnExecution(IRequest req, IResponse res)
{
DefaultBocomClient client = new DefaultBocomClient(Configs.APP_ID, Configs.MY_PRIVATE_KEY, Configs.APIGW_PUBLIC_KEY, BocomConstants.ENCRYPT_TYPE_RSA_AND_AES);
/**
* 测试环境可以忽略SSL证书告警,生产环境不可忽略
*/
client.IgnoreSslHostnameVerifier();
var request = new QueryContractOrderRequestV2();
request.SetServiceUrl(Configs.APIGW_URL_ADDRESS + Configs.QueryContractOrderRequestV2);
var bizContent = new QueryContractOrderRequestV2.QueryContractOrderRequestV2Biz();
bizContent.setOrgId(Configs.ORG_ID);
bizContent.setBillId("1354000420220402000000001792");
request.SetBizContent(bizContent);
var json = JsonSerializer.SerializeToString(request);
var response = client.Execute(request, Guid.NewGuid().ToString().Replace("-", ""));
var rtns = new RestfulExecutionResponse<string>();
rtns.Results = new List<string>();
if (response.IsSuccess())
{
rtns.Results.Add("success");
rtns.Results.Add($"ReturnCode:{response.GetRspCode()}{Environment.NewLine}ReturnMsg:{response.GetRspMsg()}");
rtns.Results.Add(response.ToString());
}
else
{
rtns.Results.Add("failed");
rtns.Results.Add($"ReturnCode:{response.GetRspCode()}{Environment.NewLine}ReturnMsg:{response.GetRspMsg()}");
}
return rtns;
}
}
public class WriteOffResultResponseV2Test : RestfulExecution<WriteOffResultResponseV2>
{
public override object OnExecution(IRequest req, IResponse res)
{
DefaultBocomClient client = new DefaultBocomClient(Configs.APP_ID, Configs.MY_PRIVATE_KEY, Configs.APIGW_PUBLIC_KEY);
/**
* 测试环境可以忽略SSL证书告警,生产环境不可忽略
*/
client.IgnoreSslHostnameVerifier();
WriteOffResultRequestV2 request = new WriteOffResultRequestV2();
request.SetServiceUrl(Configs.APIGW_URL_ADDRESS + Configs.WriteOffResultRequestV2);
WriteOffResultRequestV2.WriteOffResultRequestV2Biz bizContent = new WriteOffResultRequestV2.WriteOffResultRequestV2Biz();
bizContent.orgId = Configs.ORG_ID;
bizContent.subOrgId = Configs.SUB_ORG_ID;
bizContent.writeOffDte = "2022-05-03";
bizContent.writeOffNo = "2022050500004";
bizContent.pageablerequestPagenum = "1";
bizContent.pageablerequestPagesize = "10";
request.SetBizContent(bizContent);
var response = client.Execute(request, Guid.NewGuid().ToString().Replace("-", ""));
var rtns = new RestfulExecutionResponse<string>();
rtns.Results = new List<string>();
if (response.IsSuccess())
{
rtns.Results.Add("success");
rtns.Results.Add($"ReturnCode:{response.GetRspCode()}{Environment.NewLine}ReturnMsg:{response.GetRspMsg()}");
rtns.Results.Add(response.ToString());
}
else
{
rtns.Results.Add("failed");
rtns.Results.Add($"ReturnCode:{response.GetRspCode()}{Environment.NewLine}ReturnMsg:{response.GetRspMsg()}");
}
return rtns;
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Kivii.Common" version="5.6.2023.4000" targetFramework="net45" />
<package id="Kivii.Core" version="5.6.2023.4140" targetFramework="net45" />
</packages>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment