回调验签请求结果
@param str 验签请求结果字符串
@param pubKey 公钥
@param callback 回调
768920
private static void callbackResult(String str, String pubKey, ICheckLoginSignHandler callback){
        JSONObject json = null;
        try {
            json = new JSONObject(str);
        } catch (JSONException e) {
            callback.onCheckResult(null, "json parse fail:" + e.getMessage(), false);
            return;
        }

        String rtnCode = json.optString("rtnCode");
        String errMsg = json.optString("errMsg");
        String ts = json.optString("ts");
        String rtnSign = json.optString("rtnSign");

        if("0".equals(rtnCode))
        {
            String nosign = "rtnCode=" + RSAUtil.urlEncode(rtnCode) + "&ts=" + RSAUtil.urlEncode(ts);
            boolean s = RSAUtil.doCheck(nosign, rtnSign, pubKey);
            callback.onCheckResult(rtnCode, "request success", s);
        } else {
            callback.onCheckResult(rtnCode, "request sign fail:" + errMsg, false);
        }
    }
124897
function(p, callback) {

		var _this = this;
		var error = _this.error;

		// This has to go through a POST request
		if (!_this.isEmpty(p.data) && !('FileList' in window) && _this.hasBinary(p.data)) {

			// Disable XHR and JSONP
			p.xhr = false;
			p.jsonp = false;
		}

		// Check if the browser and service support CORS
		var cors = this.request_cors(function() {
			// If it does then run this...
			return ((p.xhr === undefined) || (p.xhr && (typeof (p.xhr) !== 'function' || p.xhr(p, p.query))));
		});

		if (cors) {

			formatUrl(p, function(url) {

				var x = _this.xhr(p.method, url, p.headers, p.data, callback);
				x.onprogress = p.onprogress || null;

				// Windows Phone does not support xhr.upload, see #74
				// Feature detect
				if (x.upload && p.onuploadprogress) {
					x.upload.onprogress = p.onuploadprogress;
				}

			});

			return;
		}

		// Clone the query object
		// Each request modifies the query object and needs to be tared after each one.
		var _query = p.query;

		p.query = _this.clone(p.query);

		// Assign a new callbackID
		p.callbackID = _this.globalEvent();

		// JSONP
		if (p.jsonp !== false) {

			// Clone the query object
			p.query.callback = p.callbackID;

			// If the JSONP is a function then run it
			if (typeof (p.jsonp) === 'function') {
				p.jsonp(p, p.query);
			}

			// Lets use JSONP if the method is 'get'
			if (p.method === 'get') {

				formatUrl(p, function(url) {
					_this.jsonp(url, callback, p.callbackID, p.timeout);
				});

				return;
			}
			else {
				// It's not compatible reset query
				p.query = _query;
			}

		}

		// Otherwise we're on to the old school, iframe hacks and JSONP
		if (p.form !== false) {

			// Add some additional query parameters to the URL
			// We're pretty stuffed if the endpoint doesn't like these
			p.query.redirect_uri = p.redirect_uri;
			p.query.state = JSON.stringify({callback:p.callbackID});

			var opts;

			if (typeof (p.form) === 'function') {

				// Format the request
				opts = p.form(p, p.query);
			}

			if (p.method === 'post' && opts !== false) {

				formatUrl(p, function(url) {
					_this.post(url, p.data, opts, callback, p.callbackID, p.timeout);
				});

				return;
			}
		}

		// None of the methods were successful throw an error
		callback(error('invalid_request', 'There was no mechanism for handling this request'));

		return;

		// Format URL
		// Constructs the request URL, optionally wraps the URL through a call to a proxy server
		// Returns the formatted URL
		function formatUrl(p, callback) {

			// Are we signing the request?
			var sign;

			// OAuth1
			// Remove the token from the query before signing
			if (p.authResponse && p.authResponse.oauth && parseInt(p.authResponse.oauth.version, 10) === 1) {

				// OAUTH SIGNING PROXY
				sign = p.query.access_token;

				// Remove the access_token
				delete p.query.access_token;

				// Enfore use of Proxy
				p.proxy = true;
			}

			// POST body to querystring
			if (p.data && (p.method === 'get' || p.method === 'delete')) {
				// Attach the p.data to the querystring.
				_this.extend(p.query, p.data);
				p.data = null;
			}

			// Construct the path
			var path = _this.qs(p.url, p.query);

			// Proxy the request through a server
			// Used for signing OAuth1
			// And circumventing services without Access-Control Headers
			if (p.proxy) {
				// Use the proxy as a path
				path = _this.qs(p.oauth_proxy, {
					path: path,
					access_token: sign || '',

					// This will prompt the request to be signed as though it is OAuth1
					then: p.proxy_response_type || (p.method.toLowerCase() === 'get' ? 'redirect' : 'proxy'),
					method: p.method.toLowerCase(),
					suppress_response_codes: true
				});
			}

			callback(path);
		}
	}
49229
function(publicKey, privateKey, callback) {
        this.publicKeyExists(publicKey, function onPubKeyExistsResponse(err, exists) {
            if (err) {
                return callback(err);
            }

            if (exists) {
                return callback(new Error(
                    'Public key `' + publicKey + '` already exists'
                ));
            }

            this.editPublicKey(publicKey, privateKey, callback);
        }.bind(this));

        return this;
    }
849894
public static boolean checkSign(PurchaseInfoResult result, String pubKey) {

        if (result == null || pubKey == null) {
            return false;
        }

        StringBuilder sb = new StringBuilder();

        Map<String, Object> paramsa = new HashMap<String, Object>();
        paramsa.put("pageCount", result.getPageCount());
        paramsa.put("rtnCode", result.getRtnCode());
        sb.append(getNoSign(paramsa, false)).append('&');

        List<PurchaseInfo> purchaseInfos = result.getPurchaseInfoList();
        if (purchaseInfos != null) {
            for (PurchaseInfo info : purchaseInfos) {
                if (info != null) {
                    Map<String, Object> paramsaSub = new HashMap<String, Object>();
                    //必选参数
                    paramsaSub.put("requestId", info.getRequestId());
                    paramsaSub.put("merchantId", info.getMerchantId());
                    paramsaSub.put("appId", info.getAppId());
                    paramsaSub.put("productId", info.getProductId());
                    paramsaSub.put("tradeTime", info.getTradeTime());

                    sb.append(getNoSign(paramsaSub, false)).append('&');
                }
            }
        }

        if (sb.charAt(sb.length()-1) == '&') {
            sb.deleteCharAt(sb.length()-1);
        }

        return doCheck(sb.toString(), result.getSign(), pubKey);
    }
1241905
function PairPublicKey(keyData) {
  this.__key = (typeof keyData === 'object' ? keyData : null);
  this.__encoded = (typeof keyData === 'string' ? keyData : null);
}
879647
private static PublicKey getPublicKey(String modulus, String exponent) {
		try {
			BigInteger b1 = new BigInteger(modulus);
			BigInteger b2 = new BigInteger(exponent);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
			RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
			return keyFactory.generatePublic(keySpec);
		} catch (Exception e) {
			LogUtil.writeErrorLog("构造RSA公钥失败：" + e);
			return null;
		}
	}
1178013
public static PrivateKey stringToRSAPrivateKey (String str)
    {
        try {
            BigInteger mod = new BigInteger(str.substring(0, str.indexOf(SPLIT)), 16);
            BigInteger exp = new BigInteger(str.substring(str.indexOf(SPLIT) + 1), 16);
            RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(mod, exp);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(keySpec);
        } catch (NumberFormatException nfe) {
            log.warning("Failed to read key from string.", "str", str, nfe);
        } catch (GeneralSecurityException gse) {
            log.warning("Failed to read key from string.", "str", str, gse);
        }
        return null;
    }
230128
private void doit(String[] args)
    {
        try
        {
            // load parameters from the commandline
            loadParameters(args);

            // Try to load the private key
            importKeyPair();
        }
        catch (Exception e)
        {
            System.out.println("Exception: " + e.getMessage());
            e.printStackTrace();
            
            System.exit(23);
        }
    }
117535
public int setString(long pos, String str) throws SQLException {
    int bytePosition = utf8Position((int) pos - 1);
    super.setBytes(bytePosition + 1 - offset, str.getBytes(StandardCharsets.UTF_8));
    return str.length();
  }
294199
public static boolean checkSign(ProductPayResultInfo rst, String pubKey) {

        if (rst == null || pubKey == null) {
            return false;
        }

        Map<String, Object> paramsa = new HashMap<String, Object>();

        // 必选参数
        paramsa.put("returnCode", rst.getReturnCode());
        paramsa.put("merchantId", rst.getMerchantId());
        paramsa.put("requestId", rst.getRequestId());
        paramsa.put("productNo", rst.getProductNo());
        paramsa.put("microsAmount", rst.getMicrosAmount());
        paramsa.put("currency", rst.getCurrency());
        paramsa.put("country", rst.getCountry());
        paramsa.put("time", rst.getTime());

        // 可选参数
        paramsa.put("orderID", rst.getOrderID());
        paramsa.put("errMsg", rst.getErrMsg());

        String noSignStr = getNoSign(paramsa, false);
        return doCheck(noSignStr, rst.getSign(), pubKey);
    }
710312
void onPushTokenResult(int rstCode, TokenResult result) {
        HMSAgentLog.i("getToken:callback=" + StrUtils.objDesc(handler) +" retCode=" + rstCode);
        if (handler != null) {
            new Handler(Looper.getMainLooper()).post(new CallbackCodeRunnable(handler, rstCode));
            handler = null;
        }
        retryTimes = MAX_RETRY_TIMES;
    }
972408
function (str) {
    var self = this;

    str = stringify(str);
    str = str.substr(1, str.length - 2);

    if (this.lastBufferedIdx == this.buf.length && this.bufferedConcatenationCount < 100) {
      if (this.lastBufferedType === 'code') {
        this.lastBuffered += ' + "';
        this.bufferedConcatenationCount++;
      }
      this.lastBufferedType = 'text';
      this.lastBuffered += str;
      this.buf[this.lastBufferedIdx - 1] = 'pug_html = pug_html + ' + this.bufferStartChar + this.lastBuffered + '";';
    } else {
      this.bufferedConcatenationCount = 0;
      this.buf.push('pug_html = pug_html + "' + str + '";');
      this.lastBufferedType = 'text';
      this.bufferStartChar = '"';
      this.lastBuffered = str;
      this.lastBufferedIdx = this.buf.length;
    }
  }
213279
private static void appendAuthParam(StringBuilder sb, String key, String value) {
		if (sb.length() > 0) {
			sb.append(",");
		}
		sb.append(key);
		sb.append("=\"");
		sb.append(value);
		sb.append("\"");
	}
865495
function(params, callbacks, recursiveCallback) {
                /**
                 * + ChatMessage        {object}
                 *    - token           {string}
                 *    - tokenIssuer     {string}
                 *    - type            {int}
                 *    - typeCode        {string}
                 *    - messageType     {int}
                 *    - subjectId       {long}
                 *    - uniqueId        {string}
                 *    - content         {string}
                 *    - time            {long}
                 *    - medadata        {string}
                 *    - systemMedadata  {string}
                 *    - repliedTo       {long}
                 */

                var asyncPriority = (params.asyncPriority > 0)
                    ? params.asyncPriority
                    : msgPriority;

                var messageVO = {
                    type: params.chatMessageVOType,
                    token: token,
                    tokenIssuer: 1
                };

                var threadId = params.subjectId;

                if (params.typeCode) {
                    messageVO.typeCode = params.typeCode;
                }
                else if (generalTypeCode) {
                    messageVO.typeCode = generalTypeCode;
                }

                if (params.messageType) {
                    messageVO.messageType = params.messageType;
                }

                if (params.subjectId) {
                    messageVO.subjectId = params.subjectId;
                }

                if (params.content) {
                    if (typeof params.content == 'object') {
                        messageVO.content = JSON.stringify(params.content);
                    }
                    else {
                        messageVO.content = params.content;
                    }
                }

                if (params.metadata) {
                    messageVO.metadata = params.metadata;
                }

                if (params.systemMetadata) {
                    messageVO.systemMetadata = params.systemMetadata;
                }

                if (params.repliedTo) {
                    messageVO.repliedTo = params.repliedTo;
                }

                var uniqueId;

                if (typeof params.uniqueId != 'undefined') {
                    uniqueId = params.uniqueId;
                }
                else if (params.chatMessageVOType !== chatMessageVOTypes.PING) {
                    uniqueId = Utility.generateUUID();
                }

                if (Array.isArray(uniqueId)) {
                    messageVO.uniqueId = JSON.stringify(uniqueId);
                }
                else {
                    messageVO.uniqueId = uniqueId;
                }

                if (typeof callbacks == 'object') {
                    if (callbacks.onSeen || callbacks.onDeliver || callbacks.onSent) {
                        if (!threadCallbacks[threadId]) {
                            threadCallbacks[threadId] = {};
                        }

                        threadCallbacks[threadId][uniqueId] = {};

                        sendMessageCallbacks[uniqueId] = {};

                        if (callbacks.onSent) {
                            sendMessageCallbacks[uniqueId].onSent = callbacks.onSent;
                            threadCallbacks[threadId][uniqueId].onSent = false;
                            threadCallbacks[threadId][uniqueId].uniqueId = uniqueId;
                        }

                        if (callbacks.onSeen) {
                            sendMessageCallbacks[uniqueId].onSeen = callbacks.onSeen;
                            threadCallbacks[threadId][uniqueId].onSeen = false;
                        }

                        if (callbacks.onDeliver) {
                            sendMessageCallbacks[uniqueId].onDeliver = callbacks.onDeliver;
                            threadCallbacks[threadId][uniqueId].onDeliver = false;
                        }

                    }
                    else if (callbacks.onResult) {
                        messagesCallbacks[uniqueId] = callbacks.onResult;
                    }
                }
                else if (typeof callbacks == 'function') {
                    messagesCallbacks[uniqueId] = callbacks;
                }

                /**
                 * Message to send through async SDK
                 *
                 * + MessageWrapperVO  {object}
                 *    - type           {int}       Type of ASYNC message based on content
                 *    + content        {string}
                 *       -peerName     {string}    Name of receiver Peer
                 *       -receivers[]  {long}      Array of receiver peer ids (if you use this, peerName will be ignored)
                 *       -priority     {int}       Priority of message 1-10, lower has more priority
                 *       -messageId    {long}      Id of message on your side, not required
                 *       -ttl          {long}      Time to live for message in milliseconds
                 *       -content      {string}    Chat Message goes here after stringifying
                 *    - trackId        {long}      Tracker id of message that you receive from DIRANA previously (if you are replying a sync message)
                 */

                var data = {
                    type: (parseInt(params.pushMsgType) > 0)
                        ? params.pushMsgType
                        : 3,
                    content: {
                        peerName: serverName,
                        priority: asyncPriority,
                        content: JSON.stringify(messageVO),
                        ttl: (params.messageTtl > 0)
                            ? params.messageTtl
                            : messageTtl
                    }
                };

                asyncClient.send(data, function(res) {
                    if (res.hasError && callbacks) {
                        if (typeof callbacks == 'function') {
                            callbacks(res);
                        }
                        else if (typeof callbacks == 'object' && typeof callbacks.onResult == 'function') {
                            callbacks.onResult(res);
                        }

                        if (messagesCallbacks[uniqueId]) {
                            delete messagesCallbacks[uniqueId];
                        }
                    }
                });

                sendPingTimeout && clearTimeout(sendPingTimeout);
                sendPingTimeout = setTimeout(function() {
                    ping();
                }, chatPingMessageInterval);

                recursiveCallback && recursiveCallback();

                return {
                    uniqueId: uniqueId,
                    threadId: threadId,
                    participant: userInfo,
                    content: params.content
                };
            }
112639
public static boolean doCheck(String noSignStr, String sign, String publicKey) {

        if (sign == null || noSignStr == null || publicKey == null) {
            return false;
        }

        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey, Base64.DEFAULT);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update(noSignStr.getBytes(CHARSET));

            return signature.verify(Base64.decode(sign, Base64.DEFAULT));
        } catch (Exception e) {
            //  这里是安全算法，为避免出现异常时泄露加密信息，这里不打印具体日志
            HMSAgentLog.e("doCheck error");
        }
        return false;
    }
462896
public void append(String str) {
	if (str == null) return;
	int restLength = buffer.length - pos;
	if (str.length() < restLength) {
	    str.getChars(0, str.length(), buffer, pos);
	    pos += str.length();
	}
	else {
	    str.getChars(0, restLength, buffer, pos);
	    curr.next = new Entity(buffer);
	    curr = curr.next;
	    length += buffer.length;
	    buffer = new char[(buffer.length > str.length() - restLength) ? buffer.length : str.length() - restLength];

	    str.getChars(restLength, str.length(), buffer, 0);
	    pos = str.length() - restLength;

	}
    }
1107738
public static String encryptData(String dataString, String encoding,
			PublicKey key) {
		/** 使用公钥对密码加密 **/
		byte[] data = null;
		try {
			data = encryptData(key, dataString.getBytes(encoding));
			return new String(SecureUtil.base64Encode(data), encoding);
		} catch (Exception e) {
			LogUtil.writeErrorLog(e.getMessage(), e);
			return "";
		}
	}