(IOS) Base64 encryption and DES encryption, and DES encryption unity issues in Java and IOS

Source: Internet
Author: User
Tags base64 encode



For security reasons, we typically choose an encryption method to encrypt text that requires security, while BASE64 encryption and DES64 encryption are common cryptographic algorithms. I remember what I used in the previous project was the combination of these two cryptographic algorithms: Base64 + des encryption. Of course, this requires mobile and background server to do a unified.


1, Base64 plus decryption


It is worth mentioning that: Apple provides the basic BASE64 encryption and decryption algorithm. This allows us to use the method directly to implement BASE64 and decryption. Let's take a look at what Apple has to offer:


 
 
@interface NSData (NSDataBase64Encoding)

/* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64.
*/
- (nullable instancetype)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create a Base-64 encoded NSString from the receiver‘s contents using the given options.
*/
- (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64.
*/
- (nullable instancetype)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create a Base-64, UTF-8 encoded NSData from the receiver‘s contents using the given options.
*/
- (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

@end







 
@interface NSData (NSDataBase64Encoding)

/* Create an NSData from a Base-64 encoded NSString using the given options. By default, returns nil when the input is not recognized as valid Base-64.
*/
- (nullable instancetype)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create a Base-64 encoded NSString from the receiver‘s contents using the given options.
*/
- (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create an NSData from a Base-64, UTF-8 encoded NSData. By default, returns nil when the input is not recognized as valid Base-64.
*/
- (nullable instancetype)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options NS_AVAILABLE(10_9, 7_0);

/* Create a Base-64, UTF-8 encoded NSData from the receiver‘s contents using the given options.
*/
- (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options NS_AVAILABLE(10_9, 7_0);

@end








Let's start by creating a nsdata, and then one more analysis of the above methods


NSData *data = [@ "Base64 encoding string" datausingencoding:nsutf8stringencoding];





(1) Create a data (create a data from a BASE64 encoded string using the given settings)


NSData *datafrombase64string = [[NSData alloc]initwithbase64encodedstring:base64string options:0];





(2) Create a BASE64 encoded string (created from the recipient's content)


NSString *base64string = [data base64encodedstringwithoptions:0];





(3) Create a data (created from a Base64, UTF-8 encoded data)


NSData *base64andutfdata = [base64data initwithbase64encodeddata:base64data options:0];





(4) Create a Base64, UTF-8 encoded data (created from the recipient content)


NSData *base64data = [data base64encodeddatawithoptions:0];





Of course, we can finally turn data into a string type.


NSString *base64decoded = [[NSString alloc]initwithdata:datafrombase64string encoding:nsutf8stringencoding];








The above is the Base64 and decryption method. Let's look at the addition and decryption of DES.











2, des plus decryption


We all know that Android and the backend can use unified code to solve this problem, which is one of the advantages of Java. Here I will attach a Java code. This is mainly for the following description of the Java and iOS implementation of the need to pay attention to the place (also different points).



To make the instructions easier, let's take a look at the Java des encryption method:


 
/**
     * EDS encryption
     * @param originalStr
     * @return
     */
    public static String Encrypt (String originalStr) {
        String result = null;
        byte [] tmpOriginalStr = null;
        Try {
            if (! Tools.isEmpty (originalStr)) {
                tmpOriginalStr = originalStr.getBytes ("utf-8");
                SecretKeyFactory keyFactory = SecretKeyFactory.getInstance ("DES");
                DESKeySpec dks = new DESKeySpec (KEY);
                SecretKey secretKey = keyFactory.generateSecret (dks);
                IvParameterSpec param = new IvParameterSpec (IV);
                Cipher cipher = Cipher.getInstance ("DES / CBC / PKCS5Padding");
                cipher.init (Cipher.ENCRYPT_MODE, secretKey, param);
                byte [] tmpEncypt = cipher.doFinal (tmpOriginalStr);
                if (tmpEncypt! = null) {
                    result = Base64.encodeToString (tmpEncypt, Base64.NO_WRAP);
                }
            }
        } catch (Exception e) {
            Log.e ("Erro", e.getMessage ());
        }
        return result;
    }


We can see that Java is using the CBC mode by default for DES encryption algorithms, and the alignment is using pkcs5padding.






While the encryption in OC is not encrypted in Java form, next we look at the code that implements DES Encryption in OC:


 
#pragma mark- Encryption Algorithm
+ (NSString *) encryptUseDES: (NSString *) plainText // key: (NSString *) key
{
    NSString * ciphertext = nil;
    NSData * textData = [plainText dataUsingEncoding: NSUTF8StringEncoding];
    NSUInteger dataLength = [textData length];
    unsigned char buffer [1024 * 5];
    memset (buffer, 0, sizeof (char));
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt (kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [key UTF8String], kCCKeySizeDES,
                                          [iv UTF8String],
                                          [textData bytes], dataLength,
                                          buffer, 1024,
                                          & numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        NSData * data = [NSData dataWithBytes: buffer length: (NSUInteger) numBytesEncrypted];
        ciphertext = [data base64EncodedStringWithOptions: 0];
    }
    return ciphertext;
}


Let's talk about the green part of red in the code: key and Iv. Key: Is the public key of DES encryption. and IV: is the initialized vector. Both are key parameters of DES encryption. This is a must and Android, backstage have a unified.



We can see that OC is using the Kccoptionpkcs7padding alignment method. In Java, it is clear that pkcs5padding is used. Let's take a look at the alignment choices given in OC, which I'll show directly in the form of code:


enum { /**/ kccoptionpkcs7padding 0x0001,    Kccoptionecbmode  0x0002 /* */}; 


The two options given in OC are Kccoptionecbmode and kccoptionpkcs7padding. Well, the problem now arises. There are many kinds of DES encryption algorithms in Java, for example: ECB,CBC,OFB,CFB, etc.



How does des encryption in Java and OC achieve consistency? (This is also the problem I encountered in the project).






Looking at a lot of information, coupled with many of their own tests, the results are as follows:



Encrypted in Java using this method:"des/cbc/pkcs5padding" corresponds to the object-c of the kccoptionpkcs7padding



and using "des/ecb/pkcs5padding" corresponds to the object-c is kccoptionpkcs7padding | Kccoptionecbmod



It seems that OC currently only supports encryption in both of these ways. Of course the results have been verified.



Other Links:



Des plus decryption implementation between Objective C and Java



IOS 7:base64 Encode and Decode NSData and NSString Objects






Attached here Demo:https://github.com/wheat-qin/base64-des






(IOS) Base64 encryption and DES encryption, and DES encryption unity issues in Java and IOS


Related Article

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.