2016-10-13 122 views
-2

Delphi 7에서 문자열을 암호화해야합니다. 내가 관리 할 수 ​​있었던 유일한 암호화 라이브러리는 DCPCrypt입니다. DCPCrypt (3DES)를 사용하여 Delphi 7에서 문자열 암호화

나는 파일을 암호화 예를 공부하고, 문자열을 적응하려고하지만 난

이 제 기능입니다 ... 내가 비참하게 실패 두려워 :

function Encrypt3DES(psString, psKey: string): string; 
var 
    lCipher:TDCP_3des; 
    CipherIV: array of byte;  // the initialisation vector (for chaining modes) 
    lHash:TDCP_sha256; 
    lHashDigest: array of byte; // the result of hashing the passphrase with the salt 
    Salt: array[0..7] of byte; // a random salt to help prevent precomputated attacks 
    i:integer; 
begin 
    lHash:=TDCP_sha256.Create(nil); 
    SetLength(lHashDigest,lHash.HashSize div 8); 
    for i := 0 to 7 do 
     Salt[i] := Random(256); // just fill the salt with random values (crypto secure PRNG would be better but not _really_ necessary) 

    //strmOutput.WriteBuffer(Salt,Sizeof(Salt)); // write out the salt so we can decrypt! ***I don't know what to do with this*** 

    lHash.Init; 
    lHash.Update(Salt[0],Sizeof(Salt)); // hash the salt 
    lHash.UpdateStr(psKey); // and the passphrase 
    lHash.Final(lHashDigest[0]);   // store the output in HashDigest 

    lCipher:=TDCP_3des.Create(nil); 
    //3DES is a block cipher, we need an initialisation vector 

    SetLength(CipherIV,TDCP_blockcipher(lCipher).BlockSize div 8); 
    for i := 0 to (Length(CipherIV) - 1) do 
     CipherIV[i] := Random(256);   // again just random values for the IV 

    //strmOutput.WriteBuffer(CipherIV[0],Length(CipherIV)); // write out the IV so we can decrypt! ***I don't know what to do with this*** 

    lCipher.Init(lHashDigest[0],TNeo.Min(lCipher.MaxKeySize,lHash.HashSize),CipherIV); // initialise the cipher with the hash as key 
    TDCP_blockcipher(lCipher).CipherMode := cmCBC; // use CBC chaining when encrypting 

    //lCipher.EncryptStream(strmInput,strmOutput,strmInput.Size); // encrypt the entire file 
    result:=lCipher.EncryptString(psString); 
    lCipher.Burn; // important! get rid of keying information 
    //strmInput.Free; 
    //strmOutput.Free; 
end; 

하십시오, 곰 암호화가 어떻게 작동하는지 완전히 알지 못합니다. 문자열을 암호화하지는 않지만 바이너리는 알고 있지만 코드로 변환하는 방법을 모르겠습니다. 나는 그것을 실행할 때마다 다른 결과를 얻는다. (나는 임의의 값을 사용하는 것이 정상적이라고 생각한다.)하지만, 다른 서버에 이것을 보내야만 체크 할 수 있기 때문에 그렇게해야하는지 모르겠다. 거기의 완전성.

있길는 나에게 API에서 자바의 기능을했다,하지만 분명히 나는 ​​그것을 사용할 수 없습니다

public byte [] encrypt_3DES(final String claveHex, final String datos) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { 
    byte [] ciphertext = null; 
    // Crea la clave 
    DESedeKeySpec desKeySpec = new DESedeKeySpec(toByteArray(claveHex)); 
    SecretKey desKey = new SecretKeySpec(desKeySpec.getKey(), "DESede"); 
    // Crea un cifrador 
    Cipher desCipher = Cipher.getInstance("DESede/CBC/NoPadding"); 

    // Inicializa el cifrador para encriptar 
    desCipher.init(Cipher.ENCRYPT_MODE, desKey, new IvParameterSpec(IV)); 

    // Se añaden los 0 en bytes necesarios para que sea un múltiplo de 8 
    int numeroCerosNecesarios = 8 - (datos.length() % 8); 
    if (numeroCerosNecesarios == 8) { 
     numeroCerosNecesarios = 0; 
    } 
    ByteArrayOutputStream array = new ByteArrayOutputStream(); 
    array.write(datos.getBytes("UTF-8"), 0, datos.length()); 
    for (int i = 0; i < numeroCerosNecesarios; i++) { 
     array.write(0); 
    } 
    byte [] cleartext = array.toByteArray(); 
    // Encripta el texto 
    ciphertext = desCipher.doFinal(cleartext); 
    return ciphertext; 
} 

내가 어떤 종류의 영혼이 나에게이와 손을 줄 수있는, 정말 감사하게 될 거라고. 나는 며칠 동안이 일에 반대해왔다.

미리 감사드립니다.

+1

이럴 AES는 ... 3DES보다 선호되어야 우리의 [SynCrypto.pas] (https://github.com : 나는 누군가가 사용하는 DCPCrypt 필요가 경우에 내가 발견 다른 하나를 게시합니다 /synopse/mORMot/blob/master/SynCrypto.pas) 오픈 소스 유닛은 Delphi 7에서 완벽하게 작동합니다. PKCS7 패딩을 사용하는 C#에서 http://synopse.info/forum/viewtopic.php?id=3395를 참조하십시오. –

+1

@ ArnaudBouchez + . 정확하게. 3DES는 이미 20 년 동안 안전하지 않습니다. –

+0

그게 좋겠지 만, 제 전화는 아닙니다 (온라인 지불 시스템에 맞게 시스템을 조정해야합니다). SHA256과 함께 HMAC를 사용하여 양식을 보내야합니다. 그들은 JSON에서 폼을 준비하고, Base64로 인코딩하고, trasansaction-unique 키를 준비하고, 인코딩 된 폼과 트랜잭션 고유 키를 기반으로 SHA256 서명을 추가하도록 요청합니다. 이 키는 비밀 암호와 트랜잭션 ID를 3DES로 암호화하여 계산됩니다. 내가 붙어있는 곳이야. – Tarrakis

답변

1

이 예는 암호화/내가 가이드로 잘못 DCPCrypt 기능을 사용하고 나중에 발견 3DES https://sourceforge.net/p/tplockbox/wiki/Home/

unit Unit1; 

interface 

uses 
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, 
    Dialogs, StdCtrls, 
    //lockbox units 
    LbCipher, LbClass, LbAsym, LbRSA, LbString; 

type 
    TForm1 = class(TForm) 
    edPlainText: TEdit; 
    edCipherText: TEdit; 
    btnEncryptString: TButton; 
    btnDescryptString: TButton; 
    procedure btnEncryptStringClick(Sender: TObject); 
    procedure btnDescryptStringClick(Sender: TObject); 
    private 
    { Private declarations } 
    public 
    { Public declarations } 
    end; 

var 
    Form1: TForm1; 

implementation 

{$R *.dfm} 

Function TripleDesEncrypt(const APlaintext, APassphrase: String): String; 
Var 
    Key128: TKey128; 
begin 
    GenerateLMDKey(Key128, SizeOf(Key128), APassphrase); 
    result := TripleDESEncryptStringEx(APlainText, Key128, True); 
End; 

Function TripleDesDecrypt(const ACipherText, APassphrase: String): String; 
Var 
    Key128: TKey128; 
begin 
    GenerateLMDKey(Key128, SizeOf(Key128), APassphrase); 
    Try 
    result := TripleDESEncryptStringEx(ACipherText, Key128, False); 
    Except 
    Result := ''; 
    End; 
End; 

procedure TForm1.btnEncryptStringClick(Sender: TObject); 
begin 
    edCipherText.text := TripleDesEncrypt(edPlainText.Text, 'SecretPassphrase'); 
end; 

procedure TForm1.btnDescryptStringClick(Sender: TObject); 
begin 
    edPlainText.text := TripleDesDecrypt(edCipherText.text, 'SecretPassphrase'); 
end; 

end. 
+0

고마워요, 존. 월요일에 해보고 알려 드리겠습니다. – Tarrakis

+0

John 덕분에 완벽하게 작동했습니다! – Tarrakis

0

를 사용하여 문자열을 해독하기 위해 오픈 소스 TLockBox 라이브러리를 사용합니다.

function Encrypt3DES(psData, psKey: string): string; 
var 
    Cipher: TDCP_3des; 
begin 
    Cipher:= TDCP_3des.Create(nil); 
    Cipher.InitStr(psKey,TDCP_sha256);   // initialize the cipher with a hash of the passphrase 
    result:=Cipher.EncryptString(psData); 
    Cipher.Burn; 
    Cipher.Free; 
end;