用 java DES 加密后的java 数据加密怎么用 Objective-C 解密

基于DES算法的数据文件加密解密的java编程实现_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
基于DES算法的数据文件加密解密的java编程实现
阅读已结束,下载本文需要
想免费下载本文?
定制HR最喜欢的简历
下载文档到电脑,同时保存到云知识,更方便管理
还剩15页未读,继续阅读
定制HR最喜欢的简历
你可能喜欢Objective-c和Java下DES加密保持一致的方式
首先,Java端的DES加密的实现方式,代码如下:
public class DES {
private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
public static String encryptDES(String encryptString, String encryptKey)
throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return Base64.encode(encryptedData);
上述代码用到了一个Base64的编码类,其代码的实现方式如下:
public class Base64 {
private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"
.toCharArray();
* data[]进行编码
* @param data
public static String encode(byte[] data) {
int start = 0;
int len = data.
StringBuffer buf = new StringBuffer(data.length * 3 / 2);
int end = len - 3;
int n = 0;
while (i &= end) {
int d = ((((int) data[i]) & 0x0ff) && 16)
| ((((int) data[i + 1]) & 0x0ff) && 8)
| (((int) data[i + 2]) & 0x0ff);
buf.append(legalChars[(d && 18) & 63]);
buf.append(legalChars[(d && 12) & 63]);
buf.append(legalChars[(d && 6) & 63]);
buf.append(legalChars[d & 63]);
if (n++ &= 14) {
buf.append(" ");
if (i == start + len - 2) {
int d = ((((int) data[i]) & 0x0ff) && 16)
| ((((int) data[i + 1]) & 255) && 8);
buf.append(legalChars[(d && 18) & 63]);
buf.append(legalChars[(d && 12) & 63]);
buf.append(legalChars[(d && 6) & 63]);
buf.append("=");
} else if (i == start + len - 1) {
int d = (((int) data[i]) & 0x0ff) && 16;
buf.append(legalChars[(d && 18) & 63]);
buf.append(legalChars[(d && 12) & 63]);
buf.append("==");
return buf.toString();
以上便是Java端的DES加密方法的全部实现过程。
我还编写了一个将byte的二进制转换成16进制的方法,以便调试的时候使用打印输出加密后的byte数组的内容,这个方法不是加密的部分,只是为调试而使用的:
/**将二进制转换成16进制
* @param buf
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i & buf. i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' +
sb.append(hex.toUpperCase());
return sb.toString();
下面是Objective-c在iOS上实现的DES加密算法:
const Byte iv[] = {1,2,3,4,5,6,7,8};
+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key
NSString *ciphertext =
NSData *textData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
NSUInteger dataLength = [textData length];
unsigned char buffer[1024];
memset(buffer, 0, sizeof(char));
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
kCCOptionPKCS7Padding,
[key UTF8String], kCCKeySizeDES,
[textData bytes], dataLength,
buffer, 1024,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
ciphertext = [Base64 encode:data];
下面也是Objective-c的一??个二进??制转换为16进制的方法,也是为了测试方便查看写的:
+(NSString *) parseByte2HexString:(Byte *) bytes
NSMutableString *hexStr = [[NSMutableString alloc]init];
int i = 0;
while (bytes[i] != '')
NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数
if([hexByte length]==1)
[hexStr appendFormat:@"0%@", hexByte];
[hexStr appendFormat:@"%@", hexByte];
NSLog(@"bytes 的16进制数为:%@",hexStr);
return hexS
+(NSString *) parseByteArray2HexString:(Byte[]) bytes
NSMutableString *hexStr = [[NSMutableString alloc]init];
int i = 0;
while (bytes[i] != '')
NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数
if([hexByte length]==1)
[hexStr appendFormat:@"0%@", hexByte];
[hexStr appendFormat:@"%@", hexByte];
NSLog(@"bytes 的16进制数为:%@",hexStr);
return hexS
以上的加密方法所在的包是CommonCrypto/CommonCryptor.h。
以上便实现了Objective-c和Java下在相同的明文和密钥的情况下生成相同明文的算法。
Base64的算法可以用你们自己写的那个,不一定必须使用我提供的这个。解密的时候还要用Base64进行密文的转换。
iOS下的Base64算法在后面 。
JAVA下的解密算法如下:
private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
  public static String decryptDES(String decryptString, String decryptKey)
throws Exception {
byte[] byteMi = Base64.decode(decryptString);
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
byte decryptedData[] = cipher.doFinal(byteMi);
return new String(decryptedData);
Base64的decode方法如下:
public static byte[] decode(String s) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
decode(s, bos);
} catch (IOException e) {
throw new RuntimeException();
byte[] decodedBytes = bos.toByteArray();
bos.close();
} catch (IOException ex) {
System.err.println("Error while decoding BASE64: " + ex.toString());
return decodedB
private static void decode(String s, OutputStream os) throws IOException {
int i = 0;
int len = s.length();
while (true) {
while (i & len && s.charAt(i) &= ' ')
if (i == len)
int tri = (decode(s.charAt(i)) && 18)
+ (decode(s.charAt(i + 1)) && 12)
+ (decode(s.charAt(i + 2)) && 6)
+ (decode(s.charAt(i + 3)));
os.write((tri && 16) & 255);
if (s.charAt(i + 2) == '=')
os.write((tri && 8) & 255);
if (s.charAt(i + 3) == '=')
os.write(tri & 255);
private static int decode(char c) {
if (c &= 'A' && c &= 'Z')
return ((int) c) - 65;
else if (c &= 'a' && c &= 'z')
return ((int) c) - 97 + 26;
else if (c &= '0' && c &= '9')
return ((int) c) - 48 + 26 + 26;
switch (c) {
return 62;
return 63;
throw new RuntimeException("unexpected code: " + c);
Objective-c在下的DES解密算法:
+(NSString *)decryptUseDES:(NSString *)cipherText key:(NSString *)key
NSString *plaintext =
NSData *cipherdata = [Base64 decode:cipherText];
unsigned char buffer[1024];
memset(buffer, 0, sizeof(char));
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
kCCOptionPKCS7Padding,
[key UTF8String], kCCKeySizeDES,
[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];
下面是objective-c 实现的Base64工具对象,当然你也可以选择使用google的那个Base64类——(功能很强大),初步测试使用GTMBase64和使用我写的这个Base64效果都是一样的。
static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
@interface Base64()
+(int)char2Int:(char)c;
@implementation Base64
+(NSString *)encode:(NSData *)data
if (data.length == 0)
char *characters = malloc(data.length * 3 / 2);
if (characters == NULL)
int end = data.length - 3;
int index = 0;
int charCount = 0;
int n = 0;
while (index &= end) {
int d = (((int)(((char *)[data bytes])[index]) & 0x0ff) && 16)
| (((int)(((char *)[data bytes])[index + 1]) & 0x0ff) && 8)
| ((int)(((char *)[data bytes])[index + 2]) & 0x0ff);
characters[charCount++] = encodingTable[(d && 18) & 63];
characters[charCount++] = encodingTable[(d && 12) & 63];
characters[charCount++] = encodingTable[(d && 6) & 63];
characters[charCount++] = encodingTable[d & 63];
index += 3;
if(n++ &= 14)
characters[charCount++] = ' ';
if(index == data.length - 2)
int d = (((int)(((char *)[data bytes])[index]) & 0x0ff) && 16)
| (((int)(((char *)[data bytes])[index + 1]) & 255) && 8);
characters[charCount++] = encodingTable[(d && 18) & 63];
characters[charCount++] = encodingTable[(d && 12) & 63];
characters[charCount++] = encodingTable[(d && 6) & 63];
characters[charCount++] = '=';
else if(index == data.length - 1)
int d = ((int)(((char *)[data bytes])[index]) & 0x0ff) && 16;
characters[charCount++] = encodingTable[(d && 18) & 63];
characters[charCount++] = encodingTable[(d && 12) & 63];
characters[charCount++] = '=';
characters[charCount++] = '=';
NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];
return rtnS
+(NSData *)decode:(NSString *)data
if(data == nil || data.length &= 0) {
NSMutableData *rtnData = [[NSMutableData alloc]init];
int slen = data.
int index = 0;
while (true) {
while (index & slen && [data characterAtIndex:index] &= ' ') {
if (index &= slen || index
+ 3 &= slen) {
int byte = ([self char2Int:[data characterAtIndex:index]] && 18) + ([self char2Int:[data characterAtIndex:index + 1]] && 12) + ([self char2Int:[data characterAtIndex:index + 2]] && 6) + [self char2Int:[data characterAtIndex:index + 3]];
Byte temp1 = (byte && 16) & 255;
[rtnData appendBytes:&temp1 length:1];
if([data characterAtIndex:index + 2] == '=') {
Byte temp2 = (byte && 8) & 255;
[rtnData appendBytes:&temp2 length:1];
if([data characterAtIndex:index + 3] == '=') {
Byte temp3 = byte & 255;
[rtnData appendBytes:&temp3 length:1];
index += 4;
return rtnD
+(int)char2Int:(char)c
if (c &= 'A' && c &= 'Z') {
return c - 65;
} else if (c &= 'a' && c &= 'z') {
return c - 97 + 26;
} else if (c &= '0' && c &= '9') {
return c - 48 + 26 + 26;
switch(c) {
return 62;
return 63;
return -1;
这个和java端的Base64的是一个算法,只是根据语言的特点不同有少许的改动。
Java端的测试代码如下:
String plaintext = "abcd";
String ciphertext = DES.encryptDES(plaintext, "");
System.out.println("明文:" + plaintext);
System.out.println("密钥:" + "");
System.out.println("密文:" + ciphertext);
System.out.println("解密后:" + DES.decryptDES(ciphertext, ""));
输出结果:
明文:abcd
密文:W7HR43/usys=
解密后:abcd
Objective-c端的测试代码如下:
NSString *plaintext = ;
NSString *ciphertext = [EncryptUtil encryptUseDES:plaintext key:];
NSLog(,plaintext);
NSLog(,ciphertext);
输出结果:
-- :: TestEncrypt[:f803] 明文:abcd
-- :: TestEncrypt[:f803] 秘钥:
-- :: TestEncrypt[:f803] 密文:W7HR43/usys=
Copyright (C) , All Rights Reserved.
版权所有 闽ICP备号
processed in 0.051 (s). 12 q(s)Pages: 1/2
主题 : IOS的DES加密解密需要与服务器端的java加密结果一致
级别: 新手上路
可可豆: 11 CB
威望: 11 点
在线时间: 3(时)
发自: Web Page
IOS的DES加密解密需要与服务器端的java加密结果一致&&&
网上的例子我基本都已经看了 ios加密的结果和java的不一致。由于业务需要 需要提供各个语言版本的 DES加密解密 java和php的加密解密已经做好了结果也一致,下面是java的代码和php 的代码 麻烦提供下ios版的DES加密解密谢谢!!!思路是这样的DES的key值是经过Base64加密的一个字符串,返回的时候经过base64加密public class DES {         public static String encryptDES(String encryptString, String encryptKey)                        throws Exception {                byte[] rawKey=Base64.decode(encryptKey);                IvParameterSpec zeroIv = new IvParameterSpec(rawKey);                SecretKeySpec key = new SecretKeySpec(rawKey, &DES&);                Cipher cipher = Cipher.getInstance(&DES/CBC/PKCS5Padding&);                cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);                byte[] encryptedData = cipher.doFinal(encryptString.getBytes());                return Base64.encode(encryptedData);        }        public static String decryptDES(String decryptString, String decryptKey)                        throws Exception {                byte[] rawKey=Base64.decode(decryptKey);                IvParameterSpec zeroIv = new IvParameterSpec(rawKey);                SecretKeySpec key = new SecretKeySpec(rawKey, &DES&);                Cipher cipher = Cipher.getInstance(&DES/CBC/PKCS5Padding&);                cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);                byte[] encryptedData=Base64.decode(decryptString);                byte decryptedData[] = cipher.doFinal(encryptedData);                return new String(decryptedData, &UTF-8&).trim();        }}php版本的&?phpclass DES{    var $    var $ //偏移量    function DES($key, $iv=0){        $this-&key = base64_decode($key);        if($iv == 0){            $this-&iv = $this-&        }else {            $this-&iv = $        }    }    //加密    function encrypt($str){                $size = mcrypt_get_block_size ( MCRYPT_DES, MCRYPT_MODE_CBC );                 $str = $this-&pkcs5Pad ( $str, $size );         $data=mcrypt_cbc(MCRYPT_DES, $this-&key, $str, MCRYPT_ENCRYPT, $this-&iv);         return base64_encode($data);    }    //解密    function decrypt($str){        $str = base64_decode ($str);        //$strBin = $this-&hex2bin( strtolower($str));        $str = mcrypt_cbc(MCRYPT_DES, $this-&key, $str, MCRYPT_DECRYPT, $this-&iv);        $str = $this-&pkcs5Unpad( $str );        return $    }    function hex2bin($hexData){        $binData = &&;        for($i = 0; $i & strlen ( $hexData ); $i += 2)        {            $binData .= chr(hexdec(substr($hexData, $i, 2)));        }        return $binD    }    function pkcs5Pad($text, $blocksize){        $pad = $blocksize - (strlen ( $text ) % $blocksize);        return $text . str_repeat ( chr ( $pad ), $pad );    }    function pkcs5Unpad($text){        $pad = ord ( $text {strlen ( $text ) - 1} );        if ($pad & strlen ( $text ))                    if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad)                    return substr ( $text, 0, - 1 * $pad );    }}$key = &U1VOWElBTkM=&;//这个key是经过base64加密后的结果原值是SUNXIANC$string1 = &abcd&;$des = new DES($key);$encryption = $des-&encrypt($string1);$decryption = $des-&decrypt($encryption);echo &ori:&.$echo &&br /&&;echo &des:&.$上面的两个版本测试结果原始key:SUNXIANC经过Base64加密后的key:U1VOWElBTkM= 将这个字符串作为DES的key把字符串abcd 进行DES加密的结果为SekgjW1matQ=但是ios下面就不一致;下面是我的ios的代码+ (NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key{    [Base64 initialize];    NSString *ciphertext =    const char *textBytes = [plainText UTF8String];    NSUInteger dataLength = [plainText length];    unsigned char buffer[1024];    memset(buffer, 0, sizeof(char));    size_t numBytesEncrypted = 0;    NSData *rawData = [Base64 decode:key];    NSString *rawKey = [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,                                           kCCAlgorithmDES,                                          kCCOptionPKCS7Padding,                                          rawKey,                                           kCCKeySizeDES,                                          nil,                                          textBytes, dataLength,                                          buffer, 1024,                                          &numBytesEncrypted);    if (cryptStatus == kCCSuccess) {        NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];        ciphertext = [Base64 encode:data];    }   }新手入门就遇见这么个问题,请大家帮忙了
级别: 侠客
可可豆: 460 CB
威望: 460 点
在线时间: 215(时)
发自: Web Page
你ios里的是kCCOptionPKCS7Padding,java的是PKCS5Padding,,,这两个要一样才行
共你那雅别。。
级别: 新手上路
可可豆: 11 CB
威望: 11 点
在线时间: 3(时)
发自: Web Page
回 1楼(110440) 的帖子
但是objc里没有PKCS5Padding啊 主要是objc那段代码的参数问题
级别: 骑士
UID: 30168
可可豆: 1042 CB
威望: 1737 点
在线时间: 475(时)
发自: Web Page
楼主同求呀!
级别: 侠客
可可豆: 539 CB
威望: 539 点
在线时间: 243(时)
发自: Web Page
回 楼主(sunxian99) 的帖子
请问 你这个问题解决了吗 我也是这个问题
级别: 侠客
可可豆: 650 CB
威望: 650 点
在线时间: 113(时)
发自: Web Page
两端都用PKCS7Padding和ECBMode就可以了
级别: 侠客
可可豆: 670 CB
威望: 670 点
在线时间: 650(时)
发自: Web Page
兄弟您 的问题解决了?
级别: 新手上路
UID: 183414
可可豆: 94 CB
威望: 28 点
在线时间: 469(时)
发自: Web Page
回 楼主(sunxian99) 的帖子
兄弟 解决这个问题了吗? 我这边也遇到同样的问题了 求指导
级别: 新手上路
可可豆: 112 CB
威望: 112 点
在线时间: 236(时)
发自: Web Page
&&楼主 这个问题 解决了吗,小弟也遇到这个问题,求指导
级别: 新手上路
可可豆: 60 CB
威望: 60 点
在线时间: 25(时)
发自: Web Page
好多遇到这个问题的啊&&同求
Pages: 1/2
关注本帖(如果有新回复会站内信通知您)
发帖、回帖都会得到可观的积分奖励。
按"Ctrl+Enter"直接提交
关注CocoaChina
关注微信 每日推荐
扫一扫 关注CVP公众号
扫一扫 浏览移动版Java用des加密后用 linux c语言解密 怎么互通_百度知道
Java用des加密后用 linux c语言解密 怎么互通
我有更好的答案
只要确保秘钥一致,用哪种语言进行加解密都没有问题的,如果中文出现差错检查是否字符集设置问题。
标准的,可以用任何语言
。。。。。。。。。
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。

我要回帖

更多关于 java数据传输加密技术 的文章

 

随机推荐