Java代码SHA1加密案例

说明:这里只展示核心代码,具体的字符串拼接格式不做案例

	@Test
	public void junitTest() throws DigestException {
		String string = "bizCode=c010101&channelCode=c010105";
		try {  
            //指定sha1算法  
            MessageDigest digest = MessageDigest.getInstance("SHA-1");  
            digest.update(string.getBytes());  
            //获取字节数组  
            byte messageDigest[] = digest.digest();  
            // Create Hex String  
            StringBuffer hexString = new StringBuffer();  
            // 字节数组转换为 十六进制 数  
            for (int i = 0; i < messageDigest.length; i++) {  
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);  
                if (shaHex.length() < 2) {  
                    hexString.append(0);  
                }  
                hexString.append(shaHex);  
            }  
            //转小写
            System.out.println(hexString.toString().toLowerCase());
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
            throw new DigestException("签名错误!");  
        } 
	}


你可能感兴趣的:(Java)