JAVA语言在中文情况下String没有采用指定编码造成debug正常,release有些机器正常,有些不正常的问题记录

本文探讨了在Windows环境下,使用Eclipse运行正常但发布为Jar后出现MD5算法结果不一致的问题。通过代码分析,发现原因是String.getBytes()未指定字符集导致的平台默认字符集差异。通过修改代码,指定使用UTF-8字符集,解决了跨平台运行的一致性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实际项目中,出现在windows下,通过eclipse启动运行正常,然而export发布的jar运行不正常的情况。通过跟踪分析。发现是由

String.getBytes 造成MD5算法结果不一致。

未修改前代码段如下:

private static String c(String requestParams,int len){
		String sign = "";
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(requestParams.getBytes());
			String updateLen = String.format("%d",len + 48);
			messageDigest.update(updateLen.getBytes());
			byte[] bytesDigest = messageDigest.digest();
			
			char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
			int j = bytesDigest.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = bytesDigest[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			sign = new String(str);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sign;
	}

修改后的代码:

	private static String c(String requestParams,int len){
		String sign = "";
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(requestParams.getBytes("utf-8"));
			String updateLen = String.format("%d",len + 48);
			messageDigest.update(updateLen.getBytes("utf-8"));
			byte[] bytesDigest = messageDigest.digest();
			
			char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
			int j = bytesDigest.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = bytesDigest[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			sign = new String(str);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sign;
	}

原因:

 /**
     * Encodes this {@code String} into a sequence of bytes using the
     * platform's default charset, storing the result into a new byte array.
     *
     * <p> The behavior of this method when this string cannot be encoded in
     * the default charset is unspecified.  The {@link
     * java.nio.charset.CharsetEncoder} class should be used when more control
     * over the encoding process is required.
     *
     * @return  The resultant byte array
     *
     * @since      JDK1.1
     */
    public byte[] getBytes() {
        return StringCoding.encode(value, 0, value.length);
    }

未指定的话,将会采用平台默认的字符集,而这是不可控的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值