2014-02-23 3 views
4

내 AES 256 암호화 방법을 구현하여 다음과 같이 Java에서 잘 작동합니다! 상기 방법에서 반환AES 256 암호화 - Java 용 Qt

private static final byte[] IV = { 
    0, 2, 4, 8, 16, 32, 64, 127, 
    127, 64, 32, 16, 8, 4, 2, 0 
}; 

    //actual encryption over here 
    private static byte[] encrypt(byte[] raw, byte[] clear) throws 
Exception { 
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 
    Cipher cipher = null; 

    if(isIVUsedForCrypto) { 
     cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(IV)); 
    } 
    else 
    { 
     cipher = Cipher.getInstance("AES"); 
     cipher.init(Cipher.ENCRYPT_MODE, skeySpec); 
    } 
    byte[] encrypted = cipher.doFinal(clear); 
    return encrypted; 
} 

바이트 배열 최종적 toHex 다음 방법을 사용하여 16 진수 문자열로 변환된다.

 public static String toHex(byte[] buf) { 
    if (buf == null) 
     return ""; 
    StringBuffer result = new StringBuffer(2*buf.length); 
    for (int i = 0; i < buf.length; i++) { 
     appendHex(result, buf[i]); 
    } 
    return result.toString(); 
} 
private final static String HEX = "ABCDEF"; 
private static void appendHex(StringBuffer sb, byte b) { 
    sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f)); 
} 

그래서 Java AES 256 암호화 코드를 사용하여 최종 결과는 16 진수 문자열입니다. 쿼트 부분 지금

,
QByteArray IV("0, 2, 4, 8, 16, 32, 64, 127,127, 64, 32, 16, 8, 4, 2, 0"); 


QString encrypt(QByteArray r, const QString &password) 
{ 
const char *sample = r.data(); 
string plain = password.toStdString(); 
string ciphertext; 
// Generate Cipher, Key, and CBC 
byte key[ AES::MAX_KEYLENGTH ], iv[ AES::BLOCKSIZE ]; 
StringSource(reinterpret_cast<const char *>(sample), true, 
       new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH))); 
memset(iv, 0x00, AES::BLOCKSIZE); 
CBC_Mode<AES>::Encryption Encryptor(key, sizeof(key), iv); 
StringSource(plain, true, new StreamTransformationFilter(Encryptor, 
       new HexEncoder(new StringSink(ciphertext)))); 
return QString::fromStdString(ciphertext); 
} 

그리고

제가 상기 함수를 호출하는 주요 방법에서

 QString encrypted = encrypt(result, "test"); 

"결과"마찬가지로 이루어 같이 I 통과하는 QByteArray 암호화하는 곳 자바.

두 경우 Java 및 Qt의 바이트 배열은 동일하게 가져옵니다. 나는 그것을 확인했다.

내 문제

Qt는 특히 어딘가에 자바와 Qt를 통해 얻은 HEX 결과가 일치하지 않는 때문에 실패에 대한 암호화 로직.

누구나 내가 Qt 부분에서 내가 뭘 잘못하고 있는지 말할 수 있습니까? IV 또는 QByteArrayresult을 올바르게 사용하지 않습니까?

+0

SecretKeySpec의 skeySpec ='와 키 새로운 SecretKeySpec의 (원시, "AES") 생성하는 단계;'* 정확히 * 자바 원시'에서 비밀 키를 구축 않는 방법을 ''AES '사용? – jww

+0

'Cipher.getInstance ("AES/CBC/PKCS5Padding");'- 저는 이것이 AES-128을 기본적으로 사용하고 있다고 생각합니다. 아마도 "AES256/CBC/PKCS5Padding"'을 시도해야 할 것입니다. Java [Cipher Algorithm Names] (http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Cipher)를 참조하십시오. – jww

답변

2

Java 구현시 키 해시 단계가 누락 된 것 같습니다. 키의 SHA256 해시를 사용하고 있습니다. 여기에 C++ 구현, 변화의 코드를 테스트하려면 :

QString encrypt(QByteArray r, const QString &password) 
{ 
const char *sample = r.data(); 
string plain = password.toStdString(); 
string ciphertext; 
// Generate Cipher, Key, and CBC 
byte key[ AES::MAX_KEYLENGTH ], iv[ AES::BLOCKSIZE ]; 
//StringSource(reinterpret_cast<const char *>(sample), true, 
//    new HashFilter(*(new SHA256), new ArraySink(key, AES::MAX_KEYLENGTH))); 
for(int i=0; i< AES::MAX_KEYLENGTH; ++i){ 
    key[i] = reinterpret_cast<const char *>(decodedKey)[i]; 
} 
memset(iv, 0x00, AES::BLOCKSIZE); 
CBC_Mode<AES>::Encryption Encryptor(key, sizeof(key), iv); 
StringSource(plain, true, new StreamTransformationFilter(Encryptor, 
       new HexEncoder(new StringSink(ciphertext)))); 
return QString::fromStdString(ciphertext); 
} 
+0

예. 앞으로 문제가 발생할 경우를 대비하여 여기에 의견을 추가하겠습니다. –

2

초기화 벡터는 자바 코드에서 다른과 Qt를 :

private static final byte[] IV = { 
    0, 2, 4, 8, 16, 32, 64, 127, 
    127, 64, 32, 16, 8, 4, 2, 0 
}; 

그리고 C++에서

:

memset(iv, 0x00, AES::BLOCKSIZE); // ==> This fills the iv array with 0s 

그래서 당신이 두 제도에 대한 동일한 IV를 사용해야합니다.

업데이트 : 당신은 자바처럼, 당신은 IV를 지정해야 AES의 CBC 모드에 대한 IV를 제공하기 위해

: AES :: BLOCKSIZE가 정의되어 있는지

byte iv[ AES::BLOCKSIZE ] = {0, 2, 4, 8, 16, 32, 64, 127, 
          127, 64, 32, 16, 8, 4, 2, 0}; 

주 라이브러리 헤더에 있으며 16입니다.

+0

sorush-r에게 다시 한번 감사드립니다. 그러면 제대로 작동할까요? qbytearray는 어떨까요? 나는 그것을 올바르게 사용하고 있습니다.죄송합니다 나는 자바 개발자이므로 C++을 이해하기가 어려워서 memset (iv, IV, AES :: BLOCKSIZE)을 사용해야한다는 것을 의미하는 –

+0

; 권리? –

+0

채팅을 위해이 공간에 가입하십시오. http://chat.stackoverflow.com/rooms/48187/qt –