Android, iOS 및 Java에 공통되는 AES128 암호화 및 복호화 샘플 코드
머리말
모바일 단말기는 점점 더 대중화되고 있습니다. 개발 과정에서 우리는 안드로이드, iOS 등 모바일 단말기를 다루어야 하는 시나리오를 항상 접하게 됩니다. 데이터 상호작용을 더욱 안전하게 하려면 전송용 데이터를 암호화해야 합니다.
이 글에서는 Android 및 iOS용 일반적인 AES 암호화 알고리즘인 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; }
요약
위 내용은 이 글의 전체 내용입니다. 궁금한 점이 있는 경우 이 글의 내용이 도움이 되기를 바랍니다. 의사소통을 위해 메시지를 남길 수 있습니다.
Android, iOS, Java에 공통적으로 적용되는 AES128 암호화 및 복호화 샘플 코드와 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.
