美文网首页iOS功能开发iOS架构
java 使用Cipher默认加密,ios aes AES/EC

java 使用Cipher默认加密,ios aes AES/EC

作者: 姬拉 | 来源:发表于2018-06-25 10:38 被阅读223次

    java加解密(java默认不支持PKCS7Padding):

    public class test {
        // 加密
        public static String Encrypt(String sSrc, String sKey) throws Exception {
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
          //"算法/模式/补码方式"、Cipher cipher = Cipher.getInstance("AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
    
            char[] result= new Base64().encode(encrypted);
            return new String(result);
            
          
        }
    
        // 解密
        public static String Decrypt(String sSrc, String sKey) throws Exception {
            try {
                // 判断Key是否正确
                if (sKey == null) {
                    System.out.print("Key为空null");
                    return null;
                }
                // 判断Key是否为16位
                if (sKey.length() != 16) {
                    System.out.print("Key长度不是16位");
                    return null;
                }
                byte[] raw = sKey.getBytes("utf-8");
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);
                byte[] encrypted1 = new Base64().decode(sSrc.toCharArray());
                try {
                    byte[] original = cipher.doFinal(encrypted1);
                    String originalString = new String(original,"utf-8");
                    return originalString;
                } catch (Exception e) {
                    System.out.println(e.toString());
                    return null;
                }
            } catch (Exception ex) {
                System.out.println(ex.toString());
                return null;
            }
        }
        public static void main(String[] args) throws Exception {
            /*
             * 此处使用AES-128-ECB加密模式,key需要为16位。
             */
            String cKey = "1234567890123456";
            // 需要加密的字串
            String cSrc = "有钱";
            System.out.println(cSrc);
            // 加密
            String enString = Encrypt(cSrc, cKey);
            System.out.println("加密后的字串是:" + enString);
            // 解密
            String DeString = Decrypt("xOgvmYILb7wr6Rov9h0vwOh3jNukN5Gnjcfvx91tm1gRe0KBZEDyzuNH9fX2rduvrSMO0b3Qb9yXyk/iSA5gaOFqSrytIHZqwxCaYinM6FGnOZtwpWqoPGOxGRS8sgwUphok9xALvByiUXel663TS+ogIv7lQrujhGqaGu0S8QeBEpNlxKj3jpjB975J2smp9j+9DUUfisj2tk5tlf63G9QdJphb6r8sJXBkf7kRFjw=", cKey);
            System.out.println("解密后的字串是:" + DeString);
        }
    }
    

    ios AES/ECB/PKCS5Padding 加解密:

    -(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key
    {
        char keyPtr[kCCKeySizeAES128+1];
        memset(keyPtr, 0, sizeof(keyPtr));
        [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
        
        NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
        NSUInteger dataLength = [data length];
        
        size_t bufferSize = dataLength + kCCBlockSizeAES128;
        unsigned char *buffer = malloc(bufferSize);
        size_t numBytesEncrypted = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                              kCCAlgorithmAES128,
                                              kCCOptionPKCS7Padding|kCCOptionECBMode,
                                              keyPtr,
                                              kCCBlockSizeAES128,
                                              NULL,
                                              [data bytes],
                                              dataLength,
                                              buffer,
                                              bufferSize,
                                              &numBytesEncrypted);
        if (cryptStatus == kCCSuccess) {
            NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
            return [NSString base64StringFromData:resultData length:[resultData length]];
            
        }
        free(buffer);
        return @"";
    }
    -(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key
    {
        char keyPtr[kCCKeySizeAES128 + 1];
        memset(keyPtr, 0, sizeof(keyPtr));
        [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
        
        //NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
        
        NSData *data=[NSData base64DataFromString:encryptText];
        
        NSUInteger dataLength = [data length];
        size_t bufferSize = dataLength + kCCBlockSizeAES128;
        unsigned char *buffer = malloc(bufferSize);
        
        size_t numBytesCrypted = 0;
        CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                              kCCAlgorithmAES128,
                                              kCCOptionPKCS7Padding|kCCOptionECBMode,
                                              keyPtr,
                                              kCCBlockSizeAES128,
                                              NULL,
                                              [data bytes],
                                              dataLength,
                                              buffer,
                                              bufferSize,
                                              &numBytesCrypted);
        if (cryptStatus == kCCSuccess) {
            NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
            return [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
        }
        free(buffer);
        return @"";
    }
    

    方法:base64DataFromString

    #import "NSData+Base64.h"
    
    @implementation NSData (Base64Additions)
    
    + (NSData *)base64DataFromString:(NSString *)string {
      unsigned long ixtext, lentext;
      unsigned char ch, inbuf[4], outbuf[3];
      short i, ixinbuf;
      Boolean flignore, flendtext = false;
      const unsigned char *tempcstring;
      NSMutableData *theData;
      
      if (string == nil) {
        return [NSData data];
      }
      
      ixtext = 0;
      
      tempcstring = (const unsigned char *)[string UTF8String];
      
      lentext = [string length];
      
      theData = [NSMutableData dataWithCapacity: lentext];
      
      ixinbuf = 0;
      
      while (true) {
        if (ixtext >= lentext) {
          break;
        }
        
        ch = tempcstring [ixtext++];
        
        flignore = false;
        
        if ((ch >= 'A') && (ch <= 'Z')) {
          ch = ch - 'A';
        }
        else if ((ch >= 'a') && (ch <= 'z')) {
          ch = ch - 'a' + 26;
        }
        else if ((ch >= '0') && (ch <= '9')) {
          ch = ch - '0' + 52;
        }
        else if (ch == '+') {
          ch = 62;
        }
        else if (ch == '=') {
          flendtext = true;
        }
        else if (ch == '/') {
          ch = 63;
        }
        else {
          flignore = true; 
        }
        
        if (!flignore) {
          short ctcharsinbuf = 3;
          Boolean flbreak = false;
          
          if (flendtext) {
            if (ixinbuf == 0) {
              break;
            }
            
            if ((ixinbuf == 1) || (ixinbuf == 2)) {
              ctcharsinbuf = 1;
            }
            else {
              ctcharsinbuf = 2;
            }
            
            ixinbuf = 3;
            
            flbreak = true;
          }
          
          inbuf [ixinbuf++] = ch;
          
          if (ixinbuf == 4) {
            ixinbuf = 0;
            
            outbuf[0] = (inbuf[0] << 2) | ((inbuf[1] & 0x30) >> 4);
            outbuf[1] = ((inbuf[1] & 0x0F) << 4) | ((inbuf[2] & 0x3C) >> 2);
            outbuf[2] = ((inbuf[2] & 0x03) << 6) | (inbuf[3] & 0x3F);
            
            for (i = 0; i < ctcharsinbuf; i++) {
              [theData appendBytes: &outbuf[i] length: 1];
            }
          }
          
          if (flbreak) {
            break;
          }
        }
      }
      
      return theData;
    }
    
    @end
    
    

    方法:base64StringFromData

    #import "NSString+Base64.h"
    #import <UIKit/UIKit.h>
    static char base64EncodingTable[64] = {
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
      'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
      'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
      'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    };
    
    @implementation NSString (Base64Additions)
    
    + (NSString *)base64StringFromData: (NSData *)data length: (NSUInteger)length {
      unsigned long ixtext, lentext;
      long ctremaining;
      unsigned char input[3], output[4];
      short i, charsonline = 0, ctcopy;
      const unsigned char *raw;
      NSMutableString *result;
      
      lentext = [data length]; 
      if (lentext < 1) {
        return @"";
      }
      result = [NSMutableString stringWithCapacity: lentext];
      raw = [data bytes];
      ixtext = 0; 
      
      while (true) {
        ctremaining = lentext - ixtext;
        if (ctremaining <= 0) {
          break;
        }
        for (i = 0; i < 3; i++) { 
          unsigned long ix = ixtext + i;
          if (ix < lentext) {
            input[i] = raw[ix];
          }
          else {
            input[i] = 0;
          }
        }
        output[0] = (input[0] & 0xFC) >> 2;
        output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);
        output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);
        output[3] = input[2] & 0x3F;
        ctcopy = 4;
        switch (ctremaining) {
          case 1: 
            ctcopy = 2; 
            break;
          case 2: 
            ctcopy = 3; 
            break;
        }
        
        for (i = 0; i < ctcopy; i++) {
          [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];
        }
        
        for (i = ctcopy; i < 4; i++) {
          [result appendString: @"="];
        }
        
        ixtext += 3;
        charsonline += 4;
        
        if ((length > 0) && (charsonline >= length)) {
          charsonline = 0;
        }
      }     
      return result;
    }
    
    @end
    

    相关文章

      网友评论

        本文标题:java 使用Cipher默认加密,ios aes AES/EC

        本文链接:https://www.haomeiwen.com/subject/ppieyftx.html