java mac.dofinal_java中消息摘要算法mac的实现

java中消息摘要算法mac的实现

jdk中mac的实现

package hmac;

import javax.crypto.KeyGenerator;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

public class HmacMD5Jdk {

public static void main(String[] args) throws Exception{

String source = "test";

/**随机产生秘钥或者指定秘钥 */

//随机产生秘钥

KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");

byte[] key =keyGenerator.generateKey().getEncoded();

//或者去指定秘钥

key = "aaaaa".getBytes();

Mac mac = Mac.getInstance("HmacMD5");

mac.init(new SecretKeySpec(key, "HmacMD5"));

mac.update(source.getBytes());

System.out.println(Hex.encodeHexString(mac.doFinal()));

}

}

bc(boucy castle)中mac的实现:

package hmac;

import org.bouncycastle.crypto.digests.MD5Digest;

import org.bouncycastle.crypto.macs.HMac;

import org.bouncycastle.crypto.params.KeyParameter;

import org.bouncycastle.util.encoders.Hex;

public class HmacMD5Bc {

public static void main(String[] args) {

String source = "test";

HMac hmac = new HMac(new MD5Digest());

hmac.init(new KeyParameter("aaaaa".getBytes()));

hmac.update(source.getBytes(), 0, source.getBytes().length);

byte[] resultBytes = new byte[hmac.getMacSize()];

hmac.doFinal(resultBytes, 0);

System.out.println(Hex.toHexString(resultBytes));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
本代码是C#方法,通过开源C#BouncyCastle加密组件进行DES加解密。和JAVA DES加解密互通。JAVA方法如下: public static String desEncrypt(String source, String desKey) throws Exception { try { // 从原始密匙数据创建DESKeySpec对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(new DESKeySpec(desKey.getBytes())); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey); // 现在,获取数据并加密 byte[] destBytes = cipher.doFinal(source.getBytes()); StringBuilder hexRetSB = new StringBuilder(); for (byte b : destBytes) { String hexString = Integer.toHexString(0x00ff & b); hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString); } return hexRetSB.toString(); } catch (Exception e) { throw new Exception("DES加密发生错误", e); } } public static String desDecrypt(String source, String desKey) throws Exception { // 解密数据 byte[] sourceBytes = new byte[source.length() / 2]; for (int i = 0; i < sourceBytes.length; i++) { sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16); } try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(new DESKeySpec(desKey.getBytes())); Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey); // 现在,获取数据并解密 byte[] destBytes = cipher.doFinal(sourceBytes); return new String(destBytes); } catch (Exception e) { throw new Exception("DES解密发生错误", e); } }
文件加密解密算法(Java源码) java,file,算法,加密解密,java源码 package com.crypto.encrypt; import java.security.SecureRandom; import java.io.*; import javax.crypto.spec.DESKeySpec; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.Cipher; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.NoSuchPaddingException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import java.lang.reflect.Constructor; import java.security.spec.KeySpec; import java.lang.reflect.InvocationTargetException; public class EncryptData { private String keyfile=null; public EncryptData() { } public EncryptData(String keyfile) { this.keyfile=keyfile; } /** * 加密文件 * @param filename String 源路径 * @param filenamekey String 加密后的路径 */ public void createEncryptData(String filename,String filenamekey) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalStateException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, IOException { //验证keyfile if(keyfile==null || keyfile.equals("")) { throw new NullPointerException("无效的key文件路径"); } encryptData(filename,filenamekey); } /** * 加密类文件 * @param filename String 原始的类文件 * @param encryptfile String 加密后的类文件 * @throws IOException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws IllegalStateException */ private void encryptData(String filename,String encryptfile) throws IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, IllegalStateException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException { byte data[]=Util.readFile(filename); // 执行加密操作 byte encryptedClassData[] = getencryptData(data); // 保存加密后的文件,覆盖原有的类文件。 Util.writeFile(encryptedClassData,encryptfile); } /** * 直接获得加密数据 * @param bytes byte[] * @throws IllegalStateException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws NoSuchPaddingException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws InstantiationException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws SecurityException * @throws ClassNotFoundException * @throws IOException * @return byte[] */ public byte[] createEncryptData(byte[] bytes) throws IllegalStateException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException, NoSuchAlgorithmException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException, IOException { bytes=getencryptData(bytes); return bytes; } private byte[] getencryptData(byte[] bytes) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, InvocationTargetException, IllegalArgumentException, IllegalAccessException, InstantiationException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, IllegalStateException { // 产生一个可信任的随机数源 SecureRandom sr = new SecureRandom(); //从密钥文件key Filename得到密钥数据 byte[] rawKeyData = Util.readFile(keyfile); // 从原始密钥数据创建DESKeySpec对象 Class classkeyspec=Class.forName(Util.getValue("keyspec")); Constructor constructor = classkeyspec.getConstructor(new Class[]{byte[].class}); KeySpec dks = (KeySpec) constructor.newInstance(new Object[]{rawKeyData}); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(Util.getAlgorithm()); SecretKey key = keyFactory.generateSecret(dks); // Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance(Util.getAlgorithm()); // 用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, key, sr); // 执行加密操作 bytes = cipher.doFinal(bytes); // 返回字节数组 return bytes; } /** * 设置key文件路径 * @param keyfile String */ public void setKeyFile(String keyfile) { this.keyfile=keyfile; } }
智能识别收货地址Java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Encoder; class Demo { public static String calcAuthorization(String source, String secretId, String secretKey, String datetime) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { String signStr = "x-date: " + datetime + "\n" + "x-source: " + source; Mac mac = Mac.getInstance("HmacSHA1"); Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm()); mac.init(sKey); byte[] hash = mac.doFinal(signStr.getBytes("UTF-8")); String sig = new BASE64Encoder().encode(hash); String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\""; return auth; } public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException { StringBuilder sb = new StringBuilder(); for (Map.Entry<?, ?> entry : map.entrySet()) { if (sb.length() > 0) { sb.append("&"); } sb.append(String.format("%s=%s", URLEncoder.encode(entry.getKey().toString(), "UTF-8"), URLEncoder.encode(entry.getValue().toString(), "UTF-8") )); } return sb.toString(); } public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { //云市场分配的密钥Id String secretId = "xxxx"; //云市场分配的密钥Key String secretKey = "xxxx"; String source = "market"; Calendar cd = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Lo
以下是基于 JavaMac实现 HMAC-MD5 算法的示例代码: ```java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class HmacMd5 { public static void main(String[] args) { String message = "Hello, world!"; String key = "secret"; String hmac = hmacMd5(message, key); System.out.println(hmac); } public static String hmacMd5(String message, String key) { try { // 创建 Mac 对象 Mac mac = Mac.getInstance("HmacMD5"); // 创建 SecretKeySpec 对象 SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacMD5"); // 初始化 Mac 对象 mac.init(keySpec); // 计算 HMAC 值 byte[] hmacBytes = mac.doFinal(message.getBytes()); // 对 HMAC 值进行 Base64 编码 return Base64.getEncoder().encodeToString(hmacBytes); } catch (NoSuchAlgorithmException | InvalidKeyException e) { e.printStackTrace(); return null; } } } ``` 在示例代码,我们通过调用 `hmacMd5` 方法来计算 HMAC-MD5 值。该方法接受两个参数:`message` 表示要计算 HMAC 值的消息,`key` 表示 HMAC 密钥。在方法内部,我们首先创建 Mac 对象,然后创建 SecretKeySpec 对象,并使用 HMAC 密钥初始化 Mac 对象。接着,我们调用 Mac 对象的 `doFinal` 方法来计算 HMAC 值,并将其转换为 Base64 编码的字符串返回。最后,在 `main` 方法,我们演示了如何使用该方法来计算 HMAC-MD5 值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值