当前位置: 移动技术网 > IT编程>开发语言>Java > Java常用加密算法实例总结

Java常用加密算法实例总结

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例总结了java常用加密算法。分享给大家供大家参考,具体如下:

项目中第一次深入地了解到加密算法的使用,现第一阶段结束,将使用到的加密算法和大家分享一下:

首先还是先给大家普及一下常用加密算法的基础知识

基本的单向加密算法

base64 严格地说,属于编码格式,而非加密算法
md5(message digest algorithm 5,信息摘要算法)
sha(secure hash algorithm,安全散列算法)

复杂的加密算法

rsa(算法的名字以发明者的名字命名:ron rivest, adishamir 和leonard adleman)
des/3des(digital signature algorithm,数字签名)

国密算法

sm2/sm4(是由国家密码管理局编制的一种商用密码分组标准对称算法)

使用方法:

base64

public static byte[] encode2base64(byte[] bytes) {
    byte[] bts = base64.encodebase64(bytes);
    return bts;
}
public static byte[] decode2base64(string str) {
    byte[] bts = base64.decodebase64(str);
    return bts;
}

md5

public static string md5(string str) {
    try {
      messagedigest digest = messagedigest.getinstance("md5");
      return new string(digest.digest(str.getbytes()));
    } catch (nosuchalgorithmexception e) {
      e.printstacktrace();
    }
    return "";
}

sha-1

public static byte[] sha1tobytes(string str) {
    try {
      messagedigest digest = messagedigest.getinstance("sha-1");
      byte[] bts = digest.digest(str.getbytes());
      return bts;
    } catch (exception e) {
      e.printstacktrace();
    }
    return null;
}

des/3des

public static byte[] encryptmode(string keystr, byte[] src) {
    try {
      // 生成密钥
      secretkey deskey = new secretkeyspec(keystr.getbytes(), "desede");
      // 加密
      cipher c1 = cipher.getinstance("desede");
      c1.init(cipher.encrypt_mode, deskey);
      return c1.dofinal(src);
    } catch (java.security.nosuchalgorithmexception e1) {
      e1.printstacktrace();
    } catch (javax.crypto.nosuchpaddingexception e2) {
      e2.printstacktrace();
    } catch (java.lang.exception e3) {
      e3.printstacktrace();
    }
    return null;
}
public static byte[] decryptmode(string keystr, byte[] src) {
    try {
      secretkey deskey = new secretkeyspec(keystr.getbytes(), "desede");
      // 解密
      cipher c1 = cipher.getinstance("desede");
      c1.init(cipher.decrypt_mode, deskey);
      return c1.dofinal(src);
    } catch (java.security.nosuchalgorithmexception e1) {
      e1.printstacktrace();
    } catch (javax.crypto.nosuchpaddingexception e2) {
      e2.printstacktrace();
    } catch (java.lang.exception e3) {
      e3.printstacktrace();
    }
    return null;
}

rsa

/**
* 初始化公密钥
* 
* @return
* @throws exception
*/
public static map<string, object> initkey() throws exception {
    keypairgenerator kpgenerator = keypairgenerator.getinstance("rsa");
    kpgenerator.initialize(2048);
    keypair keypair = kpgenerator.generatekeypair();
    // 存储公钥
    publickey publickey = keypair.getpublic();
    // 存储密钥
    privatekey privatekey = keypair.getprivate();
    map<string, object> keymap = new hashmap<string, object>();
    keymap.put(public_key, publickey);
    keymap.put(private_key, privatekey);
    return keymap;
}
/**
* 取出公钥
* 
* @param keymap
* @return
*/
public static string getpublickey(map<string, object> keymap) {
    key key = (key) keymap.get("rsapublickey");
    return encode2base64(new string(key.getencoded()));
}
/**
* 取出密钥
* 
* @param keymap
* @return
*/
public static string getprivatekey(map<string, object> keymap) {
    key key = (key) keymap.get("rsaprivatekey");
    return encode2base64(new string(key.getencoded()));
}
/**
* 公钥加密
* 
* @param data
* @param publickey
* @return
* @throws exception
*/
public static string encryptbypublickey(string data, rsapublickey publickey)
  throws exception {
    cipher cipher = cipher.getinstance("rsa");
    cipher.init(cipher.encrypt_mode, publickey);
    // 模长
    int key_len = publickey.getmodulus().bitlength() / 8;
    // 加密数据长度 <= 模长-11
    string[] datas = splitstring(data, key_len - 11);
    string mi = "";
    // 如果明文长度大于模长-11则要分组加密
    for (string s : datas) {
      mi += bcd2str(cipher.dofinal(s.getbytes()));
    }
    return mi;
}
/**
* 私钥加密
* 
* @param data
* @param privatekey
* @return
* @throws exception
*/
public static string encryptbyprivatekey(string data,
  rsaprivatekey privatekey) throws exception {
    cipher cipher = cipher.getinstance("rsa");
    cipher.init(cipher.encrypt_mode, privatekey);
    // 模长
    int key_len = privatekey.getmodulus().bitlength() / 8;
    // 加密数据长度 <= 模长-11
    string[] datas = splitstring(data, key_len - 11);
    string mi = "";
    // 如果明文长度大于模长-11则要分组加密
    for (string s : datas) {
      mi += bcd2str(cipher.dofinal(s.getbytes()));
    }
    return mi;
}
/**
* 私钥解密
* 
* @param data
* @param privatekey
* @return
* @throws exception
*/
public static string decryptbyprivatekey(string data,
  rsaprivatekey privatekey) throws exception {
    cipher cipher = cipher.getinstance("rsa");
    cipher.init(cipher.decrypt_mode, privatekey);
    // 模长
    int key_len = privatekey.getmodulus().bitlength() / 8;
    byte[] bytes = data.getbytes();
    byte[] bcd = ascii_to_bcd(bytes, bytes.length);
    system.err.println(bcd.length);
    // 如果密文长度大于模长则要分组解密
    string ming = "";
    byte[][] arrays = splitarray(bcd, key_len);
    for (byte[] arr : arrays) {
      ming += new string(cipher.dofinal(arr));
    }
    return ming;
}
/**
* ascii码转bcd码
* 
*/
public static byte[] ascii_to_bcd(byte[] ascii, int asc_len) {
    byte[] bcd = new byte[asc_len / 2];
    int j = 0;
    for (int i = 0; i < (asc_len + 1) / 2; i++) {
      bcd[i] = asc_to_bcd(ascii[j++]);
      bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
    }
    return bcd;
}
public static byte asc_to_bcd(byte asc) {
    byte bcd;
    if ((asc >= '0') && (asc <= '9'))
      bcd = (byte) (asc - '0');
    else if ((asc >= 'a') && (asc <= 'f'))
      bcd = (byte) (asc - 'a' + 10);
    else if ((asc >= 'a') && (asc <= 'f'))
      bcd = (byte) (asc - 'a' + 10);
    else
      bcd = (byte) (asc - 48);
    return bcd;
}
/**
* bcd转字符串
*/
public static string bcd2str(byte[] bytes) {
    char temp[] = new char[bytes.length * 2], val;
    for (int i = 0; i < bytes.length; i++) {
      val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
      temp[i * 2] = (char) (val > 9 ? val + 'a' - 10 : val + '0');
      val = (char) (bytes[i] & 0x0f);
      temp[i * 2 + 1] = (char) (val > 9 ? val + 'a' - 10 : val + '0');
    }
    return new string(temp);
}
/**
* 拆分字符串
*/
public static string[] splitstring(string string, int len) {
    int x = string.length() / len;
    int y = string.length() % len;
    int z = 0;
    if (y != 0) {
      z = 1;
    }
    string[] strings = new string[x + z];
    string str = "";
    for (int i = 0; i < x + z; i++) {
      if (i == x + z - 1 && y != 0) {
        str = string.substring(i * len, i * len + y);
      } else {
        str = string.substring(i * len, i * len + len);
      }
      strings[i] = str;
    }
    return strings;
}
/**
* 拆分数组
*/
public static byte[][] splitarray(byte[] data, int len) {
    int x = data.length / len;
    int y = data.length % len;
    int z = 0;
    if (y != 0) {
      z = 1;
    }
    byte[][] arrays = new byte[x + z][];
    byte[] arr;
    for (int i = 0; i < x + z; i++) {
      arr = new byte[len];
      if (i == x + z - 1 && y != 0) {
        system.arraycopy(data, i * len, arr, 0, y);
      } else {
        system.arraycopy(data, i * len, arr, 0, len);
      }
      arrays[i] = arr;
    }
    return arrays;
}

以上就是本次项目中用到的加密算法,需要注意的是编码格式一定要双方统一 ,如果不一致则加解密不成功。

ps:关于加密解密感兴趣的朋友还可以参考本站在线工具:

文字在线加密解密工具(包含aes、des、rc4等):

md5在线加密工具:

在线散列/哈希算法加密工具:

在线md5/hash/sha-1/sha-2/sha-256/sha-512/sha-3/ripemd-160加密工具:

在线sha1/sha224/sha256/sha384/sha512加密工具:

更多关于java相关内容感兴趣的读者可查看本站专题:《java数学运算技巧总结》、《java数据结构与算法教程》、《java字符与字符串操作技巧总结》、《java操作dom节点技巧总结》和《java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网