Support DES encryption for IOS and Java

Source: Internet
Author: User

Reprint please specify the blog address: http://blog.csdn.net/mengxiangyue/article/details/40015727

Recently in the consideration of data encryption requirements, so the data encryption is simple to look at, of course, not the principle of looking, just to see how to achieve. Now we need to implement the mobile and background (Java) Data encryption and decryption of the match, at the outset to consider the use of RSA, because RSA is asymmetric encryption, more secure point, but RSA encryption process, the iOS public key encryption data, background Java is able to decrypt the success, But the background Java private key encryption things, the front-end iOS, there is no decryption success, the experiment a lot of methods, and ultimately did not succeed, so gave up, turned to security nearly the DES encryption.

For DES, RSA Introduction, their own Baidu go, because I also say do not understand. (I did not mention Android, because Android uses Java, so should be consistent with the background)

The following nonsense is not much to say, directly affixed to the code:

IOS, need to introduce GTMBase64.h, GTMBASE64.M, GTMDefines.h, this github above me, I search it, and <CommonCrypto/CommonCryptor.h>.

#import "ViewController.h" #import <CommonCrypto/CommonCryptor.h> #import "GTMBase64.h" @interface        Viewcontroller () @end @implementation viewcontroller-(void) viewdidload {[Super viewdidload];    NSString *key = @ "This is a key";    NSString *encrypteddata = [Self encryptusedes:@ "The is a text" key:key];    NSLog (@ "Encrypted data is:%@", EncryptedData); NSLog (@ "decrypted data is:%@", [self decryptusedes:encrypteddata Key:key]);}    -(void) didreceivememorywarning {[Super didreceivememorywarning]; Dispose of any resources the can be recreated.} /* String Encryption * parameter *plaintext: Encrypted plaintext *key: Key 64 bit */-(NSString *) Encryptusedes: (NSString *) plaintext key: (NSString *) ke    y{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, Dataleng Th, buffer, 1024x768, &numbytesencrypted    );                 if (Cryptstatus = = kccsuccess) {NSData *data = [NSData datawithbytes:buffer length: (Nsuinteger) numbytesencrypted];    ciphertext = [[NSString alloc] initwithdata:[gtmbase64 encodedata:data] encoding:nsutf8stringencoding]; } return ciphertext;} Decryption-(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 code: You need to introduce yourself 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 is encrypted based on key value * @param data * @param key Encryption key byte array * @return * @throws Except Ion */public static string encrypt (string data, String key) throws Exception {byte[] bt = Encrypt (data.get        Bytes (), key.getbytes ());        String STRs = new Base64encoder (). Encode (BT); return STRs;    }/** * Description decryption based on key value * @param data * @param key Encryption key byte array * @return * @throws IOEXCEP            tion * @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 is encrypted based on key value * @param data * @param key Encryption key byte array * @return * @throws Exception */private static byte[] Encrypt (byte[] data, byte[] key) throws Exception {//Generate a trustworthy random number source Secureran         Dom sr = new SecureRandom ();         Create a Deskeyspec object from the original key data deskeyspec DKs = new Deskeyspec (key);        Create a key factory and use it to convert Deskeyspec to Secretkey object secretkeyfactory keyfactory = Secretkeyfactory.getinstance (DES); Secretkey SecureKey = keyfactory. Generatesecret (DKS);         The Cipher object actually completes the cryptographic operation Cipher Cipher = cipher.getinstance (DES);         Initialize the Cipher object with a key Cipher.init (Cipher.encrypt_mode, SecureKey, SR);    return cipher.dofinal (data); }/** * Description decryption based on key value * @param data * @param key Encryption key byte array * @return * @throws Ex        Ception */private static byte[] Decrypt (byte[] data, byte[] key) throws Exception {//Generate a trustworthy random number source         securerandom sr = new SecureRandom ();         Create a Deskeyspec object from the original key data deskeyspec DKs = new Deskeyspec (key);        Create a key factory and use it to convert Deskeyspec to Secretkey object secretkeyfactory keyfactory = Secretkeyfactory.getinstance (DES);         Secretkey SecureKey = Keyfactory.generatesecret (DKS);         The Cipher object actually completes the decryption operation Cipher Cipher = cipher.getinstance (DES);         Initialize the Cipher object with a key Cipher.init (Cipher.decrypt_mode, SecureKey, SR);    return cipher.dofinal (data); }}

Code: http://download.csdn.net/detail/mengxiangyue/8028311


Support DES encryption for IOS and Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.