python 和 java MD5 不一致的问题笔记

说明:合作方使用的java的提供的示例MD5看如下:

package com.iread.example.util;



import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public final class SecurityUtil {

    public SecurityUtil() {
    }

    public static byte[] getDigestSHA(String source) throws Exception {
        return getDigestSHA(source.getBytes("UTF8"));
    }

    public static byte[] getDigestSHA(String source, String charset)
            throws Exception {
        return getDigestSHA(source.getBytes(charset));
    }

    public static byte[] getDigestSHA(byte source[]) throws Exception {
        MessageDigest thisMD = MessageDigest.getInstance("SHA");
        byte digest[] = thisMD.digest(source);
        return digest;
    }

    public static String shaEncoding(byte source[]) throws Exception {
        return encodeHex(getDigestSHA(source));
    }

    public static String shaEncoding(String source) throws Exception {
        return encodeHex(getDigestSHA(source));
    }

    public static String shaEncoding(String source, String charset)
            throws Exception {
        return encodeHex(getDigestSHA(source, charset));
    }

    public static byte[] getDigestMD5(String source) throws Exception {
        return getDigestMD5(source, "UTF8");
    }

    public static byte[] getDigestMD5(String source, String charset)
            throws Exception {
        return getDigestMD5(source.getBytes(charset));
    }

    public static byte[] getDigestMD5(byte source[]) throws Exception {
        MessageDigest thisMD = MessageDigest.getInstance("MD5");
        return thisMD.digest(source);
    }

    public static String md5encoding(String source) throws Exception {
        return encodeHex(getDigestMD5(source));
    }

    public static String md5encoding(String source, String charset)
            throws Exception {
        return encodeHex(getDigestMD5(source, charset));
    }

    public static String md5encoding(byte source[]) throws Exception {
        return encodeHex(getDigestMD5(source));
    }

    public static final String encodeHex(byte bytes[]) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            if ((bytes[i] & 255) < 16)
                buf.append("0");
            buf.append(Long.toString(bytes[i] & 255, 16));
        }

        return buf.toString();
    }

    public static final byte[] encryptAESByCBC(String sKey, String ivParam,
            String sSrc) throws Exception {
        return encryptAESByCBC(sKey, ivParam.getBytes(), sSrc);
    }

    public static final byte[] encryptAESByCBC(String sKey, byte ivParam[],
            String sSrc) throws Exception {
        return encryptAESByCBC(sKey.getBytes(), ivParam, sSrc);
    }

    public static final byte[] encryptAESByCBC(byte keyBytes[], byte ivBytes[],
            String sSrc) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        cipher.init(1, skeySpec, iv);
        byte encrypted[] = cipher.doFinal(sSrc.getBytes("utf-8"));
        return encrypted;
    }

    public static final String decryptAESByCBC(String sKey, String ivParam,
            byte encrBytes[]) throws Exception {
        return decryptAESByCBC(sKey, ivParam.getBytes(), encrBytes);
    }

    public static final String decryptAESByCBC(String sKey, byte ivBytes[],
            byte encrBytes[]) throws Exception {
        return decryptAESByCBC(sKey.getBytes("ASCII"), ivBytes, encrBytes);
    }

    public static final String decryptAESByCBC(byte keyBytes[], byte ivBytes[],
            byte encrBytes[]) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        cipher.init(2, skeySpec, iv);
        byte original[] = cipher.doFinal(encrBytes);
        String originalString = new String(original, "utf-8");
        return originalString;
    }

    public static KeyPair genKey() throws Exception {
        long mySeed = System.currentTimeMillis();
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        random.setSeed(mySeed);
        keyGen.initialize(1024, random);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    }

    public static byte[] encryptByRSA(byte pubKeyInByte[], byte data[])
            throws Exception {
        KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec pub_spec = new X509EncodedKeySpec(pubKeyInByte);
        java.security.PublicKey pubKey = mykeyFactory.generatePublic(pub_spec);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(1, pubKey);
        return cipher.doFinal(data);
    }

    public static byte[] encryptByRSA(byte pubKeyInByte[], String data)
            throws Exception {
        return encryptByRSA(pubKeyInByte, data.getBytes("UTF8"));
    }

    public static byte[] decryptByRSA(byte privKeyInByte[], byte data[])
            throws Exception {
        PKCS8EncodedKeySpec priv_spec = new PKCS8EncodedKeySpec(privKeyInByte);
        KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
        java.security.PrivateKey privKey = mykeyFactory
                .generatePrivate(priv_spec);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(2, privKey);
        return cipher.doFinal(data);
    }

    public static byte[] decryptByRSA(byte privKeyInByte[], String data)
            throws Exception {
        return decryptByRSA(privKeyInByte, data.getBytes("UTF8"));
    }

    public static byte[] encodeAES(byte content[], String password)
            throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes());
        kgen.init(128, random);
        SecretKey secretKey = kgen.generateKey();
        byte enCodeFormat[] = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(1, key);
        byte result[] = cipher.doFinal(content);
        return result;
    }

    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1)
                hex = (new StringBuilder(String.valueOf('0'))).append(hex)
                        .toString();
            sb.append(hex.toUpperCase());
        }

        return sb.toString();
    }

    public static void main(String args[]) throws Exception {
        System.out.println(md5encoding("1"));
    }

    private static final String algorithm_rsa = "RSA";
    private static final String algorithm_aes = "AES";
    private static final String algorithm_sha = "SHA";
    private static final String algorithm_md5 = "MD5";
    private static final String algorithm_des = "DESede";
    private static final String _charset = "UTF8";
    private static final String transformation = "RSA/ECB/PKCS1Padding";
}

其中最关键的是:

   chargeSign = Base64.encode( SecurityUtil.getDigestMD5(signStr));
调用的是:


    public static byte[] getDigestMD5(String source) throws Exception {
        return getDigestMD5(source, "UTF8");
    }

对于的python 版本的加密应该是也是返回byte的:

返回16进制的str形式


def md5(text):
    """md5加密函数"""
    md5 = hashlib.md5()
    if not isinstance(text, bytes):
        text = str(text).encode('utf-8')
    md5.update(text)
    return md5.hexdigest()

# hexdigest实际上返回的是16进制的str形式,digest返回的是bytes


返回的:bytes

def md5_digest(text):
    """md5加密函数"""
    md5 = hashlib.md5()
    if not isinstance(text, bytes):
        text = str(text).encode('utf-8')
    md5.update(text)
    return md5.digest()

所有最终的形式应该是:

def md5_digest(text):
    """md5加密函数"""
    md5 = hashlib.md5()
    if not isinstance(text, bytes):
        text = str(text).encode('utf-8')
    md5.update(text)
    return md5.digest()


def base64_encode_digest(text):
    """进行base64编码处理"""
    return base64.b64encode(text)

然后调用:
    chargeSign = str(encrypt_helper.base64_encode_digest(encrypt_helper.md5_digest(strkeys)))
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,618评论 0 10
  • /**ios常见的几种加密方法: 普通的加密方法是讲密码进行加密后保存到用户偏好设置( [NSUserDefaul...
    彬至睢阳阅读 2,837评论 0 7
  • pyton review 学习指南 https://www.zhihu.com/question/29138020...
    孙小二wuk阅读 1,015评论 0 2
  • python学习笔记 声明:学习笔记主要是根据廖雪峰官方网站python学习学习的,另外根据自己平时的积累进行修正...
    renyangfar阅读 2,941评论 0 10
  • 与你相遇,原只是朋友在朋友圈里的一篇趣闻。文末写着你的名字,才想起来我已多年不曾提笔写东西了。以前写东西为了人生,...
    谣言止殇阅读 147评论 0 3