Supported DES encryption and iosjavades encryption for IOS and java
Reprinted please indicate blog address: http://blog.csdn.net/mengxiangyue/article/details/40015727
Recently, we are considering data encryption requirements. So I simply read about Data Encryption. Of course, it is not about the principle, but about how to implement it. Now we need to implement the cooperation between the mobile terminal and the backend (java) data encryption and decryption. At the beginning, we should consider using RSA because RSA is non-symmetric encryption, which is more secure, however, during the RSA encryption process, the data encrypted by the ios public key can be decrypted successfully in the background java. However, the data encrypted by the background java private key won't be decrypted successfully in the front-end ios, I tried a lot of methods and finally failed, so I gave up and switched to DES encryption with poor security.
For the introduction of DES and RSA, go to Baidu, because I also do not understand. (Android is not mentioned above, because Android uses java, so it should be consistent with the background)
Paste the Code directly:
For IOS, You need to introduce GTMBase64.h, GTMBase64.m, and GTMDefines. h. I found this on github and I will search for it myself, as well as <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: @ "this is a text" key: key]; NSLog (@ "encrypted data: % @", encryptedData ); NSLog (@ "the decrypted data is: % @", [self decryptUseDES: encryptedData key: key]);}-(void) didReceiveMemoryWarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} /* string encryption * parameter * plainText: Encrypted plainText * key: key 64-bit */-(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 [] = {,}; size_t numBytesEncrypted = 0; CCCryptorStatus cryptStatus = CCCrypt (kCCEncrypt, kCCAlgorithmDES, region, region, [key UTF8String], kmeaneysizedes, 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 ;} // 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, 4, 5, 6, 7}; CCCryptorStatus cryptStatus = CCCrypt (kCCDecrypt, kCCAlgorithmDES, primary, [key UTF8String], kCCKeySizeDES, iv, [cipherData bytes], [cipherData length], buffer, 1024, & numBytesDecrypted); NSString * plainText = nil; if (cryptStatus = kCCSuccess) {NSData * data = [NSData dataWithBytes: buffer length :( NSUInteger) encoding]; plainText = [[NSString alloc] initWithData: data encoding: encoding];} return plainText;} @ end
Java code: Introduce sun. misc. BASE64Decoder. jar by yourself.
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: encrypt data by key value * @ param data * @ param key: byte array * @ 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 decryption based on the key value * @ param data * @ param key the encryption key byte array * @ 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: encrypt data by key value * @ param data * @ param key: byte array * @ return * @ throws Exception */private static byte [] encrypt (byte [] data, byte [] key) throws Exception {// generate a trusted random number source SecureRandom sr = new SecureRandom (); // create the export eyspec object named Export eyspec dks = new export eyspec (key) from the original key data; // create a key factory and use it to convert the export eyspec to the SecretKey object SecretKeyFactory keyFactory = SecretKeyFactory. getInstance (DES); SecretKey securekey = keyFactory. generateSecret (dks); // The Cipher object actually completes the encryption operation Cipher cipher = Cipher. getInstance (DES); // use the key to initialize the Cipher object cipher. init (Cipher. ENCRYPT_MODE, securekey, sr); return cipher. doFinal (data );} /*** Description decrypts data based on the key value * @ param data * @ param key: the byte array * @ return * @ throws Exception */private static byte [] decrypt (byte [] data, byte [] key) throws Exception {// generate a trusted random number source SecureRandom sr = new SecureRandom (); // create the export eyspec object named Export eyspec dks = new export eyspec (key) from the original key data; // create a key factory and use it to convert the export eyspec to the 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); // use the key to initialize the Cipher object cipher. init (Cipher. DECRYPT_MODE, securekey, sr); return cipher. doFinal (data );}}
Code: http://download.csdn.net/detail/mengxiangyue/8028311
The DES encryption algorithm is implemented in java. It must be pasted directly into the platform for running.
/* Des Key Generation Code */
Import java. io. File;
Import java. io. FileNotFoundException;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. ObjectOutputStream;
Import java. security. InvalidKeyException;
Import java. security. NoSuchAlgorithmException;
Import java. security. SecureRandom;
Import java. security. spec. InvalidKeySpecException;
Import javax. crypto. KeyGenerator;
Import javax. crypto. SecretKey;
Import javax. crypto. SecretKeyFactory;
Import javax. crypto. spec. DESKeySpec;
Import com. huateng. util. common. Log;
Public class GenKey {
Private static final String DES = "DES ";
Public static final String SKEY_NAME = "key. des ";
Public static void genKey1 (String path ){
// Key
SecretKey skey = null;
// Random key generation
SecureRandom sr = new SecureRandom ();
// Generate the key file
File file = genFile (path );
Try {
// Obtain the key generation instance
KeyGenerator gen = KeyGenerator. getInstance (DES );
// Initialize the key generator
Gen. init (sr );
// Generate the key
Skey = gen. generateKey ();
// System. out. println (skey );
ObjectOutputStream oos = new ObjectOutputStream (
New FileOutputStream (file ));
Oos. writeObject (skey );
Oos. close ();
Log. sKeyPath (path );
} Catch (NoSuchAlgorithmException e ){
E. printStackTrace ();
} Catch (FileNotFoundException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
/**
* @ Param file: Path of the generated key
* SecretKeyFactory generates des keys
... The remaining full text>
How to use JAVA to encrypt and decrypt the DES of strings
Please refer to the article:
Blog.csdn.net/..365355