如何在java中散列和编码mpesa密码

问题描述 投票:0回答:2

我正在尝试动态生成一个密码,以便与每个api请求一起发送到mpesa apis。根据文档,我需要首先连接提供的密钥与时间戳和商家ID,然后执行sha256以获取哈希密码,然后我应该编码到base 64但是在Java中执行此操作会返回错误的编码字符串,而类似的过程和代码在PHP中工作,我可能在哪里出错?

import org.apache.commons.codec.binary.Base64;
import org.apache.cxf.headers.Header;
import org.apache.cxf.jaxb.JAXBDataBinding;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;



public class CheckoutHeaderBuilder {

    public static Header buildHeader(String merchantId, String passKey, String timestamp) throws JAXBException, NoSuchAlgorithmException, UnsupportedEncodingException {
    String hashedEncodedPass = Base64.encodeBase64String(MessageDigest.getInstance("SHA-256").digest((merchantId + passKey + timestamp).getBytes("utf-8")));

    List<Header> headers = new ArrayList<>();
    CheckOutHeader checkOutHeader = new CheckOutHeader();
    checkOutHeader.setTIMESTAMP(timestamp);
    checkOutHeader.setMERCHANTID(merchantId);
    checkOutHeader.setPASSWORD(hashedEncodedPass);
    return new Header(new QName("tns:ns", "CheckOutHeader"), checkOutHeader, new JAXBDataBinding(CheckOutHeader.class));

    }

}
java sha mpesa
2个回答
1
投票

您好Japheth Ongeri Inkalimeva,您不必使用SHA256加密。发送Lipa na M-Pesa Online Payment API请求时,您可能不需要必要时设置新密码。

我已修改您的代码以删除SHA256加密。

import org.apache.commons.codec.binary.Base64;
import org.apache.cxf.headers.Header;
import org.apache.cxf.jaxb.JAXBDataBinding;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


public class CheckoutHeaderBuilder  {

    public static Header buildHeader(String merchantId, String passKey, String timestamp) throws JAXBException, NoSuchAlgorithmException, UnsupportedEncodingException {
    String hashedEncodedPass = Base64.encodeBase64String((merchantId + passKey + timestamp).getBytes("utf-8"));

    List<Header> headers = new ArrayList<>();
    CheckOutHeader checkOutHeader = new CheckOutHeader();
    checkOutHeader.setTIMESTAMP(timestamp);
    checkOutHeader.setMERCHANTID(merchantId);
    checkOutHeader.setPASSWORD(hashedEncodedPass);
    return new Header(new QName("tns:ns", "CheckOutHeader"), checkOutHeader, new JAXBDataBinding(CheckOutHeader.class));

    }

}

1
投票

示例编码SHA256

import java.nio.charset.StandardCharsets;
import com.google.common.hash.Hashing;

String password = “123456”;
Hashing.sha256().hashString(password, StandardCharsets.UTF_8).toString();

希望能帮到你

© www.soinside.com 2019 - 2024. All rights reserved.