convert a hexadecimal string to a byte string

public static byte[] HexStringToByteArray(String s) throws IllegalArgumentException {
    int len = s.length();
    if (len % 2 == 1) {
        throw new IllegalArgumentException("Hex string must have even number of characters");
    }
    byte[] data = new byte[len / 2]; // Allocate 1 byte per 2 hex characters
    for (int i = 0; i < len; i += 2) {
        // Convert each character into a integer (base-16), then bit-shift into place
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}
import java.io.InputStream; import java.security.DigestInputStream; import java.security.MessageDigest; public class MD5Utils { /** * Used to build output as Hex */ private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); String inputToLog = input; if (inputToLog.length() > 500) { inputToLog = inputToLog.substring(0, 500)+"... [truncated in log]"; } return returnString; } public static String computeMD5(InputStream stream) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); DigestInputStream digestStream = new DigestInputStream(stream, digest); byte[] buf = new byte[20480]; while (digestStream.read(buf) != -1) { ; //digest is updating } } catch (Exception e) { throw new RuntimeException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); return returnString; } /** * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. * The returned array will be double the length of the passed array, as it takes two characters to represent any * given byte. * * @param data * a byte[] to convert to Hex characters * @return A char[] containing hexadecimal characters */ private static char[] encodeHex(byte[] data) { int l = data.length; char[] out = new char[l << 1]; // two characters form the hex value. for (int i = 0, j = 0; i < l; i++) { out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4]; out[j++] = DIGITS_LOWER[0x0F & data[i]]; } return out; } } 将这段代码改造成python
最新发布
09-20
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值