# Java科普之加密算法

+关注继续查看

本文来自http://blog.csdn.net/liuxian13183/ ，引用必须注明出处！

public class Base64 {

static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static private final boolean fDebug = false;
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];

static {
for (int i = 0; i < BASELENGTH; ++i) {
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}

for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}

base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;

for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (char) ('A' + i);
}

for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('a' + j);
}

for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';

}

private static boolean isWhiteSpace(char octect) {
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}

private static boolean isPad(char octect) {
}

private static boolean isData(char octect) {
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}

/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData) {

if (binaryData == null) {
return null;
}

int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0) {
return "";
}

int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1
: numberTriplets;
char encodedData[] = null;

encodedData = new char[numberQuartet * 4];

byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

int encodedIndex = 0;
int dataIndex = 0;
if (fDebug) {
System.out.println("number of triplets = " + numberTriplets);
}

for (int i = 0; i < numberTriplets; i++) {
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];

if (fDebug) {
System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
}

l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);

byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)
: (byte) ((b3) >> 6 ^ 0xfc);

if (fDebug) {
System.out.println("val2 = " + val2);
System.out.println("k4   = " + (k << 4));
System.out.println("vak  = " + (val2 | (k << 4)));
}

encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}

// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
if (fDebug) {
System.out.println("b1=" + b1);
System.out.println("b1<<2 = " + (b1 >> 2));
}
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
} else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);

byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);

encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
}

return new String(encodedData);
}

/**
* Decodes Base64 data into octects
*
* @param encoded string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded) {

if (encoded == null) {
return null;
}

char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);

if (len % FOURBYTE != 0) {
return null;// should be divisible by four
}

int numberQuadruple = (len / FOURBYTE);

return new byte[0];
}

byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;

int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];

for (; i < numberQuadruple - 1; i++) {

if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++]))
|| !isData((d4 = base64Data[dataIndex++]))) {
return null;
}// if found "no data" just return null

b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];

decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}

if (!isData((d1 = base64Data[dataIndex++]))
|| !isData((d2 = base64Data[dataIndex++]))) {
return null;// if found "no data" just return null
}

b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];

d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
} else {
return null;
}
} else { // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

}

return decodedData;
}

/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data) {
if (data == null) {
return 0;
}

// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++) {
if (!isWhiteSpace(data[i])) {
data[newSize++] = data[i];
}
}
return newSize;
}
}

Md5加密，主要用于C端对参数加密后做一个签名，然后S端采取同样操作，签名一致则认为安全，返回数据；目的，为了防止恶意添加参数，盗取数据；原理：非对称加密，加密过程单向不可逆，比较加密后的结果；应用方式，下面是通用的密码本，所以很容易破解，当然也可以自定义密码本（C/S一致即可）。
    // 全局数组
private final static String[] strDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
protected static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

// 返回形式为数字跟字符串
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
// System.out.println("iRet="+iRet);
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return strDigits[iD1] + strDigits[iD2];
}

// 转换字节数组为16进制字串
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}

public static String MD5Encrypt(String strObj) {
String resultString = null;
try {
resultString = new String(strObj);
MessageDigest md = MessageDigest.getInstance("MD5");
// md.digest() 该函数返回值为存放哈希值结果的byte数组
resultString = byteToString(md.digest(strObj.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}

Des加密-（Data Encryption Standard），由56位密钥和8位奇偶检验符组成，通过异或、移位、置换和代换四种操作循环完成，如果一台PC计算能力是一秒一百万次，那么需要2000年才能破解，破解的方案只有穷举法猜出它的密码本或者暴力方式。特别说明一点，使用DES加密的KEY只有前8位有效，写多了也是多余。对称加密，加密方式可逆，用于双方各持有的一个密码本，一个加密一个解密，二战期间的情报加密方式类似这种。

private static String encoding = "UTF-8";

/**
* sKey 奇偶校验位  加密字符串
*/
public static String encrypTo(String sKey, String str) {
String result = str;
if (str != null && str.length() > 0) {
try {
byte[] encodeByte = str.getBytes(encoding);
byte[] encoder = getSymmetricResult(Cipher.ENCRYPT_MODE, sKey, encodeByte);
result = Base64.encode(encoder).toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
return result;
}

/**
* sKey 奇偶校验位
* 解密字符串
*/
public static String decrypTo(String sKey, String str) {
String result = str;
if (str != null && str.length() > 0) {
try {
byte[] decodeByte = Base64.decode(str);
byte[] decoder = getSymmetricResult(Cipher.DECRYPT_MODE, sKey, decodeByte);
result = new String(decoder, encoding);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
return result;
}

/**
* 对称加密字节数组并返回
*
* @param byteSource
*            需要加密的数据
* @return 经过加密的数据
* @throws Exception
*/
public static byte[] getSymmetricResult(int mode, String sKey, byte[] byteSource) throws Exception {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
byte[] keyData = sKey.getBytes();
DESKeySpec keySpec = new DESKeySpec(keyData);
Key key = keyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(mode, key);
byte[] result = cipher.doFinal(byteSource);
return result;
} catch (Exception e) {
throw e;
} finally {
}
}


	/**
* 加密
*
* @param content
*            需要加密的内容
*            加密密码
* @return
*/
public static byte[] encrypt(String password, String content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
e.printStackTrace();
}
return null;
}

/**
* 解密
*
* @param content
*            待解密内容
*            解密密钥
* @return
*/
public static byte[] decrypt(String password, byte[] content) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
e.printStackTrace();
}
return null;
}

public static void main(String[] args) {
String str = "Hello World";
byte[] aesEncryptStr = AESEncrypt.encrypt(sKey, str);
byte[] aesDecryptStr = AESEncrypt.decrypt(sKey, aesEncryptStr);
System.out.println(new String(aesDecryptStr));
}

Sha加密-（Secure Hash Algorithm），与MD5算法类似，但复杂度要高出32个量级，不对称加密，加密过程不可逆，其中SHA-1-224-256-384-512加密复杂度依次增加，

	/**
* 散列算法
*
* @param byteSource
*            需要散列计算的数据
* @return 经过散列计算的数据
* @throws Exception
*/
public static String getShaStr(byte[] byteSource) {
try {
MessageDigest currentAlgorithm = MessageDigest.getInstance("SHA-256");
currentAlgorithm.reset();
currentAlgorithm.update(byteSource);
return bytes2String(currentAlgorithm.digest());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

private static String bytes2String(byte[] aa) {// 将字节数组转换为字符串
String hash = "";
for (int i = 0; i < aa.length; i++) {// 循环数组
int temp;
if (aa[i] < 0) // 判断是否是负数
temp = 256 + aa[i];
else
temp = aa[i];
if (temp < 16)
hash += "0";
hash += Integer.toString(temp, 16);// 转换为16进
}
hash = hash.toUpperCase(); // 转换为大写
return hash;
}

public static void main(String[] args) {
String str = "Hello World";
String shaEncryptStr = ShaEncrypt.getShaStr(str.getBytes());
System.out.println(shaEncryptStr);// sha1-0A4D55A8D778E5022FAB701977C5D840BBC486D0
System.out.println(shaEncryptStr.length());
}

RSA加密（三位发明者名字首字母），由一个公钥和一个私钥组成，支付宝目前就采用这种加密方式，C端持有公钥，S端持有私钥，C端发送的加密数据只能由S端来处理，安全系统业界称为最高；原理是对两大素数的乘积做拆分，有无数种可能，所以只要公钥和私钥不泄密，一般就没有问题。非对称加密，但加密过程可逆。

ECB：直接分块加密

for(int i=0;i<grey->width;i++)
for(int j=0;j<grey->height;j++)
grey->imageData[j*grey->width+i]=bitrev(grey->imageData[j*grey->width+i]);
cvNamedWindow("ecb");
cvShowImage("ecb", grey);  
CBC：与上块密文异或后加密，需要向量
for(int i=0;i<grey->width;i++)
for(int j=0;j<grey->height;j++)
if(i!=0&&j!=0)
grey->imageData[j*grey->width+i]=bitrev(grey->imageData[j*grey->width+i]^grey->imageData[j*grey->width+i-1]);
else
grey->imageData[0]=grey->imageData[0]^IV;
cvNamedWindow("cbc");
cvShowImage("cbc", grey); 

1、将加密过程放在so库里，这样对方即使得知你的加密字符串，也无法知道你的密钥和加密过程

2、将加密算法通过远程管理，一旦发现出问题，通过服务器派发客户端反射的方式，下发新的算法

3、增加代码混淆的难度

4、为防止撞库，可以选择更慢的算法，来延长被破解的时间。

ECB，应显示指定使用 CBC CFB 加密模式。

ECBCBCCFBOFB 等，其中 ECB 的安全性较弱，会使相同的铭文

CBC CFB 模式。
1) ECBElectronic codebook，电子密码本模式
2) CBCCipher-block chaining，密码分组链接模式
3) CFBCipher feedback，密文反馈模式
4) OFBOutput feedback，输出反馈模式

|
1月前
|

java密码学-对称加密算法
java密码学-对称加密算法
22 0
|
6月前
|

JAVA面试——加密算法
JAVA面试——加密算法
102 0
|
9月前
|

|
9月前
|

|

java中的对称加密算法

1094 2
|

[自己做个游戏服务器三]你帮我为服务器选择一种加密算法，Java实现各种加解密算法

222 0
|
Java 数据安全/隐私保护
java自带的MessageDigest实现文本的md5加密算法
java自带的MessageDigest实现文本的md5加密算法
245 0
|

1002 0
|

1628 1