0
回答
IOS跟c#,安卓des加密结果不一致问题
华为云实践训练营,热门技术免费实践!>>>   

先贴出代码一、c#代码

public string EncryptData(string data)
{
    byte[] keyBytes = Convert.FromBase64String(Key1);
    byte[] keyIV = Convert.FromBase64String(Key2);
    byte[] inputByteArray = Encoding.UTF8.GetBytes(data);
    DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
    MemoryStream mStream = new MemoryStream();
    CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
    cStream.Write(inputByteArray, 0, inputByteArray.Length);
    cStream.FlushFinalBlock();
    return Convert.ToBase64String(mStream.ToArray());

}


二、安卓代码

public String EncryptData(String Data) throws Exception {
    byte[] keyBytes = new BASE64Decoder().decodeBuffer(Key1);//ASCIIEncoding.ASCII.GetBytes(key);
    byte[] keyIV = new BASE64Decoder().decodeBuffer(Key2); //将12位密钥转为8位
    IvParameterSpec zeroIv = new IvParameterSpec(keyIV);
    //获得秘钥
    SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
    //实例化加密类Cipher      加密方式/工作模式/填充
    Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
    byte[] encryptedData = cipher.doFinal(Data.getBytes("UTF-8"));
    String encode = new String(Base64.encode(encryptedData, Base64.DEFAULT),"UTF-8");
    return encode;
}


三、ios代码

+ (NSString *) encryptUseDES:(NSString *)plainText key1:(NSString *)key1 key2:(NSString*)key2{
    NSString *ciphertext = nil;
    NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSUInteger dataLength = [textData length];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesEncrypted = 0;
    NSData* key1Data = [key1 dataUsingEncoding:NSUTF8StringEncoding];
    NSData* key2Data = [key2 dataUsingEncoding:NSUTF8StringEncoding];
    Byte* key1Byte = (Byte*)[[key1Data base64EncodedDataWithOptions:0] bytes];
    Byte* key2Byte = (Byte*)[[key2Data base64EncodedDataWithOptions:0] bytes];
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,kCCOptionPKCS7Padding,key1Byte,kCCKeySizeDES,key2Byte,[textData bytes],dataLength,buffer,1024,&numBytesEncrypted);
    
    if (cryptStatus == kCCSuccess) {
        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
        ciphertext = [GTMBase64 stringByEncodingData:data];
    }
     return ciphertext;
}


举报
_谢__
发帖于2年前 0回/505阅
顶部