由于业务需求,需要实现在客户端对重要信息进行加密,在服务端进行解密。客户端包括IOS和安卓的 服务端位Java。

注意密钥 需要保持一致,可以自己定义 。

安卓端加密代码:

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

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; public class SymmetricEncoder { private static final String IV_STRING = "A-16-Byte-String";
private static final String charset = "UTF-8"; /**
*
* @param content 要加密的内容
* @param key 16位加密密钥
* @return
* @throws Exception
*/
public static String aesEncryptHexStr(String content, String key) throws Exception
{
return str2HexStr(aesEncryptString(content,key));
}
public static String aesEncryptString(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] contentBytes = content.getBytes(charset);
byte[] keyBytes = key.getBytes(charset);
byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes);
return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP);
} /**
* 字符串转换成十六进制字符串
* @return String 每个Byte之间空格分隔,如: [61 6C 6B]
*/
public static String str2HexStr(String str)
{ char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit; for (int i = 0; i < bs.length; i++)
{
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString().trim();
}
public static String aesDecryptString(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] encryptedBytes = Base64.decode(content.getBytes(), Base64.NO_WRAP);
byte[] keyBytes = key.getBytes(charset);
byte[] decryptedBytes = aesDecryptBytes(encryptedBytes, keyBytes);
return new String(decryptedBytes, charset);
} public static byte[] aesEncryptBytes(byte[] contentBytes, byte[] keyBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
return cipherOperation(contentBytes, keyBytes, Cipher.ENCRYPT_MODE);
} public static byte[] aesDecryptBytes(byte[] contentBytes, byte[] keyBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
return cipherOperation(contentBytes, keyBytes, Cipher.DECRYPT_MODE);
} private static byte[] cipherOperation(byte[] contentBytes, byte[] keyBytes, int mode) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES"); byte[] initParam = IV_STRING.getBytes(charset);
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(mode, secretKey, ivParameterSpec); return cipher.doFinal(contentBytes);
} public static void main(String args[]){
try {
// 要加密的内容 加密的密钥
SymmetricEncoder.aesEncryptHexStr("xiaoming9999","ABCDEFGHIJKLMNOP");
} catch (Exception e) {
e.printStackTrace();
}
} }

IOS 端加密:

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

//  AESCipher.h
#import <Foundation/Foundation.h> NSString * aesEncryptString(NSString *content, NSString *key);
NSString * aesEncryptHexStr(NSString *content, NSString *key);//16进制表现形式
NSString * aesDecryptString(NSString *content, NSString *key);
NSString * hexStringFromString(NSString *string); NSData * aesEncryptData(NSData *data, NSData *key);
NSData * aesDecryptData(NSData *data, NSData *key);
//
// AESCipher.m
// AESCipher
// #import "AESCipher.h"
#import <CommonCrypto/CommonCryptor.h> NSString const *kInitVector = @"A-16-Byte-String";
size_t const kKeySize = kCCKeySizeAES128; NSData * cipherOperation(NSData *contentData, NSData *keyData, CCOperation operation) {
NSUInteger dataLength = contentData.length; void const *initVectorBytes = [kInitVector dataUsingEncoding:NSUTF8StringEncoding].bytes;
void const *contentBytes = contentData.bytes;
void const *keyBytes = keyData.bytes; size_t operationSize = dataLength + kCCBlockSizeAES128;
void *operationBytes = malloc(operationSize);
size_t actualOutSize = ; CCCryptorStatus cryptStatus = CCCrypt(operation,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyBytes,
kKeySize,
initVectorBytes,
contentBytes,
dataLength,
operationBytes,
operationSize,
&actualOutSize); if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:operationBytes length:actualOutSize];
}
free(operationBytes);
return nil;
} NSString * aesEncryptString(NSString *content, NSString *key) {
NSData *contentData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *encrptedData = aesEncryptData(contentData, keyData);
return [encrptedData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
} NSString * aesEncryptHexStr(NSString *content, NSString *key){
NSString *str=aesDecryptString(content,key);
return hexStringFromString(str);
} //普通字符串转换为十六进制的。
NSString * hexStringFromString(NSString *string){
NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
Byte *bytes = (Byte *)[myD bytes];
//下面是Byte 转换为16进制。
NSString *hexStr=@"";
for(int i=;i<[myD length];i++)
{
NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
if([newHexStr length]==)
hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
else
hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
}
return hexStr;
} NSString * aesDecryptString(NSString *content, NSString *key) {
NSData *contentData = [[NSData alloc] initWithBase64EncodedString:content options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSData *decryptedData = aesDecryptData(contentData, keyData);
return [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
} NSData * aesEncryptData(NSData *contentData, NSData *keyData) {
NSString *hint = [NSString stringWithFormat:@"The key size of AES-%lu should be %lu bytes!", kKeySize * , kKeySize];
NSCAssert(keyData.length == kKeySize, hint);
return cipherOperation(contentData, keyData, kCCEncrypt);
} NSData * aesDecryptData(NSData *contentData, NSData *keyData) {
NSString *hint = [NSString stringWithFormat:@"The key size of AES-%lu should be %lu bytes!", kKeySize * , kKeySize];
NSCAssert(keyData.length == kKeySize, hint);
return cipherOperation(contentData, keyData, kCCDecrypt);
}

调用方式:

1、引入#import "AESCipher.h" 文件

2、

NSString *userID = aesEncryptHexStr([NSString stringWithFormat:@"%@;%@",userID,userPassword],@"ABCDEFGHIJKLMNOP");

JAVA服务端解密:

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

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; public class SymmetricEncoder { private static final String IV_STRING = "A-16-Byte-String";
private static final String charset = "UTF-8"; public static String aesEncryptString(String content, String key)
throws InvalidKeyException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException,
UnsupportedEncodingException {
byte[] contentBytes = content.getBytes(charset);
byte[] keyBytes = key.getBytes(charset);
byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes);
//Encoder encoder = Base64.getEncoder();
return new BASE64Encoder().encode((encryptedBytes));
} public static String aesDecryptString(String content, String key)
throws Exception {
//Decoder decoder = Base64.getDecoder();
byte[] encryptedBytes = new BASE64Decoder().decodeBuffer(content);
byte[] keyBytes = key.getBytes(charset);
byte[] decryptedBytes = aesDecryptBytes(encryptedBytes, keyBytes);
return new String(decryptedBytes, charset);
} public static byte[] aesEncryptBytes(byte[] contentBytes, byte[] keyBytes)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException,
UnsupportedEncodingException {
return cipherOperation(contentBytes, keyBytes, Cipher.ENCRYPT_MODE);
} public static byte[] aesDecryptBytes(byte[] contentBytes, byte[] keyBytes)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException,
UnsupportedEncodingException {
return cipherOperation(contentBytes, keyBytes, Cipher.DECRYPT_MODE);
} private static byte[] cipherOperation(byte[] contentBytes, byte[] keyBytes,
int mode) throws UnsupportedEncodingException,
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES"); byte[] initParam = IV_STRING.getBytes(charset);
IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(mode, secretKey, ivParameterSpec); return cipher.doFinal(contentBytes);
}
/**
* 十六进制转换字符串
* @param String str Byte字符串(Byte之间无分隔符 如:[616C6B])
* @return String 对应的字符串
*/
public static String hexStr2Str(String hexStr)
{
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n; for (int i = 0; i < bytes.length; i++)
{
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}public static String aesDecryptHexStr(String aecStr,String key) throws Exception{
return SymmetricEncoder.aesDecryptString(SymmetricEncoder.hexStr2Str(aecStr),key);
} public static void main(String args[]){
try { String ss="364453613168592F4E68532F4F75306C7A72585459754F62686E43777475377733363339476278514468773D";
System.out.println(SymmetricEncoder.aesDecryptHexStr(ss, "ABCDEFGHIJKLMNOP"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

安卓、IOS端AEC密钥加密 Java端密钥解密通用实现(16进制表现形式)的更多相关文章

  1. java 将数字转成成16进制

      java 将数字转成成16进制 CreationTime--2018年6月11日17点11分 Author:Marydon 1.前提 数字必须是byte类型,即[-128,127] 2.代码实现 ...

  2. Java 将字节数组转化为16进制的多种方案

    很多时候我们需要将字节数组转化为16进制字符串来保存,尤其在很多加密的场景中,例如保存密钥等.因为字节数组,除了写入文件或者以二进制的形式写入数据库以外,无法直接转为为字符串,因为字符串结尾有\0,当 ...

  3. java中把字节数组转换为16进制字符串

    把字符串数组转换为16进制字符串 import java.security.MessageDigest; public class StringUtil { public StringUtil() { ...

  4. java标签(label)求16进制字符串的整数和 把一个整数转为4个16进制字符表示

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Menlo; color: #4f76cb } p.p2 { margin: 0.0px 0. ...

  5. JAVA中将byte[]数组转成16进制字符串

    方法一: /** * byte数组转化为16进制字符串 * @param bytes * @return */ public static String byteToHexString(byte[] ...

  6. java byte数组与16进制间的相互转换

      java byte数组与16进制间的相互转换 CreationTime--2018年6月11日15点34分 Author:Marydon 1.准备工作 import java.util.Array ...

  7. 【java】RC4加密转16进制获取长度为40的不重复优惠码字符串 【未优化版本】

    需求:需要一串给各机构独有的优惠码 间接需求:固定长度.不重复.没有规律可循 实现思想如下: 1.首先获取一个UUID 2.去除UUID中的“-” 3.小写转大写 4.获取一个固定长度字符串 5.按照 ...

  8. java字符串MD5加密后再转16进制

    话不多说上码 pom.xml <!-- MD5 --> <dependency> <groupId>org.apache.commons</groupId&g ...

  9. AES加密 16进制与二进制转换

    import java.security.Key; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax ...

随机推荐

  1. pkusc2019游记

    Day0 早上 6:55 的高铁,6 点就起了,好困呜呜呜 去的路上跟 memset0 坐一起,突然发现雀魂还没停服,先雀了一局(居然拿了个 1 位还飞了一个人),与此同时 memset0 切了一道毒 ...

  2. 解决node.js链接数据库时出现的报错 --- client does not support authentication

    打开mysql数据库小黑屏 然后输入 mysql> alter user 'root'@'localhost' identified with mysql_native_password by ...

  3. SpringBoot:认认真真梳理一遍自动装配原理

    前言 Spring翻译为中文是“春天”,的确,在某段时间内,它给Java开发人员带来过春天,但是随着我们项目规模的扩大,Spring需要配置的地方就越来越多,夸张点说,“配置两小时,Coding五分钟 ...

  4. 8.8poc包问题

    对于8.8的包的问题:zabbix server设备重启后 zabbix server,mariadb,zabbix agent启动不了.是因为在7代的centos中在主机重启后.自动删除了/var/ ...

  5. 前端零基础入门:页面结构层HTML(3)

    搭建网页HTML结构 标签 标签 块级标签 和 行内标签 标签嵌套规则 和 div css 标签是一个区块容器标记, 之间是一个容器,可以包含段落,表格,图片等各种HTML元素. 标签没有实际意义,为 ...

  6. nginx之TCP反向代理

    实现Nginx tcp负载均衡 Nginx在1.9.0版本开始支持tcp模式的负载均衡,在1.9.13版本开始支持udp协议的负载,udp主要用于DNS的域名解析,其配置方式和指令和http 代理类似 ...

  7. keepalived haproxy 主备配置

    global_defs { router_id k8s_master} vrrp_script chk_http_port {script "/etc/keepalived/check_ha ...

  8. hdu1276士兵队列训练问题[简单STL list]

    目录 题目地址 题干 代码和解释 题目地址 hdu1276 题干 代码和解释 本题使用了STL中的list,STL的list是双向链表.它的内存空间不必连续,通过指针来进行数据的访问,高效率地在任意地 ...

  9. js数组reduce()方法的使用和一些应用场景

    reduce()的使用 reduce()方法为归并类方法,最常见的应用场景就是,计算数组中每一项的总和. reduce()方法会遍历数组的每一项,它接收两个参数: 第一个参数是:每次遍历都会调用的函数 ...

  10. js待学习

    异步原理 事件循环 任务队列