什么是Base64 格式字符串?
Base64是一种基于64个可打印字符来表示二进制数据的表示方法。通常是52个大小字母和10个数字,以及+,/两个字符,还有个=用于补缺。
所以一定要注意 字符串是没有空格、用+代替空格。 同url网址传递后,往往+被替换成了空格,如果要解密 url获取到的加密字符串,需要替换空格;
/* desc base64 解密算法*/
private function fill8($str){
if(strlen($str) % 8){
$len = strlen($str) + 8 - strlen($str) % 8;
$str = str_pad($str, $len, " ");
}
return $str;
}
public function DesBase64_Decrypt($encrypt_str, $key){
$encrypt_str = substr($encrypt_str, 8);
$encrypt_str = $this->fill8($encrypt_str);
$key = $this->fill8($key);
$cipher = "DES-ECB";
$iv = "";
$original_plaintext = openssl_decrypt(base64_decode($encrypt_str), $cipher, $key ,OPENSSL_NO_PADDING, $iv, $tag);
return base64_decode($original_plaintext);
}
上面代码 功能是解密 一个经过 des-ecb 加密的字符串;
这个加密是增加了一些附加功能的: 加密字符串 = des-ecb 加密后 ,再用 base64 加密。
本算法:des-ecb 加密得到一个 base64字符串,然后再把它 base64 一次。
所以用 openssl_decrypt 解密之前,用 base_decode 字符串。
加密方法:
function DescBase64_Encrypt($data) {
$key = ‘thisisakey’;
$cipher = "DES-ECB";
$iv = "";
return base64_encode( openssl_decrypt($data, $cipher, $key, OPENSSL_NO_PADDING));
}
java端解密的代码:
static public String DecodeString_ver1(String s, String pass) throws Exception {
Log.d(LOG_TAG, "EncodeString_ver1 s" + s);
byte[] buf = Base64.decode(s, 0);
Key kpass = DesBase64.initKey(pass);
buf = decryptByte(buf, kpass); //这时的内容应该是 base64 的,所以可以直接转换成明文
s = new String(buf, "utf-8");
s = s.trim(); //将填充的 8倍 空格去掉
Log.d(LOG_TAG, "EncodeString_ver1 s" + s);
return new String(buf, ("utf-8"));
}
//创建一个加密解密的key
static public Key initKey(String keyRule) throws Exception {
byte[] keyByte = keyRule.getBytes("utf-8"); //奇怪,和上面的是一样的
// 创建一个空的八位数组,默认情况下为0
byte[] byteTemp = new byte[8];
// 将用户指定的规则转换成八位数组
for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
byteTemp[i] = keyByte[i];
}
Key mKey = new SecretKeySpec(byteTemp, "DES");
return mKey;
}
//des 解密
static public byte[] decryptByte(byte[] byteD, Key key) {
Cipher cipher;
byte[] byteFina = null;
try {
cipher = Cipher.getInstance("DES/ECB/NOPADDING");
cipher.init(Cipher.DECRYPT_MODE, key);
byteFina = cipher.doFinal(byteD);
} catch (Exception e) {
throw new RuntimeException(
"Error initializing SqlMap class. Cause: " + e);
} finally {
cipher = null;
}
return byteFina;
}
static public String fill8(String s) throws Exception {
int len = s.length();
len = len % 8;
if (len > 0) len = 8 - len; //算出要填充多少个字符才到8的倍数
for (int i = 0; i < len; i++) {
s = s + ' ';
}
return s;
}//