互联网开发之神器:经典加解密函数Discuz authcode
作者:互联网
肉眼品世界导读:互联网开发里有一个很重要的业务,就是数据的安全性,而有的数据真正处理的时候又需要明文出现,那么安全的加解密就是一个非常重要的常见场景了,api 的token,关键数据的加密存储;php的discuz里就有这么一个神级函数authcode,不过java版本的也有哦 读懂中国互联网,读懂商业模式请关注微信公众号“肉眼品世界”(ID:find_world_fine),深度价值体系传递
应用场景
场景一:
小编曾经一个一个代码的码了一个开放平台出来,自然也看到oauth的代码和数据库存储,oauth是一个字段存第一次请求的临时token和过期时间字段,每次都在数据库里对比;在和app对接的时候,客户端请求server的api的时候也是需要token的,当然java里还有jwt,好多同学认为简单了,那就自己通过此authcode函数以用户id,用户名的截取以及随机串加密一个串生成一个token,此函数还有设置有效时间,过期了app端就重新生成,服务器端收到此token时只需要反向解密,能解出来uid和username就代表ok了
场景二:关键数据存储,如一些与银行对接的key
加密存储数据库,待过期前讲整个加密存储刷新一遍,即使人家拿走数据的东西,已经没有用了,当然你还可以动态修改你自己加密函数的key,也相对更安全了
场景三:干点儿坏事
就不说了
直接上代码:
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
$ckey_length = 4;
$key = md5($key ? $key : UC_KEY);
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if($operation == 'DECODE') {
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc.str_replace('=', '', base64_encode($result));
}
}
小编,你别唬我啊,php的到处都能下,java的在哪呢,百度一下,csdn里下的有点儿问题,小编小修改了一下,能用了,这东西拿去唬唬一般公司的面试官应该是能有一定把握的,大家多赚钱
关注公众号:肉眼品世界,回复authcodejava下载有加密过期时间设置版本的
csdn里的包改用了org.apache.commons.codec.binary.Base64能用了,不过好像没过期时间,过期时间版请关注公众号回复"authcodejava"下载
import org.apache.commons.codec.binary.Base64;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Random;
public class AuthCode {
public enum DiscuzAuthcodeMode {
Encode, Decode
};
// private static MD5 md5 = new MD5();
// private static BASE64 base64 = new BASE64();
// / <summary>
// / 从字符串的指定位置截取指定长度的子字符串
// / </summary>
// / <param name="str">原字符串</param>
// / <param name="startIndex">子字符串的起始位置</param>
// / <param name="length">子字符串的长度</param>
// / <returns>子字符串</returns>
public static String CutString(String str, int startIndex, int length) {
if (startIndex >= 0) {
if (length < 0) {
length = length * -1;
if (startIndex - length < 0) {
length = startIndex;
startIndex = 0;
} else {
startIndex = startIndex - length;
}
}
if (startIndex > str.length()) {
return "";
}
} else {
if (length < 0) {
return "";
} else {
if (length + startIndex > 0) {
length = length + startIndex;
startIndex = 0;
} else {
return "";
}
}
}
if (str.length() - startIndex < length) {
length = str.length() - startIndex;
}
return str.substring(startIndex, startIndex + length);
}
// / <summary>
// / 从字符串的指定位置开始截取到字符串结尾的了符串
// / </summary>
// / <param name="str">原字符串</param>
// / <param name="startIndex">子字符串的起始位置</param>
// / <returns>子字符串</returns>
public static String CutString(String str, int startIndex) {
return CutString(str, startIndex, str.length());
}
// / <summary>
// / 返回文件是否存在
// / </summary>
// / <param name="filename">文件名</param>
// / <returns>是否存在</returns>
public static boolean FileExists(String filename) {
File f = new File(filename);
return f.exists();
}
// / <summary>
// / MD5函数
// / </summary>
// / <param name="str">原始字符串</param>
// / <returns>MD5结果</returns>
public static String MD5(String str) {
// return md5.convert(str);
StringBuffer sb = new StringBuffer();
String part = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] md5 = md.digest(str.getBytes());
for (int i = 0; i < md5.length; i++) {
part = Integer.toHexString(md5[i] & 0xFF);
if (part.length() == 1) {
part = "0" + part;
}
sb.append(part);
}
} catch (NoSuchAlgorithmException ex) {
}
return sb.toString();
}
// / <summary>
// / 字段串是否为Null或为""(空)
// / </summary>
// / <param name="str"></param>
// / <returns></returns>
public static boolean StrIsNullOrEmpty(String str) {
// #if NET1
if (str == null || str.trim().equals("")) {
return true;
}
return false;
}
// / <summary>
// / 用于 RC4 处理密码
// / </summary>
// / <param name="pass">密码字串</param>
// / <param name="kLen">密钥长度,一般为 256</param>
// / <returns></returns>
static private byte[] GetKey(byte[] pass, int kLen) {
byte[] mBox = new byte[kLen];
for (int i = 0; i < kLen; i++) {
mBox[i] = (byte) i;
}
int j = 0;
for (int i = 0; i < kLen; i++) {
j = (j + (int) ((mBox[i] + 256) % 256) + pass[i % pass.length])
% kLen;
byte temp = mBox[i];
mBox[i] = mBox[j];
mBox[j] = temp;
}
return mBox;
}
// / <summary>
// / 生成随机字符
// / </summary>
// / <param name="lens">随机字符长度</param>
// / <returns>随机字符</returns>
public static String RandomString(int lens) {
char[] CharArray = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int clens = CharArray.length;
String sCode = "";
Random random = new Random();
for (int i = 0; i < lens; i++) {
sCode += CharArray[Math.abs(random.nextInt(clens))];
}
return sCode;
}
public static String authcodeEncode(String source, String key, int expiry) {
return authcode(source, key, DiscuzAuthcodeMode.Encode, expiry);
}
public static String authcodeEncode(String source, String key) {
return authcode(source, key, DiscuzAuthcodeMode.Encode, 0);
}
public static String authcodeDecode(String source, String key) {
return authcode(source, key, DiscuzAuthcodeMode.Decode, 0);
}
private static String authcode(String source, String key,
DiscuzAuthcodeMode operation, int expiry) {
System.out.println("--------source:" + source);
try {
if (source == null || key == null) {
return "";
}
int ckey_length = 4;
String keya, keyb, keyc, cryptkey, result;
key = MD5(key);
keya = MD5(CutString(key, 0, 16));
keyb = MD5(CutString(key, 16, 16));
keyc = ckey_length > 0 ? (operation == DiscuzAuthcodeMode.Decode ? CutString(
source, 0, ckey_length) : RandomString(ckey_length))
: "";
cryptkey = keya + MD5(keya + keyc);
if (operation == DiscuzAuthcodeMode.Decode) {
byte[] temp;
String tstr = CutString(source, ckey_length);
System.out.println(" CutString(source, ckey_length):" + CutString(source, ckey_length));
temp = Base64.decodeBase64(CutString(source, ckey_length));
result = new String(RC4(temp, cryptkey));
if (CutString(result, 10, 16).equals(
CutString(MD5(CutString(result, 26) + keyb), 0, 16))) {
return CutString(result, 26);
} else {
temp = Base64.decodeBase64(CutString(source + "=", ckey_length));
result = new String(RC4(temp, cryptkey));
if (CutString(result, 10, 16)
.equals(CutString(
MD5(CutString(result, 26) + keyb), 0, 16))) {
return CutString(result, 26);
} else {
temp = Base64.decodeBase64(CutString(source + "==",
ckey_length));
result = new String(RC4(temp, cryptkey));
if (CutString(result, 10, 16).equals(
CutString(MD5(CutString(result, 26) + keyb), 0,
16))) {
return CutString(result, 26);
} else {
return "2";
}
}
}
} else {
source = "0000000000" + CutString(MD5(source + keyb), 0, 16)
+ source;
byte[] temp = RC4(source.getBytes("GBK"), cryptkey);
return keyc + Base64.encodeBase64String(temp);
}
} catch (Exception e) {
e.printStackTrace();
return "==aaaa==";
}
}
// / <summary>
// / RC4 原始算法
// / </summary>
// / <param name="input">原始字串数组</param>
// / <param name="pass">密钥</param>
// / <returns>处理后的字串数组</returns>
private static byte[] RC4(byte[] input, String pass) {
if (input == null || pass == null)
return null;
byte[] output = new byte[input.length];
byte[] mBox = GetKey(pass.getBytes(), 256);
// 加密
int i = 0;
int j = 0;
for (int offset = 0; offset < input.length; offset++) {
i = (i + 1) % mBox.length;
j = (j + (int) ((mBox[i] + 256) % 256)) % mBox.length;
byte temp = mBox[i];
mBox[i] = mBox[j];
mBox[j] = temp;
byte a = input[offset];
// byte b = mBox[(mBox[i] + mBox[j] % mBox.Length) % mBox.Length];
// mBox[j] 一定比 mBox.Length 小,不需要在取模
byte b = mBox[(toInt(mBox[i]) + toInt(mBox[j])) % mBox.length];
output[offset] = (byte) ((int) a ^ (int) toInt(b));
}
return output;
}
public static int toInt(byte b) {
return (int) ((b + 256) % 256);
}
public long getUnixTimestamp() {
Calendar cal = Calendar.getInstance();
return cal.getTimeInMillis() / 1000;
}
public static void main(String[] args) {
String test = "111aaaaaaaaaaaaaaaaaaaf" +
"" +
"";
String key = "eafdf6";
String afStr = AuthCode.authcodeEncode(test, key);
System.out.println("--------encode:" + afStr);
long lStart = System.currentTimeMillis();
System.out.println("解码后:" + AuthCode.authcodeDecode(afStr, key));
long lUseTime = System.currentTimeMillis() - lStart;
System.out.println("加解密耗时:" + lUseTime + "毫秒");
}
}
标签:return,String,加解密,authcode,CutString,Discuz,length,key,mBox 来源: https://blog.51cto.com/u_14637492/2900235