更新时间:2025-11-13 gmt 08:00
java代码示例(总)-j9九游会登录
package com.huawei.cbc.cbcmarketplacecommentservice.ability.jsonutils;
import java.io.unsupportedencodingexception;
import java.security.invalidalgorithmparameterexception;
import java.security.invalidkeyexception;
import java.security.nosuchalgorithmexception;
import java.security.securerandom;
import java.util.hashmap;
import java.util.iterator;
import java.util.map;
import java.util.set;
import java.util.treemap;
import javax.crypto.badpaddingexception;
import javax.crypto.cipher;
import javax.crypto.illegalblocksizeexception;
import javax.crypto.keygenerator;
import javax.crypto.mac;
import javax.crypto.nosuchpaddingexception;
import javax.crypto.secretkey;
import javax.crypto.spec.ivparameterspec;
import javax.crypto.spec.secretkeyspec;
import org.apache.commons.codec.binary.base64;
import org.apache.commons.lang.stringutils;
public class encrypttest {
// 编码方式
private static final string charset = "utf-8";
// 加密类型 256加密(aes256_cbc_pkcs5padding)时传1,128加密(aes128_cbc_pkcs5padding)时传2
private static final string encrypt_type_256 = "1";
// 商家信息界面的key值(需要替换为自己的key)
private static final string access_key = "xxxxxxx";
public static void main(string args[]) throws exception {
// ------------商家验证请求---------------
// 将请求转换为map,模拟从request中获取参数操作(request.getparametermap())
map paramsmap = gettesturlmap();
// 加密类型 256加密(aes256_cbc_pkcs5padding),128加密(aes128_cbc_pkcs5padding)
system.out.println("商家验证请求:" verificaterequestparams(paramsmap, access_key, 256));
// 需要加密的手机、密码等
string needencryptstr = "15905222222";
string encryptstr = generatesaasusernameorpwd(needencryptstr, access_key, encrypt_type_256);
system.out.println("加密的手机、密码等:" encryptstr);
// 解密
string decryptstr = decryptmobilephoneoremail(access_key, encryptstr, encrypt_type_256);
system.out.println("解密的手机、密码等:" decryptstr);
// body签名
string needencryptbody =
"{\"resultcode\":\"00000\",\"resultmsg\":\"购买成功\",\"encrypttype\":\"1\",\"instanceid\":\"000bd4e1-5726-4ce9-8fe4-fd081a179304\",\"appinfo\"{\"username\":\"3lqvu8363e5o4zqwynxyjgwz8y gacu0rpm0wq==\",\"password\":\"ry31aenr5gmcfmt3ig1hw7uf1hk09mual2sgxa==\"}}";
string encryptbody = generateresponsebodysignature(access_key, needencryptbody);
system.out.println("body签名:" encryptbody);
}
private static map gettesturlmap() {
// 原始请求:http://bzapic.natappfree.cc?activity=newinstance&businessid=61e834ba-7b97-4418-b8f7-e5345137278c&customerid=68cbc86abc2018ab880d92f36422fa0e&expiretime=20200727153156&orderid=cs1906666666abcde&productid=00301-666666-0--0&testflag=1×tamp=20200727073711903&authtoken=gzbfjf9lhrbci3bfvi slincnobf6qa7is1fvjegyq=
map paramsmap = new hashmap();
paramsmap.put("activity", new string[] {"newinstance"});
paramsmap.put("businessid", new string[] {"61e834ba-7b97-4418-b8f7-e5345137278c"});
paramsmap.put("customerid", new string[] {"68cbc86abc2018ab880d92f36422fa0e"});
paramsmap.put("expiretime", new string[] {"20200727153156"});
paramsmap.put("orderid", new string[] {"cs1906666666abcde"});
paramsmap.put("productid", new string[] {"00301-666666-0--0"});
paramsmap.put("testflag", new string[] {"1"});
paramsmap.put("timestamp", new string[] {"20200727073711903"});
paramsmap.put("authtoken", new string[] {"gzbfjf9lhrbci3bfvi slincnobf6qa7is1fvjegyq="});
return paramsmap;
}
/** * 校验通知消息的合法性 * * @param accesskey 接入码 * @param encryptlength 加密长度 * @return 验证结果 */ public static boolean verificaterequestparams(mapparamsmap, string accesskey, int encryptlength) { string timestamp = null; string authtoken = null; string[] timestamparray = paramsmap.get("timestamp"); if (null != timestamparray && timestamparray.length > 0) { timestamp = timestamparray[0]; } string[] authtokenarray = paramsmap.get("authtoken"); if (null != authtokenarray && authtokenarray.length > 0) { authtoken = authtokenarray[0]; } // 对剩下的参数进行排序,拼接成加密内容 map sortedmap = new treemap (); sortedmap.putall(paramsmap); sortedmap.remove("authtoken"); stringbuffer strbuffer = new stringbuffer(); set keyset = sortedmap.keyset(); iterator iter = keyset.iterator(); while (iter.hasnext()) { string key = iter.next(); string value = sortedmap.get(key)[0]; strbuffer.append("&").append(key).append("=").append(value); } // 修正消息体,去除第一个参数前面的& string reqparams = strbuffer.tostring().substring(1); string key = accesskey timestamp; string signature = null; try { signature = generateresponsebodysignature(key, reqparams); } catch (invalidkeyexception | nosuchalgorithmexception | illegalstateexception | unsupportedencodingexception e) { // todo auto-generated catch block } return authtoken.equals(signature); } public static string generateresponsebodysignature(string key, string body) throws invalidkeyexception, nosuchalgorithmexception, illegalstateexception, unsupportedencodingexception { return base_64(hmacsha256(key, body)); } public static byte[] hmacsha256(string mackey, string macdata) { try { try { secretkeyspec secret = new secretkeyspec(mackey.getbytes(charset), "hmacsha256"); mac mac = mac.getinstance("hmacsha256"); mac.init(secret); return mac.dofinal(macdata.getbytes(charset)); } catch (unsupportedencodingexception e) { } catch (invalidkeyexception e) { } } catch (nosuchalgorithmexception e) { } return new byte[0]; } // 商家body签名 public static string generatesaasusernameorpwd(string isvbody, string decryptaccesskey, string sencrypttype) { string iv = getrandomchars(16); int iencrypttype = 0; try { iencrypttype = integer.parseint(sencrypttype); } catch (numberformatexception exception) { iencrypttype = 1; } int encrypttype; if (1 == iencrypttype) { encrypttype = 256; } else { encrypttype = 128; } string isvencryptbody = encryptaescbcencode(isvbody, decryptaccesskey, iv, encrypttype); return iv isvencryptbody; }
/**
* aes cbc 256位加密
*
* @param content 加密内容
* @param key 加密密钥
* @param iv 加密盐值
* @return 加密结果
*/
public static string encryptaescbcencode(string content, string key, string iv, int encrypttype) {
if (stringutils.isempty(content) || stringutils.isempty(key) || stringutils.isempty(iv)) {
return null;
}
try {
byte[] encrypcontent =
encryptaescbc(content.getbytes(charset), key.getbytes(charset), iv.getbytes(charset), encrypttype);
if (null != encrypcontent) {
return base_64(encrypcontent);
} else {
return null;
}
} catch (unsupportedencodingexception e) {
return null;
}
}
public static byte[] encryptaescbc(byte[] content, byte[] keybytes, byte[] iv, int encrypttype) {
try {
keygenerator keygenerator = keygenerator.getinstance("aes");
securerandom securerandom = securerandom.getinstance("sha1prng");
securerandom.setseed(keybytes);
keygenerator.init(encrypttype, securerandom);
secretkey key = keygenerator.generatekey();
cipher cipher = cipher.getinstance("aes/cbc/pkcs5padding");
cipher.init(cipher.encrypt_mode, key, new ivparameterspec(iv));
return cipher.dofinal(content);
} catch (exception e) {
}
return null;
}
public static string base_64(byte[] bytes) {
try {
return new string(base64.encodebase64(bytes), charset);
} catch (unsupportedencodingexception e) {
return null;
}
}
static string decryptmobilephoneoremail(string accesskey, string encryptstr, string sencrypttype) {
string iv = encryptstr.substring(0, 16);
int iencrypttype = 1;
try {
iencrypttype = integer.parseint(sencrypttype);
} catch (numberformatexception exception) {
exception.printstacktrace();
}
int encrypttype;
if (1 == iencrypttype) {
encrypttype = 256;
} else {
encrypttype = 128;
}
string decryptbody = null;
try {
decryptbody = decryptaescbcencode(encryptstr.substring(16), accesskey, iv, encrypttype);
} catch (exception e) {
e.printstacktrace();
return decryptbody;
}
return decryptbody;
}
public static string decryptaescbcencode(string content, string key, string iv, int encrypttype)
throws invalidkeyexception, nosuchalgorithmexception, nosuchpaddingexception,
invalidalgorithmparameterexception, illegalblocksizeexception, badpaddingexception {
if (stringutils.isempty(content) || stringutils.isempty(key) || stringutils.isempty(iv)) {
return null;
}
return new string(decryptaescbc(org.apache.commons.codec.binary.base64.decodebase64(content.getbytes()),
key.getbytes(), iv.getbytes(), encrypttype));
}
public static byte[] decryptaescbc(byte[] content, byte[] keybytes, byte[] iv, int encrypttype)
throws nosuchalgorithmexception, nosuchpaddingexception, invalidkeyexception,
invalidalgorithmparameterexception, illegalblocksizeexception, badpaddingexception {
keygenerator keygenerator = keygenerator.getinstance("aes");
securerandom securerandom = securerandom.getinstance("sha1prng");
securerandom.setseed(keybytes);
keygenerator.init(encrypttype, securerandom);
secretkey key = keygenerator.generatekey();
cipher cipher = cipher.getinstance("aes/cbc/pkcs5padding");
cipher.init(cipher.decrypt_mode, key, new ivparameterspec(iv));
byte[] result = cipher.dofinal(content);
return result;
}
/**
* 获取随机字符串
*
* @param length 字符串长度
* @return
* @author d00420944
*/
public static string getrandomchars(int length) {
stringbuffer randomcharsbuf = new stringbuffer(1024);
securerandom random = new securerandom();
for (int i = 0; i < length; i ) {
// 字母和数字中随机
if (random.nextint(2) % 2 == 0) {
// 输出是大写字母还是小写字母
int letterindex = random.nextint(2) % 2 == 0 ? 65 : 97;
randomcharsbuf.append((char) (random.nextint(26) letterindex));
} else {
randomcharsbuf.append(string.valueof(random.nextint(10)));
}
}
string randomchars = randomcharsbuf.tostring();
return randomchars;
}
}
父主题:
相关文档
意见反馈
文档内容是否对您有帮助?
提交成功!非常感谢您的反馈,我们会继续努力做到更好!
您可在查看反馈及问题处理状态。
系统繁忙,请稍后重试
如您有其它疑问,您也可以通过华为云社区问答频道来与我们联系探讨