IOS、java支援DES加密

來源:互聯網
上載者:User

標籤:des   android   blog   http   io   os   使用   ar   java   

轉載請註明部落格地址:http://blog.csdn.net/mengxiangyue/article/details/40015727

最近在考慮資料加密方面的需求,所以對資料加密簡單的看了一下,當然不是看的原理,只是看看怎麼能夠實現。現在我們需要實現的是移動端和後台(java)資料加解密的配合,開始的時候考慮的使用RSA,因為RSA是非對稱式加密,更加安全點,但是RSA加密的過程中,ios公開金鑰加密的資料,後台java是能夠解密成功,但是後台java私密金鑰加密的東西,前端ios,就沒有解密成功,實驗了很多方法,最終也沒有成功,所以就放棄了,轉向了安全性差一點的DES加密。

對於DES、RSA的介紹,自己百度去吧,因為我也說不明白。(上面我沒有提Android,因為Android使用的是java,所以應該跟後台一致)

下面廢話不多說,直接貼上代碼:

IOS,需要引入GTMBase64.h、GTMBase64.m、GTMDefines.h,這個github上面有我,自己搜搜吧,還有<CommonCrypto/CommonCryptor.h>。

#import "ViewController.h"#import <CommonCrypto/CommonCryptor.h>#import "GTMBase64.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        NSString *key = @"這是個key";    NSString *encryptedData = [self encryptUseDES:@"this is a text" key:key];    NSLog(@"加密後的資料是:%@", encryptedData);    NSLog(@"解密後的資料是:%@", [self decryptUseDES:encryptedData key:key]);}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}/*字串加密 *參數 *plainText : 加密明文 *key        : 密鑰 64位 */- (NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key{    NSString *ciphertext = nil;    const char *textBytes = [plainText UTF8String];    NSUInteger dataLength = [plainText length];    unsigned char buffer[1024];    memset(buffer, 0, sizeof(char));    Byte iv[] = {1,2,3,4,5,6,7,8};    size_t numBytesEncrypted = 0;    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,                                          kCCOptionPKCS7Padding,                                          [key UTF8String], kCCKeySizeDES,                                          iv,                                          textBytes, dataLength,                                          buffer, 1024,                                          &numBytesEncrypted);    if (cryptStatus == kCCSuccess) {        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];                ciphertext = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];    }    return ciphertext;}//解密- (NSString *) decryptUseDES:(NSString*)cipherText key:(NSString*)key{    NSData* cipherData = [GTMBase64 decodeString:cipherText];    unsigned char buffer[1024];    memset(buffer, 0, sizeof(char));    size_t numBytesDecrypted = 0;    Byte iv[] = {1,2,3,4,5,6,7,8};    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,                                          kCCAlgorithmDES,                                          kCCOptionPKCS7Padding,                                          [key UTF8String],                                          kCCKeySizeDES,                                          iv,                                          [cipherData bytes],                                          [cipherData length],                                          buffer,                                          1024,                                          &numBytesDecrypted);    NSString* plainText = nil;    if (cryptStatus == kCCSuccess) {        NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];        plainText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];    }    return plainText;}@end
java 代碼:需要自己引入sun.misc.BASE64Decoder.jar

package com.yue;import java.io.IOException;import java.security.SecureRandom;import javax.crypto.Cipher;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;import Decoder.BASE64Decoder;import Decoder.BASE64Encoder;  public class DesUtil {     private final static String DES = "DES";     public static void main(String[] args) throws Exception {        String data = "123 456";        String key = "abcdefgh";        System.err.println(encrypt(data, key));        System.err.println(decrypt(encrypt(data, key), key));                System.out.println(decrypt("JF5dX/TlOg529KAhh+vywjzIp5Msktmf", key));     }         /**     * Description 根據索引值進行加密     * @param data      * @param key  加密鍵byte數組     * @return     * @throws Exception     */    public static String encrypt(String data, String key) throws Exception {        byte[] bt = encrypt(data.getBytes(), key.getBytes());        String strs = new BASE64Encoder().encode(bt);        return strs;    }     /**     * Description 根據索引值進行解密     * @param data     * @param key  加密鍵byte數組     * @return     * @throws IOException     * @throws Exception     */    public static String decrypt(String data, String key) throws IOException,            Exception {        if (data == null)            return null;        BASE64Decoder decoder = new BASE64Decoder();        byte[] buf = decoder.decodeBuffer(data);        byte[] bt = decrypt(buf,key.getBytes());        return new String(bt);    }     /**     * Description 根據索引值進行加密     * @param data     * @param key  加密鍵byte數組     * @return     * @throws Exception     */    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {        // 產生一個可信任的隨機數源        SecureRandom sr = new SecureRandom();         // 從原始密鑰資料建立DESKeySpec對象        DESKeySpec dks = new DESKeySpec(key);         // 建立一個密鑰工廠,然後用它把DESKeySpec轉換成SecretKey對象        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);        SecretKey securekey = keyFactory.generateSecret(dks);         // Cipher對象實際完成加密操作        Cipher cipher = Cipher.getInstance(DES);         // 用密鑰初始化Cipher對象        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);         return cipher.doFinal(data);    }              /**     * Description 根據索引值進行解密     * @param data     * @param key  加密鍵byte數組     * @return     * @throws Exception     */    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {        // 產生一個可信任的隨機數源        SecureRandom sr = new SecureRandom();         // 從原始密鑰資料建立DESKeySpec對象        DESKeySpec dks = new DESKeySpec(key);         // 建立一個密鑰工廠,然後用它把DESKeySpec轉換成SecretKey對象        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);        SecretKey securekey = keyFactory.generateSecret(dks);         // Cipher對象實際完成解密操作        Cipher cipher = Cipher.getInstance(DES);         // 用密鑰初始化Cipher對象        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);         return cipher.doFinal(data);    }}

代碼:http://download.csdn.net/detail/mengxiangyue/8028311


IOS、java支援DES加密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.