Android、iOS和Java通用的AES128加密解密示例代码

 更新时间:2016年11月04日 10:05:28   投稿:daisy  
现在很多App在与服务器接口的请求和响应过程中,为了安全都会涉及到加密和解密的问题,如果不加的话就会是明文的,即使加了GZIP也可以被直接解压成明文。如果同时有Android和IOS的App的话、必须要保证加密和解密的算法一致、不然后台没法处理,下面通过这篇文章学习下。

前言

移动端越来越火了,我们在开发过程中,总会碰到要和移动端打交道的场景,比如android和iOS的打交道。为了让数据交互更安全,我们需要对数据进行加密传输。

这篇文章给大家分享AES的加密和解密、Android和ios通用的AES加密算法、大家可以直接集成到自己的项目、服务器接口如果是用Java写的话、整个框架都完美了、如果是.NET编写的后台接口的话、得改造一下哦

IOS加密

/*加密方法*/
 (NSString *)AES256EncryptWithPlainText:(NSString *)plain {
 NSData *plainText = [plain dataUsingEncoding:NSUTF8StringEncoding];
 // ´key´ should be 32 bytes for AES256, will be null-padded otherwise
 char keyPtr[kCCKeySizeAES256 1]; // room for terminator (unused)
 bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
  
 NSUInteger dataLength = [plainText length];

 size_t bufferSize = dataLength kCCBlockSizeAES128;
 void *buffer = malloc(bufferSize);
 bzero(buffer, sizeof(buffer));
 
 size_t numBytesEncrypted = 0;
 
 CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,kCCOptionPKCS7Padding,
           [[NSData AESKeyForPassword:PASSWORD] bytes], kCCKeySizeAES256,
           ivBuff /* initialization vector (optional) */,
           [plainText bytes], dataLength, /* input */
           buffer, bufferSize, /* output */
           &numBytesEncrypted);
 if (cryptStatus == kCCSuccess) {
  NSData *encryptData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
  return [encryptData base64Encoding];
 }
 
 free(buffer); //free the buffer;
 return nil;
}

IOS解密

/*解密方法*/
 (NSString *)AES256DecryptWithCiphertext:(NSString *)ciphertexts{
 
 NSData *cipherData = [NSData dataWithBase64EncodedString:ciphertexts];
 // ´key´ should be 32 bytes for AES256, will be null-padded otherwise
 char keyPtr[kCCKeySizeAES256 1]; // room for terminator (unused)
 bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
  
 NSUInteger dataLength = [cipherData length];
 
 size_t bufferSize = dataLength kCCBlockSizeAES128;
 void *buffer = malloc(bufferSize);
  
 size_t numBytesDecrypted = 0;
 CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
           [[NSData AESKeyForPassword:PASSWORD] bytes], kCCKeySizeAES256, 
           ivBuff ,/* initialization vector (optional) */
           [cipherData bytes], dataLength, /* input */
           buffer, bufferSize, /* output */
           &numBytesDecrypted);
 
 if (cryptStatus == kCCSuccess) {
  NSData *encryptData = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
  return [[[NSString alloc] initWithData:encryptData encoding:NSUTF8StringEncoding] init];
 }
 
 free(buffer); //free the buffer;
 return nil;
}

Android加密

private byte[] encrypt(String cmp, SecretKey sk, IvParameterSpec IV,
  byte[] msg) {
 try {
  Cipher c = Cipher.getInstance(cmp);
  c.init(Cipher.ENCRYPT_MODE, sk, IV);
  return c.doFinal(msg);
 } catch (NoSuchAlgorithmException nsae) {
  Log.e("AESdemo", "no cipher getinstance support for " cmp);
 } catch (NoSuchPaddingException nspe) {
  Log.e("AESdemo", "no cipher getinstance support for padding " cmp);
 } catch (InvalidKeyException e) {
  Log.e("AESdemo", "invalid key exception");
 } catch (InvalidAlgorithmParameterException e) {
  Log.e("AESdemo", "invalid algorithm parameter exception");
 } catch (IllegalBlockSizeException e) {
  Log.e("AESdemo", "illegal block size exception");
 } catch (BadPaddingException e) {
  Log.e("AESdemo", "bad padding exception");
 }
 return null;
}

Android解密

private byte[] decrypt(String cmp, SecretKey sk, IvParameterSpec IV,
   byte[] ciphertext) {
 try {
  Cipher c = Cipher.getInstance(cmp);
  c.init(Cipher.DECRYPT_MODE, sk, IV);
  return c.doFinal(ciphertext);
 } catch (NoSuchAlgorithmException nsae) {
  Log.e("AESdemo", "no cipher getinstance support for " cmp);
 } catch (NoSuchPaddingException nspe) {
  Log.e("AESdemo", "no cipher getinstance support for padding " cmp);
 } catch (InvalidKeyException e) {
  Log.e("AESdemo", "invalid key exception");
 } catch (InvalidAlgorithmParameterException e) {
  Log.e("AESdemo", "invalid algorithm parameter exception");
 } catch (IllegalBlockSizeException e) {
  Log.e("AESdemo", "illegal block size exception");
 } catch (BadPaddingException e) {
  Log.e("AESdemo", "bad padding exception");
  e.printStackTrace();
 }
 return null;
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对各位开发者们能有所帮助,如果有疑问大家可以留言交流。

相关文章

  • 常用Java排序算法详解

    常用Java排序算法详解

    本文主要介绍了java的七种常见排序算法的实现,对选择排序、插入排序、冒泡排序、归并排序、快速排序、希尔排序、最小堆排序进行原理分析与实例介绍,具有很好的参考价值。下面就跟着小编一起来看下吧
    2016-12-12
  • 解析ConcurrentHashMap:成员属性、内部类、构造方法

    解析ConcurrentHashMap:成员属性、内部类、构造方法

    ConcurrentHashMap是由Segment数组结构和HashEntry数组结构组成。Segment的结构和HashMap类似,是一种数组和链表结构,今天给大家普及java面试常见问题---ConcurrentHashMap知识,一起看看吧
    2021-06-06
  • springboot中引入日志文件生成的配置详解

    springboot中引入日志文件生成的配置详解

    本文主要介绍了springboot中引入日志文件生成的配置详解,包括日志级别的设置、日志格式的配置以及日志输出的位置等,从而帮助开发者更好地进行开发与调试
    2023-10-10
  • 解读Eureka的TimedSupervisorTask类(自动调节间隔的周期性任务)

    解读Eureka的TimedSupervisorTask类(自动调节间隔的周期性任务)

    在Eureka客户端中,尽管ScheduledExecutorService的schedule方法创建的是一次性任务,但通过在任务执行完毕后再次调用schedule方法实现了周期性执行,这种设计既考虑到了任务超时导致的间隔时间调整,又通过CAS实现了多线程同步,展现了简洁而巧妙的设计思想
    2024-11-11
  • Spring-Task定时任务的使用介绍

    Spring-Task定时任务的使用介绍

    目前springboot应用广泛,因此对于spring-task直接基于springboot框架介绍,不涉及xml配置。本文直接介绍spring-task的使用方法,需要的可以参考一下
    2022-11-11
  • Struts2截取字符串代码介绍

    Struts2截取字符串代码介绍

    这篇文章主要介绍了Struts2截取字符串代码介绍,介绍了基本的截取方法,以及截取带html标签字符串的方法,需要的朋友可以了解下。
    2017-09-09
  • JavaEE Cookie的基本使用细节

    JavaEE Cookie的基本使用细节

    本章我们将学习会话跟踪技术中的Cookie与Session,它在我们整个JavaEE的知识体系中是非常重要的,本节我们先介绍Cookie,废话不多说,直接上正文
    2022-12-12
  • Java中为什么要实现Serializable序列化

    Java中为什么要实现Serializable序列化

    在Java编程中,Serializable序列化是一个常见的概念,它允许对象在网络上传输或持久化到磁盘上,本文将深入探讨为什么在Java中要实现Serializable序列化,并通过示例代码来解释其重要性
    2023-10-10
  • Spring中的@EnableWebSecurity注解详解

    Spring中的@EnableWebSecurity注解详解

    这篇文章主要介绍了Spring中的@EnableWebSecurity注解详解,EnableWebSecurity注解是个组合注解,它的注解中,又使用了@EnableGlobalAuthentication注解,需要的朋友可以参考下
    2023-12-12
  • java JSON解析库Alibaba Fastjson用法详解

    java JSON解析库Alibaba Fastjson用法详解

    这篇文章主要介绍了java JSON解析库Alibaba Fastjson用法,结合实例形式详细分析了java JSON解析库Alibaba Fastjson的基本功能、原理、用法及操作注意事项,需要的朋友可以参考下
    2020-04-04

最新评论