/**
* AES加解密
*/
public class AESHelper {
final static String AES_KEY = "43hr8fhu34b58123"; /**
* AES加密
*
* @param text
* 待加密字符串
* @return 加密后字符串
*/
public static String AESEncrypt(String text) {
try {
String password = AES_KEY;
SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
String strTmp = Base64.encodeToString(cipher.doFinal(text.getBytes()), Base64.DEFAULT);
return strTmp;
} catch (Exception e) {
e.printStackTrace();
}
return text;
} /**
* AES解密
*
* @param text
* 待解密字符串
* @return 解密后字符串
*/
public static String aesDecrypt(String text) {
try {
String password = AES_KEY;
SecretKeySpec skeySpec = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
String strTmp = new String(cipher.doFinal(Base64.decode(text, Base64.DEFAULT)));
return strTmp;
} catch (Exception ex) {
ex.printStackTrace();
}
return text;
}
}

Java

 public class AESHelper
{
const string AES_KEY = "43hr8fhu34b58123"; /// <summary>
/// AES加密
/// </summary>
/// <param name="Text">待加密字符串</param>
/// <returns>加密后字符串</returns>
public static string AESEncrypt(string Text)
{
try
{
string key = AES_KEY;
//分组加密算法
AesCryptoServiceProvider aes =new AesCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(Text);//得到需要加密的字节数组
//设置密钥及密钥向量
aes.Key = Encoding.UTF8.GetBytes(key);
//aes.IV = Encoding.UTF8.GetBytes(key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] cipherBytes = null;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
cipherBytes = ms.ToArray();//得到加密后的字节数组
cs.Close();
ms.Close();
}
}
return Convert.ToBase64String(cipherBytes);
}
catch { }
return Text;
} /// <summary>
/// AES解密
/// </summary>
/// <param name="Text">待解密字符串</param>
/// <returns>解密后字符串</returns>
public static string AESDecrypt(string Text)
{
try
{
string key = AES_KEY;
byte[] cipherText = Convert.FromBase64String(Text);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = Encoding.UTF8.GetBytes(key);
//aes.IV = Encoding.UTF8.GetBytes(key);
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
byte[] decryptBytes = new byte[cipherText.Length];
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
cs.Read(decryptBytes, , decryptBytes.Length);
cs.Close();
ms.Close();
}
}
return Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""); //将字符串后尾的'\0'去掉
}
catch { }
return Text;
}
}

C#

 /*
*.h文件
*/
#import <Foundation/Foundation.h> @interface Security : NSObject
+(NSString*)AesEncrypt:(NSString*)str;
+(NSString*)AesDecrypt:(NSString*)str;
@end -------------------------------------------------------------------------------- /*
*.m文件
*/
#import "Security.h"
#import <CommonCrypto/CommonCryptor.h>
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#define LocalStr_None @"" //空字符串 @implementation Security /*
* AES加密
*
*/
+(NSString*)AesEncrypt:(NSString*)str{
NSString *key=@"43hr8fhu34b58123"; // 密钥
NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding]; // 待加密字符转为NSData型
char keyPtr[kCCKeySizeAES128 + ];
memset(keyPtr, , sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
voidvoid *buffer = malloc(bufferSize); size_t numBytesCrypted = ;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
nil,
[data bytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if (cryptStatus == kCCSuccess) {
NSData *resultData=[NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
NSString *result =[self base64EncodedStringFrom:resultData];
return result;
}
free(buffer);
return str;
} /*
* AES解密
*
*/
+(NSString*)AesDecrypt:(NSString*)str{
NSString *key=@"Q*1_3@c!4kd^j&g%"; // 密钥
NSData *data=[self dataWithBase64EncodedString:str]; // base4解码
char keyPtr[kCCKeySizeAES128 + ];
memset(keyPtr, , sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
voidvoid *buffer = malloc(bufferSize); size_t numBytesCrypted = ;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding|kCCOptionECBMode,
keyPtr,
kCCBlockSizeAES128,
nil,
[data bytes],
dataLength,
buffer,
bufferSize,
&numBytesCrypted);
if (cryptStatus == kCCSuccess) {
NSData *resultData=[NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
NSString *result =[[NSString alloc]initWithData:resultData encoding:NSUTF8StringEncoding];
return result;
}
free(buffer);
return str;
} + (NSString *)base64StringFromText:(NSString *)text
{
if (text && ![text isEqualToString:LocalStr_None]) {
NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];
return [self base64EncodedStringFrom:data];
}
else {
return LocalStr_None;
}
} + (NSString *)textFromBase64String:(NSString *)base64
{
if (base64 && ![base64 isEqualToString:LocalStr_None]) {
NSData *data = [self dataWithBase64EncodedString:base64];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
else {
return LocalStr_None;
}
} + (NSData *)dataWithBase64EncodedString:(NSString *)string
{
if (string == nil)
[NSException raise:NSInvalidArgumentException format:nil];
if ([string length] == )
return [NSData data]; static charchar *decodingTable = NULL;
if (decodingTable == NULL)
{
decodingTable = malloc();
if (decodingTable == NULL)
return nil;
memset(decodingTable, CHAR_MAX, );
NSUInteger i;
for (i = ; i < ; i++)
decodingTable[(short)encodingTable[i]] = i;
} const charchar *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
if (characters == NULL) // Not an ASCII string!
return nil;
charchar *bytes = malloc((([string length] + ) / ) * );
if (bytes == NULL)
return nil;
NSUInteger length = ; NSUInteger i = ;
while (YES)
{
char buffer[];
short bufferLength;
for (bufferLength = ; bufferLength < ; i++)
{
if (characters[i] == '\0')
break;
if (isspace(characters[i]) || characters[i] == '=')
continue;
buffer[bufferLength] = decodingTable[(short)characters[i]];
if (buffer[bufferLength++] == CHAR_MAX) // Illegal character!
{
free(bytes);
return nil;
}
} if (bufferLength == )
break;
if (bufferLength == ) // At least two characters are needed to produce one byte!
{
free(bytes);
return nil;
} // Decode the characters in the buffer to bytes.
bytes[length++] = (buffer[] << ) | (buffer[] >> );
if (bufferLength > )
bytes[length++] = (buffer[] << ) | (buffer[] >> );
if (bufferLength > )
bytes[length++] = (buffer[] << ) | buffer[];
} bytes = realloc(bytes, length);
return [NSData dataWithBytesNoCopy:bytes length:length];
} + (NSString *)base64EncodedStringFrom:(NSData *)data
{
if ([data length] == )
return @""; charchar *characters = malloc((([data length] + ) / ) * );
if (characters == NULL)
return nil;
NSUInteger length = ; NSUInteger i = ;
while (i < [data length])
{
char buffer[] = {,,};
short bufferLength = ;
while (bufferLength < && i < [data length])
buffer[bufferLength++] = ((charchar *)[data bytes])[i++]; // Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
characters[length++] = encodingTable[(buffer[] & 0xFC) >> ];
characters[length++] = encodingTable[((buffer[] & 0x03) << ) | ((buffer[] & 0xF0) >> )];
if (bufferLength > )
characters[length++] = encodingTable[((buffer[] & 0x0F) << ) | ((buffer[] & 0xC0) >> )];
else characters[length++] = '=';
if (bufferLength > )
characters[length++] = encodingTable[buffer[] & 0x3F];
else characters[length++] = '=';
} return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
} @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. Hadoop HDFS HA启动出现两个StandBy NameNode

    可能是zkfc服务没有启动,正确的流程如下: 1.在nn001上格式化zkfc sudo -u hdfs hdfs zkfc -formatZK 2.在三个(或以上)节点上启动journalnode ...

  2. ashx、aspx、ASP.NET MVC

    ashx:ProcessRequest(IHandler的方法)aspx:Page_Load(Page继承IHttpHandler)(RouteHandler)(HttpHandler)(MvcHan ...

  3. api接口响应类型定义

    public class Response<T> { public ResponseStatus Status { get; set; } public string Message { ...

  4. js日期转换工具

    var dq = new Date();//定义当前时间var sDueDate = formatDate(dq);/调用日期转换方法 传入当前时间 //进行日期转换 function formatD ...

  5. WebService-php- 2(17)

    wsdl实例 <?xml version ='1.0' encoding ='UTF-8' ?> <definitions targetNamespace='http://local ...

  6. 六、linux目录结构知识

    1.显示行号: cat -n 2.set    nu 3.tail -f  a.txt  查看文件的尾部变化 4.w  当前的登陆用户 5.yum包管理工具底层调用的还是  rpm  -ivh  包名 ...

  7. 第八届蓝桥杯JavaB---承压计算

    标题:承压计算 X星球的高科技实验室中整齐地堆放着某批珍贵金属原料. 每块金属原料的外形.尺寸完全一致,但重量不同. 金属材料被严格地堆放成金字塔形. 7 5 8 7 8 8 9 2 7 2 8 1 ...

  8. 记一次MBR锁机病毒分析

    有一天,在机缘巧合之下我获得了一个锁机软件(是多巧合阿喂!),然后兴高采烈的把它拖入了虚拟机里蹂躏(>_<!). 很巧,软件有虚拟机检测... Emmmm好吧,随便过一下... 我用的虚拟 ...

  9. SpringMvc @RequestMapping原理

    讲这个之前,我们得先知道在SpringMvc启动时,会加载所有的Bean类,就是加了@Controller,@Component等组件标识的类,然后会把@RequestMapping的方法也加入到一个 ...

  10. idea部署tomcat:tomee required to support ear/ejb de。。

    要确定artifact 的type是使用的web application :exploded类型,使用javaee application :exploded就会报这个错误.