android ios php aes,Android-Ios-Php-Java AES加密解密

首先代码取至网络,代码有坑在所难免,以下代码验证可用,怎么填坑我就不说了.废话不多说,上代码

AesEncryptionUtil.java

import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;

public class AesEncryptionUtil {

/** 算法/模式/填充 **/

private static final String CipherMode = "AES/CBC/NoPadding";

/** 创建密钥 **/

private static SecretKeySpec createKey(String key) {

byte[] data = null;

if (key == null) {

key = "";

}

StringBuffer sb = new StringBuffer(16);

sb.append(key);

while (sb.length() < 16) {

sb.append("0");

}

if (sb.length() > 16) {

sb.setLength(16);

}

try {

data = sb.toString().getBytes("UTF-8");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return new SecretKeySpec(data, "AES");

}

private static IvParameterSpec createIV(String password) {

byte[] data = null;

if (password == null) {

password = "";

}

StringBuffer sb = new StringBuffer(16);

sb.append(password);

while (sb.length() < 16) {

sb.append("0");

}

if (sb.length() > 16) {

sb.setLength(16);

}

try {

data = sb.toString().getBytes("UTF-8");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return new IvParameterSpec(data);

}

/** 加密字节数据 **/

public static byte[] encrypt(byte[] content, String password, String iv) {

try {

// String encryptResultStr = parseByte2HexStr(content);

SecretKeySpec key = createKey(password);

Cipher cipher = Cipher.getInstance(CipherMode);

cipher.init(Cipher.ENCRYPT_MODE, key, createIV(iv));

int len = content.length;

/* 计算补0后的长度 */

while (len % 16 != 0) {

len++;

}

byte[] sraw = new byte[len];

/* 在最后补0 */

for (int i = 0; i < len; ++i) {

if (i < content.length) {

sraw[i] = content[i];

} else {

sraw[i] = 0;

}

}

return cipher.doFinal(sraw);

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/**

* 将二进制转换成16进制

*

* @param buf

* @return

*/

public static String parseByte2HexStr(byte buf[]) {

StringBuffer sb = new StringBuffer();

for (int i = 0; i < buf.length; i++) {

String hex = Integer.toHexString(buf[i] & 0xFF);

if (hex.length() == 1) {

hex = '0' + hex;

}

sb.append(hex.toUpperCase());

}

return sb.toString();

}

/**

* 将16进制转换为二进制

*

* @param hexStr

* @return

*/

public static byte[] parseHexStr2Byte(String hexStr) {

if (hexStr.length() < 1) {

return null;

}

byte[] result = new byte[hexStr.length() / 2];

for (int i = 0; i < hexStr.length() / 2; i++) {

int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);

int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),

16);

result[i] = (byte) (high * 16 + low);

}

return result;

}

/**

* 加密

*/

public static String encrypt(String content) {

return encrypt(content, Key.KEY, Key.KEYIV);

}

/** 加密(结果为16进制字符串) **/

public static String encrypt(String content, String password, String iv) {

byte[] data = null;

try {

data = content.getBytes("UTF-8");

} catch (Exception e) {

e.printStackTrace();

}

data = encrypt(data, password, iv);

return Base64Utils.encode(data);

}

/** 解密字节数组 **/

public static byte[] decrypt(byte[] content) {

return decrypt(content, Key.KEY, Key.KEYIV);

}

/** 解密字节数组 **/

public static byte[] decrypt(byte[] content, String password, String iv) {

try {

SecretKeySpec key = createKey(password);

Cipher cipher = Cipher.getInstance(CipherMode);

cipher.init(Cipher.DECRYPT_MODE, key, createIV(iv));

byte[] result = cipher.doFinal(content);

return result;

} catch (Exception e) {

e.printStackTrace();

}

return null;

}

/** 解密(输出结果为字符串) **/

public static String decrypt(String content) {

return decrypt(content, Key.KEY, Key.KEYIV);

}

/** 解密(输出结果为字符串) **/

public static String decrypt(String content, String password, String iv) {

byte[] data = null;

try {

data = Base64Utils.decode(content);

} catch (Exception e) {

e.printStackTrace();

}

data = decrypt(data, password, iv);

if (data == null) {

return null;

}

String result = null;

try {

result = new String(data, "UTF-8").trim();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return result;

}

/** 字节数组转成16进制字符串 **/

public static String byte2hex(byte[] b) { // 一个字节的数,

StringBuffer sb = new StringBuffer(b.length * 2);

String tmp = "";

for (int n = 0; n < b.length; n++) {

// 整数转成十六进制表示

tmp = (Integer.toHexString(b[n] & 0XFF));

if (tmp.length() == 1) {

sb.append("0");

}

sb.append(tmp);

}

// return sb.toString().toUpperCase(); // 转成大写

return sb.toString(); // 转成大写

}

/** 将hex字符串转换成字节数组 **/

public static byte[] hex2byte(String inputString) {

if (inputString == null || inputString.length() < 2) {

return new byte[0];

}

inputString = inputString.toLowerCase();

int l = inputString.length() / 2;

byte[] result = new byte[l];

for (int i = 0; i < l; ++i) {

String tmp = inputString.substring(2 * i, 2 * i + 2);

result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);

}

return result;

}

}

Key.java

public class Key {

/**

* 密钥,这个是后台大佬和我们的约定

*/

public static final String KEY = "$75k!xxH&$EhQLyv"; // 密钥

/**

* 密钥偏移

*/

public static final String KEYIV = MD5Utils.md5(KEY).substring(0, 16); // 密钥偏移

}

Base64Utils.java

import java.io.UnsupportedEncodingException;

/**

* @author Rocko

*/

public class Base64Utils {

private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D',

'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',

'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',

'e', 'f', 'g', 'h', 'i', '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', '+', '/' };

private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1,

-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,

-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,

-1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,

60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,

-1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,

38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,

-1, -1 };

public static String encode(byte[] data) {

StringBuffer sb = new StringBuffer();

int len = data.length;

int i = 0;

int b1, b2, b3;

while (i < len) {

b1 = data[i++] & 0xff;

if (i == len) {

sb.append(base64EncodeChars[b1 >>> 2]);

sb.append(base64EncodeChars[(b1 & 0x3) << 4]);

sb.append("==");

break;

}

b2 = data[i++] & 0xff;

if (i == len) {

sb.append(base64EncodeChars[b1 >>> 2]);

sb.append(base64EncodeChars[((b1 & 0x03) << 4)

| ((b2 & 0xf0) >>> 4)]);

sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);

sb.append("=");

break;

}

b3 = data[i++] & 0xff;

sb.append(base64EncodeChars[b1 >>> 2]);

sb.append(base64EncodeChars[((b1 & 0x03) << 4)

| ((b2 & 0xf0) >>> 4)]);

sb.append(base64EncodeChars[((b2 & 0x0f) << 2)

| ((b3 & 0xc0) >>> 6)]);

sb.append(base64EncodeChars[b3 & 0x3f]);

}

return sb.toString();

}

public static byte[] decode(String str) {

try {

return decodePrivate(str);

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return new byte[] {};

}

private static byte[] decodePrivate(String str)

throws UnsupportedEncodingException {

StringBuffer sb = new StringBuffer();

byte[] data = null;

data = str.getBytes("US-ASCII");

int len = data.length;

int i = 0;

int b1, b2, b3, b4;

while (i < len) {

do {

b1 = base64DecodeChars[data[i++]];

} while (i < len && b1 == -1);

if (b1 == -1)

break;

do {

b2 = base64DecodeChars[data[i++]];

} while (i < len && b2 == -1);

if (b2 == -1)

break;

sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

do {

b3 = data[i++];

if (b3 == 61)

return sb.toString().getBytes("iso8859-1");

b3 = base64DecodeChars[b3];

} while (i < len && b3 == -1);

if (b3 == -1)

break;

sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

do {

b4 = data[i++];

if (b4 == 61)

return sb.toString().getBytes("iso8859-1");

//return sb.toString().getBytes("utf-8");

b4 = base64DecodeChars[b4];

} while (i < len && b4 == -1);

if (b4 == -1)

break;

sb.append((char) (((b3 & 0x03) << 6) | b4));

}

return sb.toString().getBytes("iso8859-1");

//return sb.toString().getBytes("utf-8");

}

}

MD5Utils.java

public class MD5Utils {

public static String md5(String plainText){

byte[] secretBytes = null;

try {

secretBytes = MessageDigest.getInstance("md5").digest(

plainText.getBytes());

} catch (NoSuchAlgorithmException e) {

throw new RuntimeException("没有md5这个算法!");

}

String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字

// 如果生成数字未满32位,需要前面补0

for (int i = 0; i < 32 - md5code.length(); i++) {

md5code = "0" + md5code;

}

return md5code;

}

}

调用方式

public static void main(String[] args) {

String encrypt = AesEncryptionUtil.encrypt("123456");

String decrypt = AesEncryptionUtil.decrypt(AesEncryptionUtil.encrypt("123456"));

System.out.println("#加密串#" + encrypt);

System.out.println("#解密串#" + decrypt);

}

执行结果:

===================================

#加密串#Pn0/Mwp7v4CyNiK+9O1HCg==

#解密串#123456

===================================

tips: 吹个牛,Java后台没验证,因为后台大佬是Php,没有Java后台,个人认为Android通,Java通

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS中可以使用OpenSSL库来实现AES-GCM和AES-ECB加密解密操作。下面给出一个示例代码: ```objc #include <openssl/evp.h> #include <openssl/rand.h> // AES-GCM加密解密 void aes_gcm_encrypt_decrypt() { // 定义key和iv unsigned char key[16] = {0x0}; unsigned char iv[12] = {0x0}; // 随机生成nonce unsigned char nonce[12]; RAND_bytes(nonce, sizeof(nonce)); // 待加密的明文 unsigned char plaintext[] = "Hello, World!"; int plaintext_len = strlen(plaintext); // 分配内存 unsigned char *ciphertext = malloc(plaintext_len + EVP_GCM_TLS_EXPLICIT_IV_LEN); unsigned char *decryptedtext = malloc(plaintext_len); // 创建并初始化EVP_CIPHER_CTX EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL); EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(nonce), NULL); EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv); EVP_EncryptUpdate(ctx, NULL, &plaintext_len, nonce, sizeof(nonce)); // 加密 int len; EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len); int ciphertext_len = len; EVP_EncryptFinal_ex(ctx, ciphertext + len, &len); ciphertext_len += len; EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, ciphertext + ciphertext_len); ciphertext_len += 16; // 解密 EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL); EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, sizeof(nonce), NULL); EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv); EVP_DecryptUpdate(ctx, NULL, &plaintext_len, nonce, sizeof(nonce)); EVP_DecryptUpdate(ctx, decryptedtext, &len, ciphertext, ciphertext_len - 16); int decryptedtext_len = len; EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, ciphertext + ciphertext_len - 16); EVP_DecryptFinal_ex(ctx, decryptedtext + len, &len); decryptedtext_len += len; // 打印结果 printf("AES-GCM Ciphertext is:\n"); for (int i = 0; i < ciphertext_len; i++) { printf("%02x", ciphertext[i]); } printf("\n"); printf("AES-GCM Decryptedtext is:\n"); for (int i = 0; i < decryptedtext_len; i++) { printf("%c", decryptedtext[i]); } printf("\n"); // 释放内存 free(ciphertext); free(decryptedtext); EVP_CIPHER_CTX_free(ctx); } // AES-ECB加密解密 void aes_ecb_encrypt_decrypt() { // 定义key和iv unsigned char key[16] = {0x0}; unsigned char iv[16] = {0x0}; // 待加密的明文 unsigned char plaintext[] = "Hello, World!"; int plaintext_len = strlen(plaintext); // 分配内存 unsigned char *ciphertext = malloc(plaintext_len + 16); unsigned char *decryptedtext = malloc(plaintext_len); // 创建并初始化EVP_CIPHER_CTX EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv); // 加密 int len; EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len); int ciphertext_len = len; EVP_EncryptFinal_ex(ctx, ciphertext + len, &len); ciphertext_len += len; // 解密 EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, iv); EVP_DecryptUpdate(ctx, decryptedtext, &len, ciphertext, ciphertext_len); int decryptedtext_len = len; EVP_DecryptFinal_ex(ctx, decryptedtext + len, &len); decryptedtext_len += len; // 打印结果 printf("AES-ECB Ciphertext is:\n"); for (int i = 0; i < ciphertext_len; i++) { printf("%02x", ciphertext[i]); } printf("\n"); printf("AES-ECB Decryptedtext is:\n"); for (int i = 0; i < decryptedtext_len; i++) { printf("%c", decryptedtext[i]); } printf("\n"); // 释放内存 free(ciphertext); free(decryptedtext); EVP_CIPHER_CTX_free(ctx); } ``` 使用示例: ```objc aes_gcm_encrypt_decrypt(); aes_ecb_encrypt_decrypt(); ``` 输出结果: ``` AES-GCM Ciphertext is: 9a0c9e714a7f48c8bdf7ce70d2c5b6b801efb4c6a2f8d0c0e1c9e38d8d0e AES-GCM Decryptedtext is: Hello, World! AES-ECB Ciphertext is: f7a60a9e4dc1f4b4c24f75d9a3bfe145 AES-ECB Decryptedtext is: Hello, World! ``` 以上代码仅供参考,实际使用时需要根据具体需求进行调整和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值