关于AES解密,java代码转成c++代码

Smile_Tiger 2014-04-29 07:00:49
客户提供了java的实现aes的代码,然后需要我这边c++实现解密


我在网上找了各种c++的aes算法,甚至包括Crypto++开源代码,结果发现产生的密文都是二进制数据,而客户提供的密文都是可显示字符,密文如下:

1oEqdH8vYSxza/LINXTbu8H86ssc7tkO227qErhtV+K/HNGBjZLrgA0loYTVQU505BQj078b9Mehcy1qfvGmiJxNZO1GsfN2ey0ActInMBw=

我是什么地方搞错了?

附带java源码



package test;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AspireAes {
private static AspireAes instance = null;

private Cipher cipher;

SecretKeySpec key = null;

AlgorithmParameterSpec iv = null;

public static AspireAes getInstance() {
String key = "0123456789abcdef0123456789abcdef", iv = "0123456789abcdef0123456789abcdef";
if (instance == null) {
instance = new AspireAes(key, iv);
}
return instance;
}

/**
* 将32bytes的16禁止串压缩成16bytes,充分利用128bits的密钥空间
*
* @param hex
* @return byte[]
*/
private static byte[] packHex(String hex) {
int len = hex.length() >> 1;
byte[] b = new byte[len];
short k = 0;
for (int i = 0, j = 0; i < len; i++, j = i << 1) {
k = Short.parseShort(hex.substring(j, j + 2), 16);
b[i] = (byte) (k & 0xff);
}
return b;
}

private AspireAes(String keyStr, String ivStr) {
try {
iv = new IvParameterSpec(packHex(ivStr));
key = new SecretKeySpec(packHex(keyStr), "AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}

/**
* 加密
*
* @param String
* txt
*
* @return String
*/
public byte[] encrypt(byte[] txt) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(txt);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}

/**
* 加密
*
* @param String
* txt
*
* @return String
*/
public String encrypt(String txt) {
try {
byte[] b = this.encrypt(txt.getBytes("utf-8"));
return Base64.encodeToString(b, 0, b.length, Base64.NO_WRAP);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

/**
* 加密
*
* @param String
* txt
*
* @return String
*/
public byte[] decrypt(byte[] txt) {
try {
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(txt);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
}
return null;
}

/**
* 加密
*
* @param String
* txt
*
* @return String
*/
public String decrypt(String txt) {

try {
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] b = txt.getBytes();
b = Base64.decode(b, 0, b.length, Base64.NO_WRAP);
b = cipher.doFinal(b);
return new String(b, "utf-8");
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}

public static void test() {
String txt = "JCE中支持AES,支持的模式和填充方式JCE中AES支持五中模式:CBC,CFB,ECB,OFB,PCBC;支持三种填充:NoPadding,PKCS5Padding,ISO10126Padding。不支持SSL3Padding。不支持“NONE”模式";
AspireAes aes = AspireAes.getInstance();
String x = aes.encrypt(txt);
System.out.print("加密:" + txt + "\t\t" + x+"\r\n");
txt=x;
x = aes.decrypt(txt);
System.out.print("解密:" + txt + "\t\t" + x+"\r\n");

}

/**
* @param args
*/
public static void main(String[] args) {
test();
}

}

...全文
330 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2014-04-30
  • 打赏
  • 举报
回复
#pragma comment(lib,"crypt32")
#include <windows.h>
#include <stdio.h>
#include <tchar.h>

//+-------------------------------------------------------------------------
// convert formatted string to binary
// If cchString is 0, then pszString is NULL terminated and
// cchString is obtained via strlen() + 1.
// dwFlags defines string format
// if pbBinary is NULL, *pcbBinary returns the size of required memory
// *pdwSkip returns the character count of skipped strings, optional
// *pdwFlags returns the actual format used in the conversion, optional
//--------------------------------------------------------------------------
BOOL
WINAPI
CryptStringToBinaryA(
    IN     LPCSTR  pszString,
    IN     DWORD     cchString,
    IN     DWORD     dwFlags,
    IN     BYTE     *pbBinary,
    IN OUT DWORD    *pcbBinary,
    OUT    DWORD    *pdwSkip,    //OPTIONAL
    OUT    DWORD    *pdwFlags    //OPTIONAL
    );
//+-------------------------------------------------------------------------
// convert formatted string to binary
// If cchString is 0, then pszString is NULL terminated and
// cchString is obtained via strlen() + 1.
// dwFlags defines string format
// if pbBinary is NULL, *pcbBinary returns the size of required memory
// *pdwSkip returns the character count of skipped strings, optional
// *pdwFlags returns the actual format used in the conversion, optional
//--------------------------------------------------------------------------
BOOL
WINAPI
CryptStringToBinaryW(
    IN     LPCWSTR  pszString,
    IN     DWORD     cchString,
    IN     DWORD     dwFlags,
    IN     BYTE     *pbBinary,
    IN OUT DWORD    *pcbBinary,
    OUT    DWORD    *pdwSkip,    //OPTIONAL
    OUT    DWORD    *pdwFlags    //OPTIONAL
    );
#ifdef UNICODE
#define CryptStringToBinary  CryptStringToBinaryW
#else
#define CryptStringToBinary  CryptStringToBinaryA
#endif // !UNICODE

//+-------------------------------------------------------------------------
// convert binary to formatted string
// dwFlags defines string format
// if pszString is NULL, *pcchString returns the size of required memory in byte
//--------------------------------------------------------------------------
BOOL
WINAPI
CryptBinaryToStringA(
    IN     CONST BYTE  *pbBinary,
    IN     DWORD        cbBinary,
    IN     DWORD        dwFlags,
    IN     LPSTR      pszString,
    IN OUT DWORD       *pcchString
    );
//+-------------------------------------------------------------------------
// convert binary to formatted string
// dwFlags defines string format
// if pszString is NULL, *pcchString returns the size of required memory in byte
//--------------------------------------------------------------------------
BOOL
WINAPI
CryptBinaryToStringW(
    IN     CONST BYTE  *pbBinary,
    IN     DWORD        cbBinary,
    IN     DWORD        dwFlags,
    IN     LPWSTR      pszString,
    IN OUT DWORD       *pcchString
    );
#ifdef UNICODE
#define CryptBinaryToString  CryptBinaryToStringW
#else
#define CryptBinaryToString  CryptBinaryToStringA
#endif // !UNICODE

// dwFlags has the following defines
#define CRYPT_STRING_BASE64HEADER           0x00000000
#define CRYPT_STRING_BASE64                 0x00000001
#define CRYPT_STRING_BINARY                 0x00000002
#define CRYPT_STRING_BASE64REQUESTHEADER    0x00000003
#define CRYPT_STRING_HEX                    0x00000004
#define CRYPT_STRING_HEXASCII               0x00000005
#define CRYPT_STRING_BASE64_ANY             0x00000006
#define CRYPT_STRING_ANY                    0x00000007
#define CRYPT_STRING_HEX_ANY                0x00000008
#define CRYPT_STRING_BASE64X509CRLHEADER    0x00000009
#define CRYPT_STRING_HEXADDR                0x0000000a
#define CRYPT_STRING_HEXASCIIADDR           0x0000000b

#define CRYPT_STRING_NOCR                   0x80000000

// CryptBinaryToString uses the following flags
// CRYPT_STRING_BASE64HEADER - base64 format with certificate begin
//                             and end headers
// CRYPT_STRING_BASE64 - only base64 without headers
// CRYPT_STRING_BINARY - pure binary copy
// CRYPT_STRING_BASE64REQUESTHEADER - base64 format with request begin
//                                    and end headers
// CRYPT_STRING_BASE64X509CRLHEADER - base64 format with x509 crl begin
//                                    and end headers
// CRYPT_STRING_HEX - only hex format
// CRYPT_STRING_HEXASCII - hex format with ascii char display
// CRYPT_STRING_HEXADDR - hex format with address display
// CRYPT_STRING_HEXASCIIADDR - hex format with ascii char and address display
//
// CryptBinaryToString accepts CRYPT_STRING_NOCR or'd into one of the above.
// When set, line breaks contain only LF, instead of CR-LF pairs.

// CryptStringToBinary uses the following flags
// CRYPT_STRING_BASE64_ANY tries the following, in order:
//    CRYPT_STRING_BASE64HEADER
//    CRYPT_STRING_BASE64
// CRYPT_STRING_ANY tries the following, in order:
//    CRYPT_STRING_BASE64_ANY
//    CRYPT_STRING_BINARY -- should always succeed
// CRYPT_STRING_HEX_ANY tries the following, in order:
//    CRYPT_STRING_HEXADDR
//    CRYPT_STRING_HEXASCIIADDR
//    CRYPT_STRING_HEXASCII
//    CRYPT_STRING_HEX


char *flags[12]={
"CRYPT_STRING_BASE64HEADER",
"CRYPT_STRING_BASE64",
"CRYPT_STRING_BINARY",
"CRYPT_STRING_BASE64REQUESTHEADER",
"CRYPT_STRING_HEX",
"CRYPT_STRING_HEXASCII",
"CRYPT_STRING_BASE64_ANY",
"CRYPT_STRING_ANY",
"CRYPT_STRING_HEX_ANY",
"CRYPT_STRING_BASE64X509CRLHEADER",
"CRYPT_STRING_HEXADDR",
"CRYPT_STRING_HEXASCIIADDR",
};
#define MAXC 1024
BYTE b[22]={
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,
0x41,0x42,0xB0,0xA1,0x4A,0x55,
};
BOOL r;
DWORD len,dwFlags;
TCHAR s[MAXC];
int _tmain() {
    _tprintf(_T("API CryptBinaryToString in crypt32.dll Demonstration:\n"));
    for (dwFlags=0;dwFlags<12;dwFlags++) {
        if (dwFlags==2
         || dwFlags==6
         || dwFlags==7
         || dwFlags==8) continue;
        r=CryptBinaryToString(b,22,dwFlags,NULL,&len);
        if (!r) {
            _tprintf(_T("CryptBinaryToString error!\n"));
            return 1;
        }
        if (len>MAXC) {
            _tprintf(_T("%d==len>MAXC==%d!\n"),len,MAXC);
            return 2;
        }
        r=CryptBinaryToString(b,22,dwFlags,s,&len);
        if (!r) {
            _tprintf(_T("CryptBinaryToString error!\n"));
            return 3;
        }
        _tprintf(_T("\n%s:[\n%s]\n"),flags[dwFlags],s);
    }
    return 0;
}
//API CryptBinaryToString in crypt32.dll Demonstration:
//
//CRYPT_STRING_BASE64HEADER:[
//-----BEGIN CERTIFICATE-----
//AAECAwQFBgcICQoLDA0OD0FCsKFKVQ==
//-----END CERTIFICATE-----
//]
//
//CRYPT_STRING_BASE64:[
//AAECAwQFBgcICQoLDA0OD0FCsKFKVQ==
//]
//
//CRYPT_STRING_BASE64REQUESTHEADER:[
//-----BEGIN NEW CERTIFICATE REQUEST-----
//AAECAwQFBgcICQoLDA0OD0FCsKFKVQ==
//-----END NEW CERTIFICATE REQUEST-----
//]
//
//CRYPT_STRING_HEX:[
//        00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f
//        41 42 b0 a1 4a 55
//]
//
//CRYPT_STRING_HEXASCII:[
//        00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f   ................
//        41 42 b0 a1 4a 55                                  AB..JU
//]
//
//CRYPT_STRING_BASE64X509CRLHEADER:[
//-----BEGIN X509 CRL-----
//AAECAwQFBgcICQoLDA0OD0FCsKFKVQ==
//-----END X509 CRL-----
//]
//
//CRYPT_STRING_HEXADDR:[
//0000    00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f
//0010    41 42 b0 a1 4a 55
//]
//
//CRYPT_STRING_HEXASCIIADDR:[
//0000    00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f   ................
//0010    41 42 b0 a1 4a 55                                  AB..JU
//]
//
majia2011 2014-04-30
  • 打赏
  • 举报
回复
看结尾的=,明显是base用来补齐的,这是基础,多接触些就知道了
Smile_Tiger 2014-04-30
  • 打赏
  • 举报
回复
虽然还是不对(应该是key 和 iv弄错了),但是理解了base64,结贴给分
jackyjkchen 2014-04-29
  • 打赏
  • 举报
回复
工作1年后真的发现有很多不懂安全的在搞安全相关的东西,真不放心
jackyjkchen 2014-04-29
  • 打赏
  • 举报
回复
不就是多了一步base64么。。。。。
unituniverse2 2014-04-29
  • 打赏
  • 举报
回复
先用BASE64把客户那个可显示字符串还原成二进制,再用你的AES处理
Smile_Tiger 2014-04-29
  • 打赏
  • 举报
回复
另外,我不懂java

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧