在app开发中我们遇到一个需要将用户的账户密码加密问题,便是我们这篇文章的来源了。
为了保持我们三个前端的一致性我们一定要将key和位移保持一致,否则会导致bug。
首先还是直接来看一下我们的Java后端代码,其实就是加密和解密算法了。Android直接拿到这个工具类就好了,为什么么?你懂的。
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
@SuppressWarnings("restriction")
public class AESUtils {
private static final String AES = "AES";
private static final String CRYPT_KEY = "";//你自己的key
private static final String IV_STRING = "";//你自己的位移
/**
* 加密
*
* @param content 加密内容
* @return 密文
* @throws Exception e
*/
public static String encrypt(String content) throws Exception {
byte[] encryptedBytes = new byte[0];
try {
byte[] byteContent = content.getBytes("UTF-8");
// 注意,为了能与 iOS 统一
// 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成
byte[] enCodeFormat = CRYPT_KEY.getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, AES);
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// 指定加密的算法、工作模式和填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
encryptedBytes = cipher.doFinal(byteContent);
// 同样对加密后数据进行 base64 编码
} catch (Exception e) {
throw new Exception(e);
}
return new BASE64Encoder().encode(encryptedBytes);
}
/**
* 解密
*
* @param content 密文
* @return 明文
* @throws Exception e
*/
public static String decrypt(String content) throws Exception {
// base64 解码
try {
byte[] encryptedBytes = new BASE64Decoder().decodeBuffer(content);
byte[] enCodeFormat = CRYPT_KEY.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, AES);
byte[] initParam = IV_STRING.getBytes();
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
byte[] result = cipher.doFinal(encryptedBytes);
return new String(result, "UTF-8");
} catch (Exception e) {
throw new Exception(e);
}
}
}
接下来就是ios,同样的需要我们定义和Android及Java后端一致的key和位移:
//先定义一个初始向量的值。
NSString *const kInitVector = @"";
NSString *const key= @"";
//确定密钥长度,这里选择 AES-128。
size_t const kKeySize = kCCKeySizeAES128;
/**
AES加密方法
@param content 需要加密的字符串
@param key key
@return 加密后的字符串
*/
+ (NSString *)encryptAES:(NSString *)content{
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = contentData.length;
// 为结束符'\\0' +1
char keyPtr[kKeySize + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
// 密文长度 <= 明文长度 + BlockSize
size_t encryptSize = dataLength + kCCBlockSizeAES128;
void *encryptedBytes = malloc(encryptSize);
size_t actualOutSize = 0;
NSData *initVector = [kInitVector dataUsingEncoding:NSUTF8StringEncoding];
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding, // 系统默认使用 CBC,然后指明使用 PKCS7Padding
keyPtr,
kKeySize,
initVector.bytes,
contentData.bytes,
dataLength,
encryptedBytes,
encryptSize,
&actualOutSize);
if (cryptStatus == kCCSuccess) {
// 对加密后的数据进行 base64 编码
return [[NSData dataWithBytesNoCopy:encryptedBytes length:actualOutSize] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}
free(encryptedBytes);
return nil;
}
/**
AES解密方法
@param content 需要解密的字符串
@param key key
@return 解密后的字符串
*/
+ (NSString *)decryptAES:(NSString *)content{
// 把 base64 String 转换成 Data
NSData *contentData = [[NSData alloc] initWithBase64EncodedString:content options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSUInteger dataLength = contentData.length;
char keyPtr[kKeySize + 1];
memset(keyPtr, 0, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
size_t decryptSize = dataLength + kCCBlockSizeAES128;
void *decryptedBytes = malloc(decryptSize);
size_t actualOutSize = 0;
NSData *initVector = [kInitVector dataUsingEncoding:NSUTF8StringEncoding];
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyPtr,
kKeySize,
initVector.bytes,
contentData.bytes,
dataLength,
decryptedBytes,
decryptSize,
&actualOutSize);
if (cryptStatus == kCCSuccess) {
return [[NSString alloc] initWithData:[NSData dataWithBytesNoCopy:decryptedBytes length:actualOutSize] encoding:NSUTF8StringEncoding];
}
free(decryptedBytes);
return nil;
}
js端,js文件哪里找,楼主的资源链接如下
点击打开链接
<script type="text/javascript" src="./CryptoJS/crypto-js.js"></script>
<script>
//直接上代码
var key = CryptoJS.enc.Utf8.parse('');//key
var iv = CryptoJS.enc.Utf8.parse('');//位移
var source = '要加密的字符串';
var password=CryptoJS.enc.Utf8.parse(source);
console.log("原始字符串:"+source);
console.log("utf8处理后:"+password);
var encrypted = CryptoJS.AES.encrypt(password, key, { iv: iv,mode:CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7}); //CryptoJS.pad.Pkcs7
var decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv,mode:CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7}); //CryptoJS.pad.Pkcs7
console.log("加密后base64:"+encrypted);
var encryptedStr=encrypted.ciphertext.toString();
console.log("加密后16进制:"+encryptedStr);
console.log("解密后utf8:"+decrypted);
console.log("解密后原始字符串:"+decrypted.toString(CryptoJS.enc.Utf8));
</script>
方法已经在楼主参与的app中已应用。放心大胆的用吧。