DES加密 解密 java和iOS 保持一致

1.java/android DES加密解密 base64编码用的jdk1.8

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

/**
 * 解密请求参数
 * Created by prettyRain on 2019/5/21.
 */
public class DesUtil {

    /**
     * 加密解密方式
     */
    private final static String DES = "DES";
    /**
     * 秘钥
     */
    private final static String DEFAULTKEY = "mOAmKLeRIFz15XOTE1PWjg==";
    /**
     * 字符编码
     */
    private final static String ENCODE = "UTF-8";
    /**
     * 解码
     */
    private final static Base64.Decoder DECODER = Base64.getDecoder();
    /**
     * 编码
     */
    private final static Base64.Encoder ENCODER = Base64.getEncoder();


    /**
     * 加密 并用base64编码
     * @param data
     * @return
     * @throws Exception
     */
    public static String encrypt(String data) throws Exception {
        byte[] bt = encrypt(data.getBytes(ENCODE), DEFAULTKEY.getBytes(ENCODE));
        String strs = ENCODER.encodeToString(bt);
        return strs;
    }

    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);
    }

    /**
     * 解密 后并用base64解码
     * @param data
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data) throws IOException, Exception {
        if (data == null)
            return null;

        byte[] buf = DECODER.decode(data);
        byte[] bt = decrypt(buf, DEFAULTKEY.getBytes(ENCODE));
        return new String(bt, ENCODE);
    }

    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);
    }

//测试 加密解密
 public static void main(String[] args) throws Exception {
        String data = "测试加密解密";
        // System.err.println(encrypt(data, key));
        // System.err.println(decrypt(encrypt(data, key), key));
        System.out.println(encrypt(data));
        System.out.println(decrypt(encrypt(data)));
    }

2.iOS DES加密解密

//DES加密
- (NSString *)DESString {
  NSString *ciphertext = nil;
  //const char *textBytes = [plainText UTF8String];字符串直接转字节数组就会和java加密结果不一样, 用NSString 转 NSData 取字节流 和java加密结果一致
  NSData *textData = [self dataUsingEncoding:NSUTF8StringEncoding];
  NSUInteger dataLength = [textData 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|kCCOptionECBMode,[DES__KEY UTF8String], kCCKeySizeDES,iv,[textData bytes], dataLength,buffer, 1024,&numBytesEncrypted);
  if (cryptStatus == kCCSuccess) {
    NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
    ciphertext = [data base64EncodedStringWithOptions:0];
  }
  return ciphertext;
     
}

//DES解密
+(NSString *)decryptUseDES:(NSString *)cipherText key:(NSString *)key
 {
     NSString *plaintext = nil;
     NSData *cipherdata = [GTMBase64 decodeString:cipherText];
     unsigned char buffer[1024];
     memset(buffer, 0, sizeof(char));
     size_t numBytesDecrypted = 0;
     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
                              kCCOptionPKCS7Padding,
                              [key UTF8String], kCCKeySizeDES,
                              iv,
                              [cipherdata bytes], [cipherdata length],
                              buffer, 1024,
                              &numBytesDecrypted);
     if(cryptStatus == kCCSuccess)
     {
        NSData *plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
         plaintext = [[NSString alloc]initWithData:plaindata encoding:NSUTF8StringEncoding];
     }
   return plaintext;
   }

你可能感兴趣的:(DES加密 解密 java和iOS 保持一致)