1. java版本接入样例

下载地址:https://cosmos.momocdn.com/cosmosdocs/04/F2/04F22919-0E65-4AB3-6A26-99C6C98EE93320200521.zip

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: wang.jianwen
 * @create: 2020-04-24 17:31
 **/
public class CheckAuthUtils {

    private static byte[] getIV(String appKey) {
        return DigestUtils.md5Hex(appKey.getBytes(StandardCharsets.UTF_8))
                .substring(0, 16).getBytes();
    }

    private static String encrypt(String strToEncrypt, String appKey) {
        try {
            IvParameterSpec ivspec = new IvParameterSpec(getIV(appKey));
            SecretKeySpec secretKey = new SecretKeySpec(appKey.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
            byte[] doFinal = cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8));
            Base64 base64 = new Base64();
            byte[] e1 = base64.encode(doFinal);
            return base64.encodeToString(e1);
        } catch (Exception e) {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }


    public static String decrypt(String strToDecrypt, String appKey) {
        try {
            IvParameterSpec ivspec = new IvParameterSpec(getIV(appKey));
            SecretKeySpec secretKey = new SecretKeySpec(appKey.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
            Base64 base64 = new Base64();
            byte[] d1 = base64.decode(strToDecrypt);
            byte[] d2 = base64.decode(d1);
            byte[] aFinal = cipher.doFinal(d2);
            return new String(aFinal, Charset.defaultCharset());
        } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }
}
@Copyright © cosmos 2019 all right reserved,powered by Gitbook修订时间: 2020-05-22 12:43:22

results matching ""

    No results matching ""