Java Code Examples for com.alipay.api.internal.util.StringUtils#isEmpty()

The following examples show how to use com.alipay.api.internal.util.StringUtils#isEmpty() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static String getResponseCharset(String ctype) {
    String charset = DEFAULT_CHARSET;

    if (!StringUtils.isEmpty(ctype)) {
        String[] params = ctype.split(";");
        for (String param : params) {
            param = param.trim();
            if (param.startsWith("charset")) {
                String[] pair = param.split("=", 2);
                if (pair.length == 2) {
                    if (!StringUtils.isEmpty(pair[1])) {
                        charset = pair[1].trim();
                    }
                }
                break;
            }
        }
    }

    return charset;
}
 
Example 2
protected String doSign(String content, String charset, String privateKey) throws Exception {
    PrivateKey priKey = getPrivateKeyFromPKCS8(AlipayConstants.SIGN_TYPE_RSA,
            new ByteArrayInputStream(privateKey.getBytes()));

    Signature signature = Signature.getInstance(getSignAlgorithm());

    signature.initSign(priKey);

    if (StringUtils.isEmpty(charset)) {
        signature.update(content.getBytes());
    } else {
        signature.update(content.getBytes(charset));
    }

    byte[] signed = signature.sign();

    return new String(Base64.encodeBase64(signed));
}
 
Example 3
Source Project: jeewx   File: Dispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 进入事件执行器
 * 
 * @param bizContentJson
 * @return
 */
private static ActionExecutor getEnterEventTypeExecutor(JSONObject bizContentJson) {
    try {

        JSONObject param = JSONObject.fromObject(bizContentJson.get("ActionParam"));
        JSONObject scene = JSONObject.fromObject(param.get("scene"));

        if (!StringUtils.isEmpty(scene.getString("sceneId"))) {

            //自定义场景参数进入服务窗事件
            return new InAlipayDIYQRCodeEnterExecutor(bizContentJson);
        } else {

            //普通进入服务窗事件
            return new InAlipayEnterExecutor(bizContentJson);
        }
    } catch (Exception exception) {
        //无法解析sceneId的情况作为普通进入服务窗事件
        return new InAlipayEnterExecutor(bizContentJson);
    }
}
 
Example 4
Source Project: alipay-sdk-java-all   File: Message.java    License: Apache License 2.0 6 votes vote down vote up
public static void addSign(Message message, String appPrivateKey) {
    if (!("message".equals(message.getxType()) && MsgConstants.MSG_CMD_PRODUCE.equals(message.getxCmd()))) {
        return;
    }
    if (StringUtils.isEmpty(message.getxSignType()) || StringUtils.isEmpty(message.getxCharset())
            || StringUtils.isEmpty(appPrivateKey)) {
        throw new IllegalArgumentException("can not add sign, miss x-signType or x-charset.");
    }

    String signContent = genDataPart(message);
    if (StringUtils.isEmpty(signContent)) {
        throw new IllegalArgumentException("can not add sign, miss signContent.");
    }
    try {
        message.setxSign(AlipaySignature.rsaSign(signContent, appPrivateKey, message.getxCharset(),
                message.getxSignType()));
    } catch (Throwable t) {
        throw new IllegalArgumentException("add sign fail. exception:" + t.getMessage());
    }
}
 
Example 5
/**
 * @see com.alipay.api.internal.mapping.Converter#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
        throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    SignItem signItem = new SignItem();

    // 获取签名
    String sign = getSign(responseBody);
    signItem.setSign(sign);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    signItem.setSignSourceDate(signSourceData);

    return signItem;
}
 
Example 6
Source Project: jeewx   File: AlipayCoreService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 事件执行
 * @param service
 * @param bizContentJson
 * @return
 * @throws MyException
 */
private String doEventExcute(String service, JSONObject bizContentJson) throws MyException {

	// 1. 获取事件类型
	String eventType = bizContentJson.getString("EventType");

	if (StringUtils.isEmpty(eventType)) {
		throw new MyException("无法取得事件类型");
	}

	// 2.根据事件类型再次区分服务类型
	// 2.1 激活验证开发者模式
	if (AlipayServiceNameConstants.ALIPAY_CHECK_SERVICE.equals(service)&& eventType.equals(AlipayServiceEventConstants.VERIFYGW_EVENT)) {
		return new InAlipayVerifyExecutor().execute();
		// 2.2 其他消息通知类
	} else if (AlipayServiceNameConstants.ALIPAY_PUBLIC_MESSAGE_NOTIFY.equals(service)) {
		return getMsgNotifyExecutor(eventType, bizContentJson);
		// 2.3 对于后续支付宝可能新增的类型,统一默认返回AKC响应
	} else {
		return doSendDefaultMessage(bizContentJson);
	}
}
 
Example 7
private static boolean sm2Verify(byte[] signature, byte[] message, PublicKey publicKey, String sm2UserId) {
    try {
        String userId = "1234567812345678";
        if (!StringUtils.isEmpty(sm2UserId)) {
            userId = sm2UserId;
        }
        Signature sm2SignEngine = Signature.getInstance("SM3withSM2");
        sm2SignEngine.setParameter(new SM2ParameterSpec(Strings.toByteArray(userId)));
        sm2SignEngine.initVerify(publicKey);
        sm2SignEngine.update(message);
        return sm2SignEngine.verify(signature);
    } catch (Exception e) {
        AlipayLogger.logBizError(e);
        return false;
    }
}
 
Example 8
private static String getResponseCharset(String ctype) {
    String charset = DEFAULT_CHARSET;

    if (!StringUtils.isEmpty(ctype)) {
        String[] params = ctype.split(";");
        for (String param : params) {
            param = param.trim();
            if (param.startsWith("charset")) {
                String[] pair = param.split("=", 2);
                if (pair.length == 2) {
                    if (!StringUtils.isEmpty(pair[1])) {
                        charset = pair[1].trim();
                    }
                }
                break;
            }
        }
    }

    return charset;
}
 
Example 9
Source Project: pay   File: JsonConverter.java    License: Apache License 2.0 6 votes vote down vote up
/** 
 * @see com.alipay.api.internal.mapping.Converter#getSignItem(com.alipay.api.AlipayRequest, String)
 */
public SignItem getSignItem(AlipayRequest<?> request, String responseBody)
                                                                          throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {

        return null;
    }

    SignItem signItem = new SignItem();

    // 获取签名
    String sign = getSign(responseBody);
    signItem.setSign(sign);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    signItem.setSignSourceDate(signSourceData);

    return signItem;
}
 
Example 10
public String sign(String content, String charset, String privateKey) throws AlipayApiException {
    try {
        if (StringUtils.isEmpty(content)) {
            throw new AlipayApiException("待签名内容不可为空");
        }
        if (StringUtils.isEmpty(privateKey)) {
            throw new AlipayApiException("私钥不可为空");
        }
        if (StringUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        return doSign(content, charset, privateKey);
    } catch (Exception e) {

        String errorMessage = getAsymmetricType() + "签名遭遇异常,请检查私钥格式是否正确。" + e.getMessage() +
                " content=" + content + ",charset=" + charset + ",privateKeySize=" + privateKey.length();
        throw new AlipayApiException(errorMessage,e);
    }

}
 
Example 11
public boolean verify(String content, String charset, String publicKey, String sign) throws AlipayApiException {
    try {
        if (StringUtils.isEmpty(content)) {
            throw new AlipayApiException("待验签内容不可为空");
        }
        if (StringUtils.isEmpty(publicKey)) {
            throw new AlipayApiException("公钥不可为空");
        }
        if (StringUtils.isEmpty(sign)) {
            throw new AlipayApiException("签名串不可为空");
        }
        if (StringUtils.isEmpty(charset)) {
            charset = DEFAULT_CHARSET;
        }
        return doVerify(content, charset, publicKey, sign);
    } catch (Exception e) {

        String errorMessage = getAsymmetricType() + "验签遭遇异常,请检查公钥格式是否正确。" + e.getMessage() +
                " content=" + content + ",charset=" + charset + ",publicKey=" + publicKey;
        throw new AlipayApiException(errorMessage,e);
    }
}
 
Example 12
protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
    String charset = getResponseCharset(conn.getContentType());
    InputStream es = conn.getErrorStream();
    if (es == null) {
        return getStreamAsString(conn.getInputStream(), charset);
    } else {
        String msg = getStreamAsString(es, charset);
        if (StringUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
        } else {
            throw new IOException(msg);
        }
    }
}
 
Example 13
Source Project: alipay-sdk-java-all   File: Message.java    License: Apache License 2.0 5 votes vote down vote up
private static String genDataPart(Message message) {
    StringBuilder dataSb = new StringBuilder();
    dataSb.append("{\"header\":{");
    if (!StringUtils.isEmpty(message.getAppId())) {
        dataSb.append("\"appId\":\"").append(message.getAppId()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getMsgApi())) {
        dataSb.append("\"msgApi\":\"").append(message.getMsgApi()).append("\",");
    }
    if (',' == dataSb.charAt(dataSb.length() - 1)) {
        dataSb.deleteCharAt(dataSb.length() - 1);
    }
    dataSb.append("}");
    if (!StringUtils.isEmpty(message.getBizContent())) {
        JSONValidator jsonValidator = new JSONValidator(new ExceptionErrorListener());
        if (!jsonValidator.validate(message.getBizContent())) {
            throw new IllegalArgumentException("bizContent json format illegal.");
        }
        dataSb.append(",\"content\":").append(message.getBizContent());
    }
    dataSb.append("}");
    String data = dataSb.toString();
    if ("{\"header\":{}}".equals(data)) {
        data = null;
    }
    return data;
}
 
Example 14
/**
 * @see com.alipay.api.internal.mapping.Converter#getCertItem(com.alipay.api.AlipayRequest, String)
 */
public CertItem getCertItem(AlipayRequest<?> request, String responseBody)
        throws AlipayApiException {

    // 响应为空则直接返回
    if (StringUtils.isEmpty(responseBody)) {
        return null;
    }

    CertItem certItem = new CertItem();

    JSONReader reader = new JSONValidatingReader(new ExceptionErrorListener());
    Object rootObj = reader.read(responseBody);
    Map<?, ?> rootJson = (Map<?, ?>) rootObj;

    // 获取签名
    String sign = (String) rootJson.get(AlipayConstants.SIGN);
    certItem.setSign(sign);

    //获取证书序列号
    String cert = (String) rootJson.get(AlipayConstants.ALIPAY_CERT_SN);
    certItem.setCert(cert);

    // 签名源串
    String signSourceData = getSignSourceData(request, responseBody);
    certItem.setSignSourceDate(signSourceData);

    return certItem;
}
 
Example 15
public AbstractAlipayClient(String serverUrl, String appId, String format,
                            String charset, String signType, String encryptType) {
    this(serverUrl, appId, format, charset, signType);
    if (!StringUtils.isEmpty(encryptType)) {
        this.encryptType = encryptType;
    }
}
 
Example 16
protected String doEncrypt(String plainText, String charset, String publicKey) throws Exception {
    int maxEncrypt = getMaxEncryptBlockSize();
    PublicKey pubKey = getPublicKeyFromX509(AlipayConstants.SIGN_TYPE_RSA,
            new ByteArrayInputStream(publicKey.getBytes()));
    Cipher cipher = Cipher.getInstance(AlipayConstants.SIGN_TYPE_RSA);
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    byte[] data = StringUtils.isEmpty(charset) ? plainText.getBytes()
            : plainText.getBytes(charset);
    int inputLen = data.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段加密
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > maxEncrypt) {
            cache = cipher.doFinal(data, offSet, maxEncrypt);
        } else {
            cache = cipher.doFinal(data, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        i++;
        offSet = i * maxEncrypt;
    }
    byte[] encryptedData = Base64.encodeBase64(out.toByteArray());
    out.close();

    return StringUtils.isEmpty(charset) ? new String(encryptedData)
            : new String(encryptedData, charset);
}
 
Example 17
public AbstractAlipayClient(String serverUrl, String appId, String format,
                            String charset, String signType,
                            String certPath, String certContent,
                            String alipayPublicCertPath, String alipayPublicCertContent,
                            String rootCertPath, String rootCertContent,
                            String proxyHost, int proxyPort, String encryptType) throws AlipayApiException {
    this(serverUrl, appId, format, charset, signType);
    if (!StringUtils.isEmpty(encryptType)) {
        this.encryptType = encryptType;
    }
    this.proxyHost = proxyHost;
    this.proxyPort = proxyPort;
    //读取根证书(用来校验本地支付宝公钥证书失效后自动从网关下载的新支付宝公钥证书是否有效)
    this.rootCertContent = StringUtils.isEmpty(rootCertContent) ? readFileToString(rootCertPath) : rootCertContent;
    //alipayRootCertSN根证书序列号
    if (AlipayConstants.SIGN_TYPE_SM2.equals(signType)) {
        this.alipayRootSm2CertSN = AntCertificationUtil.getRootCertSN(this.rootCertContent, "SM2");
    } else {
        this.alipayRootCertSN = AntCertificationUtil.getRootCertSN(this.rootCertContent);
        if (StringUtils.isEmpty(this.alipayRootCertSN)) {
            throw new AlipayApiException("AlipayRootCert Is Invalid");
        }
    }
    //获取应用证书
    this.cert = StringUtils.isEmpty(certContent) ? AntCertificationUtil.getCertFromPath(certPath)
            : AntCertificationUtil.getCertFromContent(certContent);
    //获取支付宝公钥证书
    X509Certificate alipayPublicCert = StringUtils.isEmpty(alipayPublicCertContent) ?
            AntCertificationUtil.getCertFromPath(alipayPublicCertPath) :
            AntCertificationUtil.getCertFromContent(alipayPublicCertContent);

    //appCertSN为最终发送给网关的应用证书序列号
    this.appCertSN = AntCertificationUtil.getCertSN(cert);
    if (StringUtils.isEmpty(this.appCertSN)) {
        throw new AlipayApiException("AppCert Is Invalid");
    }
    //alipayCertSN为支付宝公钥证书序列号
    this.alipayCertSN = AntCertificationUtil.getCertSN(alipayPublicCert);
    //将公钥证书以序列号为key存入map
    ConcurrentHashMap<String, X509Certificate> alipayPublicCertMap = new ConcurrentHashMap<String, X509Certificate>();
    alipayPublicCertMap.put(alipayCertSN, alipayPublicCert);
    this.alipayPublicCertMap = alipayPublicCertMap;
    //获取支付宝公钥以序列号为key存入map
    PublicKey publicKey = alipayPublicCert.getPublicKey();
    ConcurrentHashMap<String, String> alipayPublicKeyMap = new ConcurrentHashMap<String, String>();
    alipayPublicKeyMap.put(alipayCertSN, Base64.encodeBase64String(publicKey.getEncoded()));
    this.alipayPublicKeyMap = alipayPublicKeyMap;
}
 
Example 18
Source Project: alipay-sdk-java-all   File: Message.java    License: Apache License 2.0 4 votes vote down vote up
public static String toStr(Message message) throws IllegalArgumentException {
    if (message == null) {
        return null;
    }
    if (!StringUtils.isEmpty(message.getBody())) {
        return message.getBody();
    }
    if (StringUtils.isEmpty(message.getxType())) {
        throw new IllegalArgumentException("xType required. " + message);
    }
    StringBuilder sb = new StringBuilder();
    sb.append("{\"protocol\":{");
    sb.append("\"x-type\":\"").append(message.getxType()).append("\",");
    if (!StringUtils.isEmpty(message.getxCmd())) {
        sb.append("\"x-cmd\":\"").append(message.getxCmd()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getxMessageId())) {
        sb.append("\"x-msgId\":\"").append(message.getxMessageId()).append("\",");
    }
    if (message.getxTimestamp() != null) {
        sb.append("\"x-timestamp\":\"").append(message.getxTimestamp()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getxVersion())) {
        sb.append("\"x-version\":\"").append(message.getxVersion()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getxStatus())) {
        sb.append("\"x-status\":\"").append(message.getxStatus()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getxCode())) {
        sb.append("\"x-code\":\"").append(message.getxCode()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getxError())) {
        sb.append("\"x-error\":\"").append(message.getxError()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getxCharset())) {
        sb.append("\"x-charset\":\"").append(message.getxCharset()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getxSignType())) {
        sb.append("\"x-signType\":\"").append(message.getxSignType()).append("\",");
    }
    if (!StringUtils.isEmpty(message.getxSign())) {
        sb.append("\"x-sign\":\"").append(message.getxSign()).append("\",");
    }
    if (',' == sb.charAt(sb.length() - 1)) {
        sb.deleteCharAt(sb.length() - 1);
    }
    sb.append("}");
    String data = genDataPart(message);
    if (data != null) {
        sb.append(",\"data\":").append(data);
    }
    sb.append("}");
    message.setBody(sb.toString());
    return message.getBody();
}
 
Example 19
Source Project: pay   File: DefaultAlipayClient.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *  检查响应签名
 * 
 * @param request
 * @param parser
 * @param responseBody
 * @param responseIsSucess
 * @throws AlipayApiException
 */
private <T extends AlipayResponse> void checkResponseSign(AlipayRequest<T> request,
                                                          AlipayParser<T> parser,
                                                          String responseBody,
                                                          boolean responseIsSucess) throws AlipayApiException {
    // 针对成功结果且有支付宝公钥的进行验签
    if (!StringUtils.isEmpty(this.alipayPublicKey)) {

        SignItem signItem = parser.getSignItem(request, responseBody);

        if (signItem == null) {

            throw new AlipayApiException("sign check fail: Body is Empty!");
        }

        if (responseIsSucess
            || (!responseIsSucess && !StringUtils.isEmpty(signItem.getSign()))) {

            boolean rsaCheckContent = AlipaySignature.rsaCheck(signItem.getSignSourceDate(),
                signItem.getSign(), this.alipayPublicKey, this.charset, this.sign_type);

            if (!rsaCheckContent) {

                // 针对JSON \/问题,替换/后再尝试做一次验证
                if (!StringUtils.isEmpty(signItem.getSignSourceDate())
                    && signItem.getSignSourceDate().contains("\\/")) {

                    String srouceData = signItem.getSignSourceDate().replace("\\/", "/");

                    boolean jsonCheck = AlipaySignature.rsaCheck(srouceData, signItem.getSign(),
                        this.alipayPublicKey, this.charset, this.sign_type);

                    if (!jsonCheck) {
                        throw new AlipayApiException(
                            "sign check fail: check Sign and Data Fail!JSON also!");
                    }
                } else {

                    throw new AlipayApiException("sign check fail: check Sign and Data Fail!");
                }
            }
        }

    }
}
 
Example 20
Source Project: alipay-sdk   File: DefaultAlipayClient.java    License: Apache License 2.0 4 votes vote down vote up
/**
 *  检查响应签名
 * 
 * @param request
 * @param parser
 * @param responseBody
 * @param responseIsSucess
 * @throws AlipayApiException
 */
private <T extends AlipayResponse> void checkResponseSign(AlipayRequest<T> request,
                                                          AlipayParser<T> parser,
                                                          String responseBody,
                                                          boolean responseIsSucess) throws AlipayApiException {
    // 针对成功结果且有支付宝公钥的进行验签
    if (!StringUtils.isEmpty(this.alipayPublicKey)) {

        SignItem signItem = parser.getSignItem(request, responseBody);

        if (signItem == null) {

            throw new AlipayApiException("sign check fail: Body is Empty!");
        }

        if (responseIsSucess
            || (!responseIsSucess && !StringUtils.isEmpty(signItem.getSign()))) {

            boolean rsaCheckContent = AlipaySignature.rsaCheck(signItem.getSignSourceDate(),
                signItem.getSign(), this.alipayPublicKey, this.charset, this.signType);

            if (!rsaCheckContent) {

                // 针对JSON \/问题,替换/后再尝试做一次验证
                if (!StringUtils.isEmpty(signItem.getSignSourceDate())
                    && signItem.getSignSourceDate().contains("\\/")) {

                    String srouceData = signItem.getSignSourceDate().replace("\\/", "/");

                    boolean jsonCheck = AlipaySignature.rsaCheck(srouceData, signItem.getSign(),
                        this.alipayPublicKey, this.charset, this.signType);

                    if (!jsonCheck) {
                        throw new AlipayApiException(
                            "sign check fail: check Sign and Data Fail!JSON also!");
                    }
                } else {

                    throw new AlipayApiException("sign check fail: check Sign and Data Fail!");
                }
            }
        }

    }
}