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, , 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, , 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 + ];
  31. memset(keyPtr, , 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 = ;
  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 + ];
  67. memset(keyPtr, , 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 = ;
  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. + (NSString *)base64StringFromText:(NSString *)text
  96. {
  97. if (text && ![text isEqualToString:LocalStr_None]) {
  98. NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
  99. return [self base64EncodedStringFrom:data];
  100. }
  101. else {
  102. return LocalStr_None;
  103. }
  104. }
  105.  
  106. + (NSString *)textFromBase64String:(NSString *)base64
  107. {
  108. if (base64 && ![base64 isEqualToString:LocalStr_None]) {
  109. NSData *data = [self dataWithBase64EncodedString:base64];
  110. return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  111. }
  112. else {
  113. return LocalStr_None;
  114. }
  115. }
  116.  
  117. + (NSData *)dataWithBase64EncodedString:(NSString *)string
  118. {
  119. if (string == nil)
  120. [NSException raise:NSInvalidArgumentException format:nil];
  121. if ([string length] == )
  122. return [NSData data];
  123.  
  124. static charchar *decodingTable = NULL;
  125. if (decodingTable == NULL)
  126. {
  127. decodingTable = malloc();
  128. if (decodingTable == NULL)
  129. return nil;
  130. memset(decodingTable, CHAR_MAX, );
  131. NSUInteger i;
  132. for (i = ; i < ; i++)
  133. decodingTable[(short)encodingTable[i]] = i;
  134. }
  135.  
  136. const charchar *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
  137. if (characters == NULL) // Not an ASCII string!
  138. return nil;
  139. charchar *bytes = malloc((([string length] + ) / ) * );
  140. if (bytes == NULL)
  141. return nil;
  142. NSUInteger length = ;
  143.  
  144. NSUInteger i = ;
  145. while (YES)
  146. {
  147. char buffer[];
  148. short bufferLength;
  149. for (bufferLength = ; bufferLength < ; i++)
  150. {
  151. if (characters[i] == '\0')
  152. break;
  153. if (isspace(characters[i]) || characters[i] == '=')
  154. continue;
  155. buffer[bufferLength] = decodingTable[(short)characters[i]];
  156. if (buffer[bufferLength++] == CHAR_MAX) // Illegal character!
  157. {
  158. free(bytes);
  159. return nil;
  160. }
  161. }
  162.  
  163. if (bufferLength == )
  164. break;
  165. if (bufferLength == ) // At least two characters are needed to produce one byte!
  166. {
  167. free(bytes);
  168. return nil;
  169. }
  170.  
  171. // Decode the characters in the buffer to bytes.
  172. bytes[length++] = (buffer[] << ) | (buffer[] >> );
  173. if (bufferLength > )
  174. bytes[length++] = (buffer[] << ) | (buffer[] >> );
  175. if (bufferLength > )
  176. bytes[length++] = (buffer[] << ) | buffer[];
  177. }
  178.  
  179. bytes = realloc(bytes, length);
  180. return [NSData dataWithBytesNoCopy:bytes length:length];
  181. }
  182.  
  183. + (NSString *)base64EncodedStringFrom:(NSData *)data
  184. {
  185. if ([data length] == )
  186. return @"";
  187.  
  188. charchar *characters = malloc((([data length] + ) / ) * );
  189. if (characters == NULL)
  190. return nil;
  191. NSUInteger length = ;
  192.  
  193. NSUInteger i = ;
  194. while (i < [data length])
  195. {
  196. char buffer[] = {,,};
  197. short bufferLength = ;
  198. while (bufferLength < && i < [data length])
  199. buffer[bufferLength++] = ((charchar *)[data bytes])[i++];
  200.  
  201. // Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
  202. characters[length++] = encodingTable[(buffer[] & 0xFC) >> ];
  203. characters[length++] = encodingTable[((buffer[] & 0x03) << ) | ((buffer[] & 0xF0) >> )];
  204. if (bufferLength > )
  205. characters[length++] = encodingTable[((buffer[] & 0x0F) << ) | ((buffer[] & 0xC0) >> )];
  206. else characters[length++] = '=';
  207. if (bufferLength > )
  208. characters[length++] = encodingTable[buffer[] & 0x3F];
  209. else characters[length++] = '=';
  210. }
  211.  
  212. return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
  213. }
  214.  
  215. @end

Objective-C

java C# objective-c AES对称加解密的更多相关文章

  1. AES对称加解密

    简介设计思想加密模式ECB模式(电子密码本模式:Electronic codebook)CBC模式(密码分组链接:Cipher-block chaining)CFB模式(密文反馈:Cipher fee ...

  2. Asp.Net Core 2.0 项目实战(7)MD5加密、AES&DES对称加解密

    本文目录 1. 摘要 2. MD5加密封装 3. AES的加密.解密 4. DES加密/解密 5. 总结 1.  摘要 C#中常用的一些加密和解密方案,如:md5加密.RSA加密与解密和DES加密等, ...

  3. AES对称加密解密类

    import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.Se ...

  4. php des 对称加解密类

    <?php header("Content-Type: text/html;charset=utf-8"); /** * des 对称加解密 */ class des { p ...

  5. node.js 实现 AES CTR 加解密

    node.js 实现 AES CTR 加解密 node aesctr 前言 由于最近我们在做一款安全的文件分享 App, 所有文件均需要使用 aes ctr 来进行加密,aes key 还有一整套完整 ...

  6. 最新版-Python和Java实现Aes相互加解密

    前情 需要使用Python和Java实现同一个AES加解密算法,使Python版本加密的密文能够由Java代码解密,反之亦然. Python实现 Python为3.6版本 # -*- coding: ...

  7. JAVA AES文件加解密

    AES加解密算法,代码如下: /** * Created by hua on 2017/6/30. */ import javax.crypto.Cipher; import javax.crypto ...

  8. Java拓展教程:文件DES加解密

    Java拓展教程:文件加解密 Java中的加密解密技术 加密技术根据一般可以分为对称加密技术和非对称加密技术.对称加密技术属于传统的加密技术,它的加密和解密的密钥是相同的,它的优点是:运算速度快,加密 ...

  9. JAVA和PYTHON同时实现AES的加密解密操作---且生成的BASE62编码一致

    终于有机会生产JAVA的东东了. 有点兴奋. 花了一天搞完.. java(关键key及算法有缩减): package com.security; import javax.crypto.Cipher; ...

随机推荐

  1. linux清理磁盘

    https://blog.csdn.net/u012660464/article/details/78923011 有时候,服务突然挂了,再次启动却启动不了.一看,原来是磁盘空间被占满啦,那么,怎么清 ...

  2. ASP.NET OAuth 2.0 新手上路

    OAuth2.0资料 初衷:一直想整理授权系列demo,让自己项目高端大尚,列出新手授权系列,帮助小白程序员不用在为授权头疼 OAuth 允许用户提供一个令牌,而不是用户名和密码来访问他们存放在特定服 ...

  3. Android 音频系统得框架

    http://www.mamicode.com/info-detail-1790053.html http://blog.csdn.net/lushengchu_luis/article/detail ...

  4. ClamAV学习【7】——病毒库文件格式学习

    搜查到一份详细的ClamAV病毒文件格式资料(http://download.csdn.net/detail/betabin/4215909),英文版,国内这资料不多的感觉. 重点看了下有关PE的病毒 ...

  5. NOIP2013PUZZLE

    #include<cstdio> #include<cstring> #define MIN(A,B) (A)<(B)?(A):(B) using namespace s ...

  6. 一次mysql主从同步问题及解决过程

    Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 由于经常被抓取文章内容,在此附上博 ...

  7. datatime模块

    https://www.cnblogs.com/cindy-cindy/p/6720196.html

  8. Linux磁盘及文件系统(一)

    一.磁盘 1.IO接口类型 (1)传输类型分类 并口:同一个线缆可以接多块设备 IDE口:两个,一个主设备,一个从设备 SCSI:宽带:16-1:窄带:8-1 串口:同一个线缆只可以接一个设备 (2) ...

  9. 【Qt】Qt在Windows下的开发与调试环境配置

    前文已经交待了从源码编译Qt自定义版本.现在可以开始配置一下开发与调试程序并写个Hello World了. 1. IDE 虽然Qt官方有VS插件使我们可以在VisualStudio中开发Qt应用,但我 ...

  10. kali系统越来越大解决

    Kali Linux系统提供的apt-get方式,可以很好的安装软件,对系统进行更新.但是每次执行都会下载大量的软件包.这些软件包被安装后,并不会被自动删掉,会持续占用磁盘空间.解决这个问题有两个办法 ...