1 /**
 2  * AES加解密
 3  */
 4 public class AESHelper {
 5     final static String AES_KEY = "43hr8fhu34b58123";
 6
 7     /**
 8      * AES加密
 9      *
10      * @param text
11      * 待加密字符串
12      * @return 加密后字符串
13      */
14     public static String AESEncrypt(String text) {
15         try {
16             String password = AES_KEY;
17             SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES");
18             Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
19             cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
20             String strTmp = Base64.encodeToString(cipher.doFinal(text.getBytes()), Base64.DEFAULT);
21             return strTmp;
22         } catch (Exception e) {
23             e.printStackTrace();
24         }
25         return text;
26     }
27
28     /**
29      * AES解密
30      *
31      * @param text
32      * 待解密字符串
33      * @return 解密后字符串
34      */
35     public static String aesDecrypt(String text) {
36         try {
37             String password = AES_KEY;
38             SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES");
39             Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
40             cipher.init(Cipher.DECRYPT_MODE, skeySpec);
41             String strTmp = new String(cipher.doFinal(Base64.decode(text, Base64.DEFAULT)));
42             return strTmp;
43         } catch (Exception ex) {
44             ex.printStackTrace();
45         }
46         return text;
47     }
48 } 

Java

 1 public class AESHelper
 2     {
 3         const string AES_KEY = "43hr8fhu34b58123";
 4
 5         /// <summary>
 6         /// AES加密
 7         /// </summary>
 8         /// <param name="Text">待加密字符串</param>
 9         /// <returns>加密后字符串</returns>
10         public static string AESEncrypt(string Text)
11         {
12             try
13             {
14                 string key = AES_KEY;
15                 //分组加密算法
16                 AesCryptoServiceProvider aes =new AesCryptoServiceProvider();
17                 byte[] inputByteArray = Encoding.UTF8.GetBytes(Text);//得到需要加密的字节数组
18                 //设置密钥及密钥向量
19                 aes.Key = Encoding.UTF8.GetBytes(key);
20                 //aes.IV = Encoding.UTF8.GetBytes(key);
21                 aes.Mode = CipherMode.ECB;
22                 aes.Padding = PaddingMode.PKCS7;
23                 byte[] cipherBytes = null;
24                 using (MemoryStream ms = new MemoryStream())
25                 {
26                     using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
27                     {
28                         cs.Write(inputByteArray, 0, inputByteArray.Length);
29                         cs.FlushFinalBlock();
30                         cipherBytes = ms.ToArray();//得到加密后的字节数组
31                         cs.Close();
32                         ms.Close();
33                     }
34                 }
35                 return Convert.ToBase64String(cipherBytes);
36             }
37             catch { }
38             return Text;
39         }
40
41         /// <summary>
42         /// AES解密
43         /// </summary>
44         /// <param name="Text">待解密字符串</param>
45         /// <returns>解密后字符串</returns>
46         public static string AESDecrypt(string Text)
47         {
48             try
49             {
50                 string key = AES_KEY;
51                 byte[] cipherText = Convert.FromBase64String(Text);
52                 AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
53                 aes.Key = Encoding.UTF8.GetBytes(key);
54                 //aes.IV = Encoding.UTF8.GetBytes(key);
55                 aes.Mode = CipherMode.ECB;
56                 aes.Padding = PaddingMode.PKCS7;
57                 byte[] decryptBytes = new byte[cipherText.Length];
58                 using (MemoryStream ms = new MemoryStream(cipherText))
59                 {
60                     using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
61                     {
62                         cs.Read(decryptBytes, 0, decryptBytes.Length);
63                         cs.Close();
64                         ms.Close();
65                     }
66                 }
67                 return Encoding.UTF8.GetString(decryptBytes).Replace("\0", "");   //将字符串后尾的'\0'去掉
68             }
69             catch { }
70             return Text;
71         }
72     }  

C#

  1 /*
  2  *.h文件
  3  */
  4 #import <Foundation/Foundation.h>
  5
  6 @interface Security : NSObject
  7 +(NSString*)AesEncrypt:(NSString*)str;
  8 +(NSString*)AesDecrypt:(NSString*)str;
  9 @end
 10
 11 --------------------------------------------------------------------------------
 12
 13 /*
 14  *.m文件
 15  */
 16 #import "Security.h"
 17 #import <CommonCrypto/CommonCryptor.h>
 18 static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 19 #define LocalStr_None @"" //空字符串
 20
 21 @implementation Security
 22
 23 /*
 24  * AES加密
 25  *
 26  */
 27 +(NSString*)AesEncrypt:(NSString*)str{
 28     NSString *key=@"43hr8fhu34b58123"; // 密钥
 29     NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding]; // 待加密字符转为NSData型
 30     char keyPtr[kCCKeySizeAES128 + 1];
 31     memset(keyPtr, 0, sizeof(keyPtr));
 32     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
 33
 34     NSUInteger dataLength = [data length];
 35     size_t bufferSize = dataLength + kCCBlockSizeAES128;
 36     voidvoid *buffer = malloc(bufferSize);
 37
 38     size_t numBytesCrypted = 0;
 39     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
 40                                           kCCAlgorithmAES128,
 41                                           kCCOptionPKCS7Padding|kCCOptionECBMode,
 42                                           keyPtr,
 43                                           kCCBlockSizeAES128,
 44                                           nil,
 45                                           [data bytes],
 46                                           dataLength,
 47                                           buffer,
 48                                           bufferSize,
 49                                           &numBytesCrypted);
 50     if (cryptStatus == kCCSuccess) {
 51         NSData *resultData=[NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
 52         NSString *result =[self base64EncodedStringFrom:resultData];
 53         return result;
 54     }
 55     free(buffer);
 56     return str;
 57 }
 58
 59 /*
 60  * AES解密
 61  *
 62  */
 63 +(NSString*)AesDecrypt:(NSString*)str{
 64     NSString *key=@"Q*1_3@c!4kd^j&g%"; // 密钥
 65     NSData *data=[self dataWithBase64EncodedString:str]; // base4解码
 66     char keyPtr[kCCKeySizeAES128 + 1];
 67     memset(keyPtr, 0, sizeof(keyPtr));
 68     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
 69
 70     NSUInteger dataLength = [data length];
 71     size_t bufferSize = dataLength + kCCBlockSizeAES128;
 72     voidvoid *buffer = malloc(bufferSize);
 73
 74     size_t numBytesCrypted = 0;
 75     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
 76                                           kCCAlgorithmAES128,
 77                                           kCCOptionPKCS7Padding|kCCOptionECBMode,
 78                                           keyPtr,
 79                                           kCCBlockSizeAES128,
 80                                           nil,
 81                                           [data bytes],
 82                                           dataLength,
 83                                           buffer,
 84                                           bufferSize,
 85                                           &numBytesCrypted);
 86     if (cryptStatus == kCCSuccess) {
 87         NSData *resultData=[NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
 88         NSString *result =[[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
 89         return result;
 90     }
 91     free(buffer);
 92     return str;
 93 }
 94
 95
 96 + (NSString *)base64StringFromText:(NSString *)text
 97 {
 98     if (text && ![text isEqualToString:LocalStr_None]) {
 99         NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
100         return [self base64EncodedStringFrom:data];
101     }
102     else {
103         return LocalStr_None;
104     }
105 }
106
107 + (NSString *)textFromBase64String:(NSString *)base64
108 {
109     if (base64 && ![base64 isEqualToString:LocalStr_None]) {
110         NSData *data = [self dataWithBase64EncodedString:base64];
111         return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
112     }
113     else {
114         return LocalStr_None;
115     }
116 }
117
118 + (NSData *)dataWithBase64EncodedString:(NSString *)string
119 {
120     if (string == nil)
121         [NSException raise:NSInvalidArgumentException format:nil];
122     if ([string length] == 0)
123         return [NSData data];
124
125     static charchar *decodingTable = NULL;
126     if (decodingTable == NULL)
127     {
128         decodingTable = malloc(256);
129         if (decodingTable == NULL)
130             return nil;
131         memset(decodingTable, CHAR_MAX, 256);
132         NSUInteger i;
133         for (i = 0; i < 64; i++)
134             decodingTable[(short)encodingTable[i]] = i;
135     }
136
137     const charchar *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
138     if (characters == NULL)     //  Not an ASCII string!
139         return nil;
140     charchar *bytes = malloc((([string length] + 3) / 4) * 3);
141     if (bytes == NULL)
142         return nil;
143     NSUInteger length = 0;
144
145     NSUInteger i = 0;
146     while (YES)
147     {
148         char buffer[4];
149         short bufferLength;
150         for (bufferLength = 0; bufferLength < 4; i++)
151         {
152             if (characters[i] == '\0')
153                 break;
154             if (isspace(characters[i]) || characters[i] == '=')
155                 continue;
156             buffer[bufferLength] = decodingTable[(short)characters[i]];
157             if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!
158             {
159                 free(bytes);
160                 return nil;
161             }
162         }
163
164         if (bufferLength == 0)
165             break;
166         if (bufferLength == 1)      //  At least two characters are needed to produce one byte!
167         {
168             free(bytes);
169             return nil;
170         }
171
172         //  Decode the characters in the buffer to bytes.
173         bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
174         if (bufferLength > 2)
175             bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
176         if (bufferLength > 3)
177             bytes[length++] = (buffer[2] << 6) | buffer[3];
178     }
179
180     bytes = realloc(bytes, length);
181     return [NSData dataWithBytesNoCopy:bytes length:length];
182 }
183
184 + (NSString *)base64EncodedStringFrom:(NSData *)data
185 {
186     if ([data length] == 0)
187         return @"";
188
189     charchar *characters = malloc((([data length] + 2) / 3) * 4);
190     if (characters == NULL)
191         return nil;
192     NSUInteger length = 0;
193
194     NSUInteger i = 0;
195     while (i < [data length])
196     {
197         char buffer[3] = {0,0,0};
198         short bufferLength = 0;
199         while (bufferLength < 3 && i < [data length])
200             buffer[bufferLength++] = ((charchar *)[data bytes])[i++];
201
202         //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
203         characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
204         characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
205         if (bufferLength > 1)
206             characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
207         else characters[length++] = '=';
208         if (bufferLength > 2)
209             characters[length++] = encodingTable[buffer[2] & 0x3F];
210         else characters[length++] = '=';
211     }
212
213     return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
214 }
215
216 @end  

Objective-C

转载于:https://www.cnblogs.com/sater/p/7018784.html

java C# objective-c AES对称加解密相关推荐

  1. Java使用PBE算法进行对称加解密最简入门和示例

    PBE 算法 PBE( Password Based Encryption, 基于口密加密).PBE是一种基于口令的加密算法, 采用随机数杂凑(盐)多重加密方法保证数据安全性. PBE算法并没有真正构 ...

  2. 前端利用CryptoJS进行AES对称加解密(16进制编码)

    加密相关JS https://www.npmjs.com/package/crypto-js 引入JS 使用示例: =附上原文代码方便大家自由使用=========== //============= ...

  3. java 和 c# 下的RSA证书+AES+DES加解密实现

    java 和 c# 下的RSA+AES+DES加解密实现 前言 在实际应用中,经常有需要使用加解密的情况,RSA\AES\DES是比较常用的几种加解密方式,使用和实现方式都比较成熟可靠,本文简要介绍一 ...

  4. [crypto]-02-非对称加解密RSA原理概念详解

    说明:本文使用的数据来自网络,重复的太多了,也不知道哪篇是原创. 算法原理介绍 step 说明 描述 备注 1 找出质数 P .Q - 2 计算公共模数 N = P * Q - 3 欧拉函数 φ(N) ...

  5. AES实现加解密-Java

    一.加解密算法生态圈 目前的数据加密技术根据加密密钥类型可分私钥加密(对称加密)系统和公钥加密(非对称加密)系统.对称加密算法是较传统的加密体制,通信双方在加/解密过程中使用他们共享的单一密钥,鉴于其 ...

  6. android byte转string_高性能AES256对称加解密,兼容Java、IOS、Android

    最近在设计一个给IOS和Android提供接口的项目框架,在接口安全上准备使用常规的加密技术,确保在非法访问接口的情况下拿到的数据一时半会也没用. 查了相关的资料,用的最多的几种加密算法,DES.AE ...

  7. AES方式加解密的简单介绍

    上面一篇文章介绍了使用DES方式进行加解密( DES方式加解密的简单介绍),我们说了DES由于使用8个字节(64bit)密钥进行加解密,所以安全性不够(当然这里的不够都是相对的),所以现在使用了密钥更 ...

  8. SpringBoot+Vue中使用AES进行加解密(加密模式等对照关系)

    场景 若依前后端分离版本地搭建开发环境并运行项目的教程: 若依前后端分离版手把手教你本地搭建环境并运行项目_霸道流氓气质的博客-CSDN博客 在上面搭建起来前后端架构之后,在前后端分别进行AES方式的 ...

  9. 程序猿成长之路番外篇之前后端加解密(rsa+aes混合加解密算法)

    今年国庆前夕接手一个外部项目,说是要保障接口数据安全,数据安全相对容易些,接口安全嘛emmmmm, 这个要考虑加解密算法.白名单之类的问题了.于是打算今天搞一期接口安全为题的成长之路番外篇. 为什么要 ...

最新文章

  1. TypeKit ,use online fonts
  2. 为何学习新知识这么难?因为大脑可能比你想象中更死板
  3. python语言怎么用-科学家们是如何使用 Python 语言的?
  4. 【PP操作手册】运行MRP产生计划订单
  5. Android之Debug运行项目一直卡在Debug界面(can‘t bind to local 8066 for debug)
  6. jQuery验证validate插件
  7. 使用Nagios打造专业的业务状态监控
  8. java开发app的缺点_App原生开发的优缺点有哪些
  9. 怎样去构建一个优质的Docker容器镜像
  10. FastAPI + Vue 前后端分离 接口自动化测试工具 apiAutoTestWeb
  11. javascript的getElementByTagName
  12. 商城 源码 java_java网上商城平台源码(含数据库脚本)
  13. 高等数学张宇18讲 第十一讲 二重积分
  14. Word——如何给公式自动编号插入题注交叉引用时不出现公式本身||公式行距变大怎么办
  15. Windows常用操作—热键(快捷键)
  16. 《萌小甜动图字帖》使用简介
  17. java中斜杠/和反斜杠\
  18. (转载)虚幻引擎3--【UnrealScript教程】章节一:11.Struct结构体
  19. 基于目标检测的海上舰船图像超分辨率研究
  20. 利用HTA文件绕过杀软及邮件钓⻥

热门文章

  1. (转) 各种好用的插件 Xcode
  2. Asp.net MVC4 Knockoutjs BootStrap Ace NinJect Jqgrid sqlserver2008
  3. FASTSCRIPT脚本实现多国语言
  4. 99乘法表(java版)
  5. 13 款高逼格且实用的 Linux 运维必备工具
  6. jQuery——子元素筛选器
  7. c#对数据库访问完应关闭连接
  8. D3中数据与DOM element绑定之data() enter() exit()浅析
  9. 不一样的结果,不一样的人生
  10. Android--使用Canvas绘图