/*******************************************************
 *
 * 使用此JS脚本之前请先仔细阅读mToken KEY帮助文档
 *
 * @author		Longmai
 * @version		3.0
 * @date		2015/9/25
 * @explanation	 mToken Plugin 支持各浏览器
 *
**********************************************************/
import {mToken} from './mToken.js'
import {_Base64encode,_Base64decode} from './base64.js'
import config from '@/config'

const token = new mToken("mTokenPlugin");

let nowDeviceName;
let nowContainer;
let nowCertName;
let nowCertType;
export default {
  name:'UKEY',
	//动态添加option选项
  addOption(optionStr, nowDeviceName, flag)
	{
		if(flag == 1)
		{
			for(let i = 0; i < optionStr.length; ++i)
				nowDeviceName.options.add(new Option(optionStr[i], i));
		}
		if(flag == 2)
		{
			for(let i = 0; i < optionStr.length; ++i)
			{
				nowDeviceName.options.add(new Option(optionStr[i][1], i));
			}
		}
	},

	//获取当前设备id
  getNowDeviceName(){
    if (!nowDeviceName){
      this.enumDevice();
    }
    return nowDeviceName;
  },

	//枚举当前设备
	enumDevice()
	{
		//let slectType = document.getElementById("platform").value;
		let ret;
		//let nowDeviceName = document.getElementById("sele_devices");
		//nowDeviceName.options.length=0;

		/*if(slectType == "GM3000PCSC")
			ret = token.SOF_LoadLibrary(token.GM3000PCSC);
		else if(slectType == "GM3000")*/
			ret = token.SOF_LoadLibrary(token.GM3000);
		/*else if(slectType == "K7")
			ret = token.SOF_LoadLibrary(token.K7);
		else if(slectType == "TF")
			ret = token.SOF_LoadLibrary(token.TF);
		else
			ret = token.SOF_LoadLibrary(token.K5);	*/
		if(ret != 0)
		{
			alert("加载控件失败,错误码:" + token.SOF_GetLastError());
			return ;
		}
		let deviceName = token.SOF_EnumDevice();

		if(deviceName != null)
		{
			//addOption(deviceName, nowDeviceName, 1);
      //alert(deviceName);
      nowDeviceName = deviceName[0];//默认取第一个ukey设备
      let ret = token.SOF_GetDeviceInstance(deviceName, "");//初始化mtoken.js中的_curDevName
      return nowDeviceName;
		}
		else
		{
			return null;
		}
	},

	//获取证书列表 数组中是数组 0是证书名称 1是容器名称
	getCerList()
	{
		//let nowDeviceName = document.getElementById("sele_devices");
		//let cerlistID = document.getElementById("sele_contentList");
		if(!nowDeviceName && !this.enumDevice())
		{
			alert("请选中列表中设备后操作");
			return;
		}

		let deviceName = nowDeviceName;

		let ret = token.SOF_GetDeviceInstance(deviceName, "");

		if(ret != 0)
		{
			alert("绑定应用失败，确定是否初始化Key,错误码:" + token.SOF_GetLastError());
			return;
		}
		let cerList = token.SOF_GetUserList();
    return cerList;

	},

  //获取指定名称容器下的证书
  getCert(context)
  {
    //let nowDeviceName = document.getElementById("sele_devices");
    //let cerlistID = document.getElementById("sele_contentList");
    if(!nowDeviceName && !this.enumDevice())
    {
      alert("请检测到设备后操作");
      return;
    }

    let deviceName = nowDeviceName;

    let ret = token.SOF_GetDeviceInstance(deviceName, "");

    if(ret != 0)
    {
      alert("绑定应用失败，确定是否初始化Key,错误码:" + token.SOF_GetLastError());
      return;
    }
    let cerList = token.SOF_GetUserList();
    for(let i = 0; i < cerList.length; ++i)
    {
      if(cerList[i][1]==context){
        return cerList[i][0];
      };
    }
  },

  //获取指定名称容器下的证书
  initCert(context,certType)
  {
    if(!nowDeviceName && !this.enumDevice())
    {
      alert("请检测到设备后操作");
      return;
    }
    let deviceName = nowDeviceName;
    let ret = token.SOF_GetDeviceInstance(deviceName, "");
    if(ret != 0)
    {
      alert("绑定应用失败，确定是否初始化Key,错误码:" + token.SOF_GetLastError());
      return;
    }
    //let cerList = token.SOF_GetUserList();
    /*if (!cerList) {return null;}
    for(let i = 0; i < cerList.length; ++i)
    {
      if(cerList[i][1]==context){

        //nowCertName = context;
        return cerList[i][0];
      };
    }*/
    nowContainer = context;
    nowCertType = certType;
  },

	//验证用户密码
	verifyUserPin(pin)
	{
		let ret = 0;
		let strRes = "";
		//获取UKey的类型，并按UKey类型来提示验证身份
		let hwType = token.SOF_GetHardwareType();
		if(hwType == token.TYPE_FPKEY)
		{//验证用户指纹
			//请在这里，替换更友善的用户提示...
			//开始“用户验证指纹”的提示

			alert("当指纹KEY上的指示灯开始闪烁时，请按压手指以验证指纹......"); //Longmai的示例提示方式
			ret = token.SOF_VerifyFingerprint();

			//结束“用户验证指纹”的提示

			if(ret == 0)
			{
				strRes = "验证用户指纹成功。";
			}
			else
			{
				strRes = "验证用户指纹失败。";
			}
		}
		else
		{//验证用户密码
			//let pin = document.getElementById("txt_pwd").value;
			ret = token.SOF_Login(pin);
			if(ret == 0)
			{
				strRes = "验证用户密码成功。";
			}
			else
			{
        ret = token.SOF_Login(pin);
				//strRes = "验证用户密码失败。";
			}
		}

		if(ret != 0)
		{
			let lastErr = token.SOF_GetLastError();
			let retryCount = token.SOF_GetPinRetryCount();
			//document.getElementById("tryCount").value = "剩余次数：" + retryCount;
			alert(strRes + " 错误码:" + lastErr);
      return false;
		}
    return true;
	},

	//修改密码
	changeUserPin()
	{
		let pin = document.getElementById("txt_pwd").value;
		let resetPin = document.getElementById("txt_Changepwd").value;
		let ret = token.SOF_ChangePassWd(pin, resetPin);
		if(ret != 0)
			alert("密码修改失败,错误码:" + token.SOF_GetLastError());
		else
			alert("密码修改成功");
	},

	//控件版本信息
	 getVersion()
    {
        let version = token.SOF_GetVersion();
		document.getElementById("contorlInfo").value = version;
    }	,

  //生成秘钥对
  createKeyPair(containerName,ulKeySpec)
  {
    let Rtn = token.SOF_CreateKeyPair(containerName,ulKeySpec,0x00010000,'2048');
    return Rtn;
  }	,

	//生成P10请求
		btn_P10_request(){
			//容器名

			//DN
			let dn=document.getElementById("txt_DN").value;
			//算法
			let asymAlg=document.getElementById("txt_asymAlg").value;
			//签名
			let keySpec=document.getElementById("txt_keySpec").value;
			//秘钥长度
			let keyLength=document.getElementById("txt_keyLength").value;
			if(container=="" || dn=="" || asymAlg=="" || keySpec=="" || keyLength==""){
				alert("请确保各个参数是否为空！");
				return;
			}
			let nowDeviceName = document.getElementById("sele_devices");
			let index = nowDeviceName.selectedIndex;
			if(index < 0)
			{
				alert("请选中列表中设备后操作");
				return;
			}

			let deviceName = nowDeviceName.options[index].text;
			let p10Req = token.SOF_GenerateP10Request(deviceName,container, dn, asymAlg, keySpec, keyLength);
			if(p10Req=="" || p10Req==null){
				alert("生成失败！错误码："+token.SOF_GetLastError());
				return;
			}
			document.getElementById("P10_requestData").value = p10Req;
			//开发发送到服务器，发送方式和之前一致。

		},


	//导入签名证书
	btn_importSignCert()
	{
		let cert = document.getElementById("txt_SignCertData").value;
		let container = document.getElementById("txt_Container").value;
		if(cert.length <256)
		{
			alert("无效的签名证书数据。");
			return;
		}
		let retVal = 0;
		retVal = token.SOF_ImportCert(container, cert, 0); //0:OK
		if(retVal!=0){
			alert("导入失败！错误码："+token.SOF_GetLastError());
			return;
		}
		alert("导入成功")
		//开发发送到服务器，发送方式和之前一致。
	},



	//导出证书信息
	exportUserCert(container,certType)
	{

		if(!nowDeviceName && !this.enumDevice())
		{
			alert("请检测到设备后操作");
			return;
		}

		//let

		if((container == null || container == "") && nowContainer)
		{
      container = nowContainer;
		}

    if((certType == null || certType == "") && nowCertType)
    {
      certType = nowCertType;
    }

		//let selectType;
		let cert  = token.SOF_ExportUserCert(container, nowCertType);
		if(cert != null && cert != "")
		{
			return  cert;
		}
		else
			alert("获取证书信息失败,错误码:" + token.SOF_GetLastError());
	},

	//获取证书信息
	getCertInfo()
	{
		let signCert = document.getElementById("cerInfo").value;
		if(signCert == "")
			{
				alert("请先导出证书");
				return;
			}
		let showCer = document.getElementById("showcerInfo");

		showCer.value = "";
		let cerInfo = "";
		let str = token.SOF_GetCertInfo(signCert, token.SGD_CERT_ISSUER_CN);
		cerInfo += "Issuer: " + str + "\r";

		str = token.SOF_GetCertInfo("", token.SGD_CERT_SUBJECT);
		cerInfo += "Subject: " + str + "\r";
		str = token.SOF_GetCertInfo("", token.SGD_CERT_SUBJECT_CN);
		cerInfo += "Subject_CN: " + str + "\r";
		str = token.SOF_GetCertInfo("", token.SGD_CERT_SUBJECT_EMALL);
		cerInfo += "Subject_EMail: " + str + "\r";
		str = token.SOF_GetCertInfo("", token.SGD_CERT_SERIAL);
		cerInfo += "Serial: " + str + "\r";
		str = token.SOF_GetCertInfo("", token.SGD_CERT_CRL);
		cerInfo += "cRLDistributionPoints: " + str + "\r";

		str = token.SOF_GetCertInfo("", token.SGD_CERT_NOT_BEFORE);
		cerInfo += "not before: " + str + "\r";

		str = token.SOF_GetCertInfo("", token.SGD_CERT_VALID_TIME);
		cerInfo += "validTimeTo: " + str + "\r";

		cerInfo += "如需获取更多信息请查看帮助文档";

		showCer.value = cerInfo;
	},

	//获取设备信息
	getDeviceInfo()
	{
		let strInfo = {};
		let str = token.SOF_GetDeviceInfo(token.SGD_DEVICE_NAME);
    strInfo.DeviceName = str;

    str = token.SOF_GetDeviceInfo(token.SGD_DEVICE_SORT);
    strInfo.DeviceSort = str;

		str = token.SOF_GetDeviceInfo(token.SGD_DEVICE_SUPPORT_STORANGE_SPACE);
		if(str){
      str = (str/1024)+'';
    }else{
		  str = '0';
    }
    strInfo.DeviceTotalSpace = str;


		str = token.SOF_GetDeviceInfo(token.SGD_DEVICE_SUPPORT_FREE_SAPCE);
    strInfo.DeviceFreeSpace = str;

		str = token.SOF_GetDeviceInfo(token.SGD_DEVICE_HARDWARE_VERSION);
    strInfo.DeviceHardwareVersion = str;

		str = token.SOF_GetDeviceInfo(token.SGD_DEVICE_SERIAL_NUMBER);
    strInfo.DeviceSerialNumber = str;

		str = token.SOF_GetDeviceInfo(token.SGD_DEVICE_MANUFACTURER);
    strInfo.DeviceManufacturer = str;

    str = token.SOF_GetDeviceInfo(token.SGD_DEVICE_MAX_DATA_SIZE);
    strInfo.DeviceMaxDataSize = str;

    let ukeyAccountFileName = config.ukeyAccountFileName;
    let userNameFileName = config.userNameFileName;
    let existsUkeyAccountFileName = this.readFile(ukeyAccountFileName);
    let existsUserNameFileName = this.readFile(userNameFileName);
    strInfo.ukeyAccountFileName = existsUkeyAccountFileName;
    strInfo.userNameFileName = existsUserNameFileName;

		return strInfo;
	},


	//数据签名  算法 签名数据 用户id(可无)
	signData(inData,userID,containerName)
	{
    let DigestMethod = 2;//加密算法 SGD_SHA1
		//let
		//let selectType;
		if(nowCertType == 0)
		{
			alert("请选择签名密钥进行签名");
			return ;
		}
		let ret = token.SOF_SetDigestMethod(Number(DigestMethod));
			ret = token.SOF_SetUserID(userID);


		if(!containerName)
		{
			alert("请先枚举容器后操作");
			return;
		}


		if(containerName == null || containerName == "")
		{
			alert("请选择容器操作");
			return;
		}

		let signed = token.SOF_SignData(containerName, nowCertType, _Base64encode(inData), inData.length);
		if(signed != null && signed != "")
			return signed;
		else
			alert("签名失败,错误码:" + token.SOF_GetLastError());
      return null;
	},



	//数据签名
	signData_P7()
	{
    let signed;
		//let
		//let selectType;
		if(nowCertType == 0)
		{
			alert("请选择签名密钥进行签名");
			return ;
		}
		let DigestMethod = document.getElementById("mech").value;
		let userID = document.getElementById("userID").value;
		let inData = document.getElementById("originalData").value;
		let ret = token.SOF_SetDigestMethod(Number(DigestMethod));
			ret = token.SOF_SetUserID(userID);


		if(nowContainer)
		{
			alert("请先枚举容器后操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}



		signed = token.SOF_SignDataToPKCS7(nowContainer, nowCertType, _Base64encode(inData), 0);
		if(signed != null && signed != "")
			document.getElementById("signedData").value = signed;
		else
			alert("签名失败,错误码:" + token.SOF_GetLastError());
	},

	//文件签名
	signFile()
	{
		//let
		//let selectType;
		if(nowCertType == 0)
		{
			alert("请选择签名密钥进行签名");
			return ;
		}
		let DigestMethod = document.getElementById("mech").value;
		let userID = document.getElementById("userID").value;
		let inFile = document.getElementById("signFile").value;
		let ret = token.SOF_SetDigestMethod(Number(DigestMethod));
			ret = token.SOF_SetUserID(userID);


		if(nowContainer)
		{
			alert("请先枚举容器后操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}


		let signed = token.SOF_SignFileToPKCS7(nowContainer, nowCertType, inFile);
		if(signed != null && signed != "")
			document.getElementById("signedData").value = signed;
		else
			alert("签名失败,错误码:" + token.SOF_GetLastError());
	},
	//数据验签
	verifySignFile()
	{
		//let
		//let selectType;
		if(nowCertType == 0)
		{
			alert("请选择签名密钥进行签名");
			return ;
		}
		let DigestMethod = document.getElementById("mech").value;
		let userID = document.getElementById("userID").value;
		let inFile = document.getElementById("signFile").value;
		let signed = document.getElementById("signedData").value;
		if(signed == null || signed.length <= 0)
		{
			alert("请先签名后操作");
			return;
		}


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		let cert  = token.SOF_ExportUserCert(nowContainer, nowCertType);

		let ret = token.SOF_SetDigestMethod(Number(DigestMethod));
			ret = token.SOF_SetUserID(userID);
			ret = token.SOF_VerifyFileToPKCS7(signed, inFile);
		if(ret != 0)
			alert("验签失败,错误码:" + token.SOF_GetLastError());
		else
			alert("验签成功");
	},

	//数据验签
	verifySign(DigestMethod,userID,inData,signed)
	{
		//let DigestMethod = document.getElementById("mech").value;
		//let userID = document.getElementById("userID").value;
		//let inData = document.getElementById("originalData").value;
		//let signed = document.getElementById("signedData").value;
		if(signed == null || signed.length <= 0)
		{
			alert("请先签名后操作");
			return;
		}


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}

		//let

		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		//let selectType;
		let cert = document.getElementById("cerInfo").value;
		if(cert == "")
		{
			cert  = token.SOF_ExportUserCert(nowContainer, nowCertType);
		}

		let ret = token.SOF_SetUserID(userID);
			ret = token.SOF_VerifySignedData(cert, Number(DigestMethod), _Base64encode(inData), signed);
		if(ret != 0)
			alert("验签失败,错误码:" + token.SOF_GetLastError());
		else
			alert("验签成功");
	},

	//数据验签
	verifySign_P7()
	{
		let DigestMethod = document.getElementById("mech").value;
		let userID = document.getElementById("userID").value;
		let inData = document.getElementById("originalData").value;
		let signed = document.getElementById("signedData").value;
		if(signed == null || signed.length <= 0)
		{
			alert("请先签名后操作");
			return;
		}


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}

		//let

		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		//let selectType;
		let cert  = token.SOF_ExportUserCert(nowContainer, nowCertType);

		let ret = token.SOF_SetDigestMethod(Number(DigestMethod));
			ret = token.SOF_SetUserID(userID);
			ret = token.SOF_VerifyDataToPKCS7(signed, _Base64encode(inData), 0);
		if(ret != 0)
			alert("验签失败,错误码:" + token.SOF_GetLastError());
		else
			alert("验签成功");
	},
	//数据加密
	encryptData()
	{
		//let
		//let selectType;
		if(nowCertType == 1)
		{
			alert("请选择加密证书进行加密");
			return ;
		}
		let EncryptMethod = document.getElementById("encrymech").value;
		let iv = document.getElementById("iv").value;
		let inData = document.getElementById("enData").value;


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}



		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}


		let cert  = token.SOF_ExportUserCert(nowContainer, nowCertType);

		token.SOF_SetEncryptMethodAndIV(EncryptMethod, _Base64encode(iv));

		let encrypedData = token.SOF_EncryptDataPKCS7(cert, _Base64encode(inData), inData.length);
		if(encrypedData != null || encrypedData == "")
			document.getElementById("enedData").value = encrypedData;
		else
			alert("加密失败,错误码:" + token.SOF_GetLastError());
	},


	//数据加密
	encryptFile()
	{
		//let
		//let selectType;
		if(nowCertType == 1)
		{
			alert("请选择加密证书进行加密");
			return ;
		}
		let EncryptMethod = document.getElementById("encrymech").value;
		let iv = document.getElementById("iv").value;
		let inData = document.getElementById("enFile").value;
		let OutData = document.getElementById("enDstFile").value;


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}



		let cert  = token.SOF_ExportUserCert(nowContainer, nowCertType);

		token.SOF_SetEncryptMethodAndIV(EncryptMethod,  _Base64encode(iv));

		let envelopData = token.SOF_EncryptFileToPKCS7(cert, inData, OutData, 1);
		if(envelopData != null)
			document.getElementById("enedData").value = envelopData;
		else
			alert("加密失败,错误码:" + token.SOF_GetLastError());
	},

	decryptFile()
	{
		let EncryptMethod = document.getElementById("encrymech").value;
		let iv = document.getElementById("iv").value;
		let outFile = document.getElementById("enFile").value;
		let inData = document.getElementById("enDstFile").value;
		let encrypedData = document.getElementById("enedData").value;
		if(encrypedData == null || encrypedData.length <= 0)
		{
			alert("请先加密后操作");
			return;
		}


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		token.SOF_SetEncryptMethodAndIV(EncryptMethod,  _Base64encode(iv));

		//let
		//let selectType;

		outFile = outFile + ".plainText";
		let decryptedData = token.SOF_DecryptFileToPKCS7(nowContainer, nowCertType, encrypedData, inData, outFile, 1);
		if(decryptedData != 0)
			alert("解密失败,错误码:" + token.SOF_GetLastError());
		else
		{
			document.getElementById("deData").value = outFile;
			alert("解密文件成功，目标文件:" + outFile);
		}
	},

	//数据解密
	decryptData()
	{
		let EncryptMethod = document.getElementById("encrymech").value;
		let iv = document.getElementById("iv").value;
		let encrypedData = document.getElementById("enedData").value;
		if(encrypedData == null || encrypedData.length <= 0)
		{
			alert("请先加密后操作");
			return;
		}


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		token.SOF_SetEncryptMethodAndIV(EncryptMethod,  _Base64encode(iv));

		//let
		//let selectType;

		let decryptedData = token.SOF_DecryptDataPKCS7(nowContainer, nowCertType, encrypedData);
		if(decryptedData != null && decryptedData != "")
			document.getElementById("deData").value = _Base64decode(decryptedData);
		else
			alert("解密失败,错误码:" + token.SOF_GetLastError());
	},



	//对数据做摘要
	digestData()
	{
		let DigestMethod = document.getElementById("digestmech").value;
		let inData = document.getElementById("digestData").value;
		let userID = document.getElementById("userID").value;
		token.SOF_SetDigestMethod(DigestMethod);
		let ret = token.SOF_SetUserID(userID);


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		let digest = token.SOF_DigestData(nowContainer, _Base64encode(inData), inData.length);
		if(digest != null)
			document.getElementById("digestedData").value = digest;
		else
			alert("数据摘要失败,错误码:" + token.SOF_GetLastError());
	},


	GenRemoteUnlockPin()
	{
		let request = token.SOF_GenRemoteUnblockRequest();
		if(request == null || request == "")
		{
			alert("生成解锁请求失败");
			return;
		}

		document.getElementById("remoteUnlockPin").value = request;
	},

	GenUnlockPinResponse()
	{
		let encrypedData = document.getElementById("remoteUnlockPin").value;
		let SoPinData = document.getElementById("SoPinData").value;
		let UserData = document.getElementById("newPinData").value;
		let request = token.SOF_GenResetpwdResponse(encrypedData, SoPinData, UserData);
		if(request == null || request == "")
		{
			alert("生成解锁请求失败");
			return;
		}

		document.getElementById("remoteUnlockPin").value = request;
	},


	RemoteUnlockPin()
	{
		let encrypedData = document.getElementById("remoteUnlockPin").value;
		let request = token.SOF_RemoteUnblockPIN(encrypedData);
		if(request != 0)
		{
			alert("解锁失败");
			return;
		}
		else
		{
			alert("解锁成功");
		}
	},

	exportPubKey(container,certType)
	{
    if((!container) && nowContainer)
		{
      container = nowContainer;
      certType = nowCertType;
		}
		let strPubKey  = token.SOF_ExportPubKey(container, certType);
		if(strPubKey != null && strPubKey != "")
		{
			return  strPubKey;
		}
		else
			//alert("获取公钥失败,错误码:" + token.SOF_GetLastError());
      return null;
	},

	//参数 容器名称  证书类型  带加密数据
	encryptByPubKey(nowContainer,nowCertType,strInput)
	{
    if(!nowCertType)
    {
      nowCertType = 0;
    }
		let strPubKey = this.exportPubKey(nowContainer,nowCertType);

		let strAsymCipher = token.SOF_EncryptByPubKey(strPubKey, _Base64encode(strInput), nowCertType);
		if(strAsymCipher != null && strAsymCipher != "")
		{
			return  strAsymCipher;
		}
		else
			alert("公钥加密失败,错误码:" + token.SOF_GetLastError());
	},

	decryptbyPrvKey()
	{

		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}

		//let

		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		//let selectType;

		let strAsymCipher = document.getElementById("AsymCipher").value;

		let strAsymPlain = token.SOF_DecryptByPrvKey(nowContainer, nowCertType, strAsymCipher);
		if(strAsymPlain != null)
		{
			document.getElementById("AsymPlain").value = _Base64decode(strAsymPlain);
		}
		else
			alert("私钥解密失败,错误码:" + token.SOF_GetLastError());
	},


	//数据签名---所见即所签--交易签名
	TransSignData()
	{
		//let
		//let selectType;
		if(nowCertType == 0)
		{
			alert("请选择签名密钥进行签名");
			return ;
		}
		let DigestMethod = document.getElementById("TransDigestmech").value;
		let userID = document.getElementById("userID").value;
		let inData = document.getElementById("TransPacket").value;
		let ret = token.SOF_SetDigestMethod(Number(DigestMethod));
			ret = token.SOF_SetUserID(userID);


		if(nowContainer)
		{
			alert("请先枚举容器后操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		alert("提示： 当K5上显示灯闪烁时，请在60秒以内及时按下签名按钮……");
		let signed = token.SOF_SignDataInteractive(nowContainer, nowCertType, _Base64encode(inData), inData.length);
		if(signed != null && signed != "")
			document.getElementById("TransSignedData").value = signed;
		else
			alert("签名失败,错误码:" + token.SOF_GetLastError());
	},

	//数据验签---所见即所签--交易签名验证
	TransVerifySignature()
	{
		let DigestMethod = document.getElementById("TransDigestmech").value;
		let userID = document.getElementById("userID").value;
		let inData = document.getElementById("TransPacket").value;
		let signed = document.getElementById("TransSignedData").value;
		if(signed == null || signed.length <= 0)
		{
			alert("请先签名后操作");
			return;
		}


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}

		//let

		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		//let selectType;
		let cert  = token.SOF_ExportUserCert(nowContainer, nowCertType);

		let ret = token.SOF_SetUserID(userID);
			ret = token.SOF_VerifySignedData(cert, Number(DigestMethod), _Base64encode(inData), signed);
		if(ret != 0)
			alert("验签失败,错误码:" + token.SOF_GetLastError());
		else
			alert("验签成功");
	},

	//数据签名----按键Key签名
	BB_signData()
	{
		//let
		//let selectType;
		if(nowCertType == 0)
		{
			alert("请选择签名密钥进行签名");
			return ;
		}
		let DigestMethod = document.getElementById("BB_mech").value;
		let userID = document.getElementById("BB_userID").value;
		let inData = document.getElementById("BB_originalData").value;
		let ret = token.SOF_SetDigestMethod(Number(DigestMethod));
			ret = token.SOF_SetUserID(userID);


		if(nowContainer)
		{
			alert("请先枚举容器后操作");
			return;
		}


		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		alert("提示： 当K5上显示灯闪烁时，请在20秒以内及时按下签名按钮……");

		let signed = token.SOF_SignDataInteractive(nowContainer, nowCertType, _Base64encode(inData), inData.length);
		if(signed != null && signed != "")
			document.getElementById("BB_signedData").value = signed;
		else
			alert("签名失败,错误码:" + token.SOF_GetLastError());
	},

	//数据验签----按键Key验证签名
	BB_verifySign()
	{
		let DigestMethod = document.getElementById("BB_mech").value;
		let userID = document.getElementById("BB_userID").value;
		let inData = document.getElementById("BB_originalData").value;
		let signed = document.getElementById("BB_signedData").value;
		if(signed == null || signed.length <= 0)
		{
			alert("请先签名后操作");
			return;
		}


		if(nowContainer)
		{
			alert("请选择容器操作");
			return;
		}

		//let

		if(nowContainer == null || nowContainer == "")
		{
			alert("请选择容器操作");
			return;
		}

		//let selectType;
		let cert  = token.SOF_ExportUserCert(nowContainer, nowCertType);

		let	ret = token.SOF_SetUserID(userID);
			ret = token.SOF_VerifySignedData(cert, Number(DigestMethod), _Base64encode(inData), signed);
		if(ret != 0)
			alert("验签失败,错误码:" + token.SOF_GetLastError());
		else
			alert("验签成功");
	},

	////////////////////////////////////////////////////////////////////////////////
	//数据对称加密
	SymEncryptData()
	{
		let EncryptMethod = document.getElementById("Sym_encrymech").value;
		let sessionKey = document.getElementById("Sym_SessionKey").value;
		let iv = document.getElementById("Sym_iv").value;
		let inData = document.getElementById("Sym_InData").value;

		token.SOF_SetEncryptMethodAndIV(EncryptMethod, _Base64encode(iv));
		//对输入数据、会话密钥进行Base64编码
		let encrypedData = token.SOF_SymEncryptData(_Base64encode(sessionKey), _Base64encode(inData));
		if(encrypedData != null || encrypedData == "")
			document.getElementById("Sym_enedData").value = encrypedData;
		else
			alert("加密失败,错误码:" + token.SOF_GetLastError());
	},
	//数据对称解密
	SymDecryptData()
	{
		let EncryptMethod = document.getElementById("Sym_encrymech").value;
		let sessionKey = document.getElementById("Sym_SessionKey").value;
		let iv = document.getElementById("Sym_iv").value;

		let inData = document.getElementById("Sym_enedData").value;

		token.SOF_SetEncryptMethodAndIV(EncryptMethod, _Base64encode(iv));

		//对会话密钥进行Base64编码
		let decryptedData = token.SOF_SymDecryptData(_Base64encode(sessionKey), inData);
		if(decryptedData != null && decryptedData != "")
			document.getElementById("Sym_deData").value = _Base64decode(decryptedData);
		else
			alert("解密失败,错误码:" + token.SOF_GetLastError());
	},
	//文件对称加密
	SymEncryptFile()
	{
		let EncryptMethod = document.getElementById("Sym_encrymech").value;
		let sessionKey = document.getElementById("Sym_SessionKey").value;
		let iv = document.getElementById("Sym_iv").value;
		let inFile = document.getElementById("Sym_srcFile").value;
		let outFile = document.getElementById("Sym_DstFile").value;

		token.SOF_SetEncryptMethodAndIV(EncryptMethod, _Base64encode(iv));
		//对会话密钥进行Base64编码
		let ret = token.SOF_SymEncryptFile(_Base64encode(sessionKey), inFile, outFile, 1);
		if(ret == 0)
			alert("加密成功完成.");
		else
			alert("加密失败,错误码:" + token.SOF_GetLastError());
	},
	//文件对称解密
	SymDecryptFile()
	{
		let EncryptMethod = document.getElementById("Sym_encrymech").value;
		let sessionKey = document.getElementById("Sym_SessionKey").value;
		let iv = document.getElementById("Sym_iv").value;
		let inFile = document.getElementById("Sym_DstFile").value;
		let outFile = document.getElementById("Sym_decDstFile").value;

		token.SOF_SetEncryptMethodAndIV(EncryptMethod, _Base64encode(iv));
		//对会话密钥进行Base64编码
		let ret = token.SOF_SymDecryptFile(_Base64encode(sessionKey), inFile, outFile, 1);
		if(ret == 0)
			alert("解密成功完成.");
		else
			alert("解密失败,错误码:" + token.SOF_GetLastError());
	},

	//创建文件，读写权限都是用户权限
	createFile(fileName,length){
        //16930此文件大小取决于本身图片的大小，如果需要写入图片数据进去，请先使用选择图片按钮获取一下图片大小
	    let Rtn = token.SOF_CreateFile(fileName, length, 16, 16);
		if(Rtn!=0){
			alert("创建文件失败！错误码："+token.SOF_GetLastError());
			return false;
		}
		return true;
	},

  //删除文件
  deleteFile(fileName){
    //16930此文件大小取决于本身图片的大小，如果需要写入图片数据进去，请先使用选择图片按钮获取一下图片大小
    let Rtn = token.SOF_DeleteFile(fileName);
    if(Rtn!=0){
      alert("删除文件失败！错误码："+token.SOF_GetLastError());
      return false;
    }
    return true;
  },

	enumFiles()
	{
		let fileList = token.SOF_EnumFiles();
		return fileList;

	},
  checkFile(fileName)
  {
    let fileList = this.enumFiles();
    for(let i = 0; i < fileList.length; i++)
    {
      if(fileList[i]==fileName){
        return true;
      }
    }
    return false;
  },
  //读取文件
	 readFile(fileName)
	{
		let fileData = token.SOF_ReadFile(fileName, 0, 0); //read all data
		if(fileData=="" || fileData==null || fileData==undefined)
		{
			//alert("读取失败,错误码:" + token.SOF_GetLastError());
			return null;
		}
		return  _Base64decode(fileData);
	},

	writeFile(fileName,fileData)
	{

		let ret = token.SOF_WriteFile(fileName, 0, _Base64encode(fileData)); //read all data
		if(ret != 0)
		{
			alert("写入失败,错误码:" + token.SOF_GetLastError());
			return false;
		}
		//alert("写入成功");
    return true;
	},

	btnWriteFile_Img() {
	    let nowDeviceName = document.getElementById("sel_fileList");
	    let index = nowDeviceName.selectedIndex;

	    let fileName = nowDeviceName.options[index].text;
	    let fileData = document.getElementById("base64_output").value;

	    let ret = token.SOF_WriteFile(fileName, 0, _Base64encode(fileData)); //read all data
	    if (ret != 0) {
	        alert("写入失败,错误码:" + token.SOF_GetLastError());
	        return;
	    }
	    alert("写入成功");
	},


	btnReadFile_Img() {
	    document.getElementById("base64_output").value = "";
	    let nowDeviceName = document.getElementById("sel_fileList");
	    let index = nowDeviceName.selectedIndex;
	    if (index < 0) {
	        alert("请选中列表中设备后操作");
	        return;
	    }

	    let fileName = nowDeviceName.options[index].text;
	    let fileData = token.SOF_ReadFile(fileName, 0, 0); //read all data
	    if (fileData == "" || fileData == null || fileData == undefined) {
	        alert("读取失败,错误码:" + token.SOF_GetLastError());
	        return;
	    }
	    document.getElementById("base64_output").value = _Base64decode(fileData);

	},
}
