[置顶] Android/Java中的常用签名算法
来源:程序员人生 发布时间:2016-11-16 08:43:05 阅读次数:2474次
Android/Java中经常使用的签名算法实现:
(包括BASE64、MD5、SHA1、HMAC_SHA1、AES、RSA等)
package com.helloWorld;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Locale;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
/**
* 加解密工具类
* @author helloWorld
*
*/
public class EncryptUtils {
/**
* Hex字符
*/
public static final String HEX_DIGITS = "0123456789ABCDEF";
/**
* UTF⑻
*/
public static final String UTF_8 = "UTF⑻";
/**
* base64编码
* @param bytes
* @return
*/
public static String base64Encode(byte[] bytes) {
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
/**
* base64解码
* @param base64Str
* @return
* @throws Exception
*/
public static byte[] base64Decode(String base64Str) throws Exception {
return Base64.decode(base64Str, Base64.NO_WRAP);
}
/**
* 字节数组转成16进制字符串
* @param bytes
* @return
*/
public static String bytesToHexString(byte[] bytes) {
if (bytes == null || bytes.length <= 0) {
return null;
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
int v = bytes[i] & 0xff;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 16进制字符串转换成字节数组
* @param hexString
* @return
*/
public static byte[] hexStringToBytes(String hexString) {
if (StringUtils.isBlank(hexString)) {
return null;
}
char[] hexChars = hexString.toUpperCase(Locale.US).toCharArray();
int length = hexString.length()/2;
byte[] bytes = new byte[length];
for (int i = 0; i < length; ++i) {
bytes[i] = (byte)(HEX_DIGITS.indexOf(hexChars[i*2]) << 4
| HEX_DIGITS.indexOf(hexChars[i*2 + 1]));
}
return bytes;
}
/**
* 获得MD5.字节数组
* @param bytes
* @return
* @throws Exception
*/
public static byte[] getMd5(byte[] bytes) throws Exception {
if (bytes == null) {
throw new Exception("illegal params.");
}
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(bytes);
return md5.digest();
}
/**
* 获得MD5值,返回16进制字符串
* @param str
* @return
* @throws Exception
*/
public static String getMd5Hex(String str) throws Exception {
if (StringUtils.isBlank(str)) {
throw new Exception("illegal params.");
}
return bytesToHexString(str.getBytes(UTF_8));
}
/**
* 获得SHA1值。
* @param bytes
* @return
* @throws Exception
*/
public static byte[] getSha1(byte[] bytes) throws Exception {
if (bytes == null) {
throw new Exception("illegal params.");
}
MessageDigest sha1 = MessageDigest.getInstance("SHA⑴");
sha1.update(bytes);
return sha1.digest();
}
/**
* 获得SHA1值。
* @param str
* @return
* @throws Exception
*/
public static String getSha1Hex(String str) throws Exception {
if (StringUtils.isBlank(str)) {
throw new Exception("illegal params.");
}
return bytesToHexString(getSha1(str.getBytes(UTF_8)));
}
/**
*
* @param content
* @param key
* @return
* @throws Exception
*/
public static byte[] getHmacSha1(byte[] content, byte[] key) throws Exception {
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance(signingKey.getAlgorithm());
mac.init(signingKey);
return mac.doFinal(content);
}
/**
*
* @param content
* @param key
* @return
* @throws Exception
*/
public static String getHmacSha1Hex(String content, String key) throws Exception {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), "HmacSHA1");
Mac mac = Mac.getInstance(signingKey.getAlgorithm());
mac.init(signingKey);
return bytesToHexString(mac.doFinal(content.getBytes(UTF_8)));
}
/**
*
* @param contentBytes
* @param key
* @param opmode
* @return
* @throws Exception
*/
public static byte[] aes(int opmode, byte[] content, byte[] key) throws Exception {
SecureRandom secureRandom = null;
//if (android.os.Build.VERSION.SDK_INT >= 17) {//SHA1PRNG强随机种子算法,要区分4.2以上版本的调用方法
secureRandom = SecureRandom.getInstance("SHA1PRNG", "Crypto");
//} else {
// secureRandom = SecureRandom.getInstance("SHA1PRNG");
//}
secureRandom.setSeed(key);
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, secureRandom);
Cipher cipher = Cipher.getInstance("AES/ECB/ZeroBytePadding");
cipher.init(opmode, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
return cipher.doFinal(content);
}
/**
* AES加密,返回16进制字符串
* @param content
* @param key
* @return
* @throws Exception
*/
public static String aesEncryptHex(String content, String key) throws Exception {
if (StringUtils.isBlank(content) || StringUtils.isBlank(key)) {
throw new Exception("illegal params.");
}
return bytesToHexString(aes(Cipher.ENCRYPT_MODE, content.getBytes(UTF_8), key.getBytes(UTF_8)));
}
/**
* AES解密,针对原始加密串为16进制字符串
* @param encryptHexStr
* @param key
* @return
* @throws Exception
*/
public static String aesDecryptHex(String encryptHexStr, String key) throws Exception {
if (StringUtils.isBlank(encryptHexStr) || StringUtils.isBlank(key)) {
throw new Exception("illegal params.");
}
return new String(aes(Cipher.DECRYPT_MODE, hexStringToBytes(encryptHexStr), key.getBytes(UTF_8)));
}
/**
* rsaSign
* @param content
* @param privateKey
* @return
* @throws Exception
*/
public static byte[] rsaSign(byte[] content, byte[] privateKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(privateKey, Base64.DEFAULT);
PrivateKey privateKeyObj = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");
signature.initSign(privateKeyObj);
signature.update(content);
return signature.sign();
}
/**
* rsaSignHex
* @param content
* @param privateKey
* @return
* @throws Exception
*/
public static String rsaSignHex(String content, String privateKey) throws Exception {
if (StringUtils.isBlank(content) || StringUtils.isBlank(privateKey)) {
throw new Exception("illegal params.");
}
return bytesToHexString(rsaSign(content.getBytes(UTF_8), privateKey.getBytes(UTF_8)));
}
/**
* rsaVerify
* @param content
* @param sign
* @param publicKey
* @return
* @throws Exception
*/
public static boolean rsaVerify(byte[] content, byte[] sign, byte[] publicKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.decode(publicKey, Base64.DEFAULT);
PublicKey publicKeyObj = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
java.security.Signature signature = java.security.Signature.getInstance("SHA1WithRSA");
signature.initVerify(publicKeyObj);
signature.update(content);
return signature.verify(sign);
}
/**
* rsaVerifyHex
* @param content
* @param sign
* @param publicKey
* @return
* @throws Exception
*/
public static boolean rsaVerifyHex(String content, String sign, String publicKey) throws Exception {
if (StringUtils.isBlank(content) || StringUtils.isBlank(sign) || StringUtils.isBlank(publicKey)) {
throw new Exception("illegal params.");
}
return rsaVerify(content.getBytes(UTF_8), hexStringToBytes(sign), publicKey.getBytes(UTF_8));
}
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠