Delphi与JAVA 互通AES文件加解密源码(支持D6-XE10)

Delphi用的人越来越少 了,可用资源越来越少。有什么好的完整的代码我都尽量拿出来跟大家分享,部分内容也是来自互联网整理

Delphi代码:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls,ElAES,math;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);



  private
    { Private declarations }
  public
    { Public declarations }
  end;

  type
  TKeyBit = (kb128, kb192, kb256);
  TCRLFMode = (rlCRLF, rlLF, rlCR, rlNONE);


var
  Form1: TForm1;

implementation

{$R *.dfm}

function ChangCRLFType(Value: string; CRLFMode: TCRLFMode): string;
var
  HasCRLF: Boolean;
begin
  Result := Value;
  HasCRLF := Pos(#10, Result) > 0;
  if not HasCRLF then
  begin
    HasCRLF := Pos(#13, Result) > 0;
  end;
  if HasCRLF then
  begin
    Result := StringReplace(Result, #13#10, #10, [rfReplaceAll]);
    Result := StringReplace(Result, #10#13, #10, [rfReplaceAll]);
    Result := StringReplace(Result, #13, #10, [rfReplaceAll]);
    if CRLFMode = rlCRLF then
    begin
      Result := StringReplace(Result, #10, #13#10, [rfReplaceAll]);
    end
    else if CRLFMode = rlCR then
    begin
      Result := StringReplace(Result, #10, #13, [rfReplaceAll]);
    end
    else if CRLFMode = rlNONE then
    begin
      Result := StringReplace(Result, #10, '', [rfReplaceAll]);
    end;
  end;
end;


function BytesOf(const Val: AnsiString): TBytes;
var
  Len: Integer;
begin
  Len := Length(Val);
  SetLength(Result, Len);
  Move(Val[1], Result[0], Len);
end;

function StringOf(const buf:TBytes): AnsiString;
begin
  SetLength(Result, Length(buf));
  CopyMemory(PAnsiChar(result), @buf[0], Length(buf));
end;


{ --  流加密函数 默认按照 128 位密匙解密 -- }
function EncryptStream(Stream: TStream; OutStrm:TStream;Key: string;
  KeyBit: TKeyBit = kb128; KeepKeyCRLF: Boolean = False;
  KeyCRLFMode: TCRLFMode = rlCRLF
  ): TStream;
var
  Count: Int64;
  AESKey128: TAESKey128;
  AESKey192: TAESKey192;
  AESKey256: TAESKey256;
  SS: TStringStream;
  AnsiKey: TBytes;
begin
  if KeepKeyCRLF then
  begin
    Key := ChangCRLFType(Key,KeyCRLFMode);
  end;
 // AnsiKey := TEncoding.ASCII.GetBytes(Key);
  AnsiKey :=  BytesOf(Key); //已转为ansi编码
//  OutStrm := TStream.Create;
  Stream.Position := 0;
  Count := Stream.Size;
  //OutStrm.Write(Count, SizeOf(Count));
  try
    { --  128 位密匙最大长度为 16 个字符 -- }
    if KeyBit = kb128 then
    begin
      FillChar(AESKey128, SizeOf(AESKey128), 0);
      Move(PByte(AnsiKey)^, AESKey128, Min(SizeOf(AESKey128), Length(AnsiKey)));
      EncryptAESStreamECB(Stream, 0, AESKey128, OutStrm);
    end;
    { --  192 位密匙最大长度为 24 个字符 -- }
    if KeyBit = kb192 then
    begin
      FillChar(AESKey192, SizeOf(AESKey192), 0);
      Move(PByte(AnsiKey)^, AESKey192, Min(SizeOf(AESKey192), Length(AnsiKey)));
      EncryptAESStreamECB(Stream, 0, AESKey192, OutStrm);
    end;
    { --  256 位密匙最大长度为 32 个字符 -- }
    if KeyBit = kb256 then
    begin
      FillChar(AESKey256, SizeOf(AESKey256), 0);
      Move(PByte(AnsiKey)^, AESKey256, Min(SizeOf(AESKey256), Length(AnsiKey)));
      EncryptAESStreamECB(Stream, 0, AESKey256, OutStrm);
    end;
    Result := OutStrm;
  finally
    //FreeAndNil(OutStrm);
  end;
end;


{ --  流解密函数 默认按照 128 位密匙解密 -- }
function DecryptStream(Stream: TStream;OutStrm: TStream; Key: string;  KeyBit: TKeyBit = kb128; KeepKeyCRLF: Boolean = False; KeyCRLFMode: TCRLFMode = rlCRLF ): TStream;
var
  Count, OutPos: Int64;
  AESKey128: TAESKey128;
  AESKey192: TAESKey192;
  AESKey256: TAESKey256;
  SS: TStringStream;
  AnsiKey: TBytes;
begin
  if KeepKeyCRLF then
  begin
    Key := ChangCRLFType(Key,KeyCRLFMode);
  end;
 // AnsiKey := TEncoding.ASCII.GetBytes(Key);
 AnsiKey :=  BytesOf(Key); //已转为ansi编码
  Stream.Position := 0;
  OutPos := OutStrm.Position;
 //Stream.ReadBuffer(Count, SizeOf(Count));
  count:=Stream.Size - Stream.Position;
  try
    { --  128 位密匙最大长度为 16 个字符 -- }
    if KeyBit = kb128 then
    begin
      FillChar(AESKey128, SizeOf(AESKey128), 0);
      Move(PByte(AnsiKey)^, AESKey128, Min(SizeOf(AESKey128), Length(AnsiKey)));

      //add by phx 2016-02-02
      Stream.Position := 0;
//      DecryptAESStreamECB(Stream, Stream.Size - Stream.Position, AESKey128, OutStrm);
      DecryptAESStreamECB(Stream, count, AESKey128, OutStrm);
    end;
    { --  192 位密匙最大长度为 24 个字符 -- }
    if KeyBit = kb192 then
    begin
      FillChar(AESKey192, SizeOf(AESKey192), 0);
      Move(PByte(AnsiKey)^, AESKey192, Min(SizeOf(AESKey192), Length(AnsiKey)));
      DecryptAESStreamECB(Stream, Stream.Size - Stream.Position, AESKey192,
        OutStrm);
    end;
    { --  256 位密匙最大长度为 32 个字符 -- }
    if KeyBit = kb256 then
    begin
      FillChar(AESKey256, SizeOf(AESKey256), 0);
      Move(PByte(AnsiKey)^, AESKey256, Min(SizeOf(AESKey256), Length(AnsiKey)));
      DecryptAESStreamECB(Stream, Stream.Size - Stream.Position, AESKey256,
        OutStrm);
    end;
    OutStrm.Size := OutPos + Count;
    OutStrm.Position := OutPos;
    Result := OutStrm;
  finally
    //FreeAndNil(OutStrm);
  end;
end;



procedure TForm1.Button1Click(Sender: TObject);
var
  InStream,OutStream: TMemoryStream;
  password: string;
begin
  password := 'fy22moe2cobs4ygs';
  InStream := TMemoryStream.Create;
  OutStream := TMemoryStream.Create;
  try
   //InStream := download_file_to_stream('http://localhost:8080/docs/1_encrypted.jpg', http_download_stream);
    InStream.LoadFromFile('E:\软件\idea_setting_Eecrypted.zip');
    InStream.Position := 0;
    OutStream := DecryptStream(InStream, OutStream, password) as TMemoryStream;
    OutStream.Position := 0;
    OutStream.SaveToFile('D:\idea_setting_Decrypted.zip');
  finally
    InStream.Free;
    OutStream.Free;
  end;

end;

procedure TForm1.Button2Click(Sender: TObject);
var
  my_stream: TMemoryStream;
  out_stream: TMemoryStream;
  password: string;
begin
  password := 'test_password123';
  try
    my_stream := TMemoryStream.Create;
    out_stream := TMemoryStream.Create;
    my_stream.LoadFromFile('d:\1.jpg');
    EncryptStream(my_stream, out_stream, password);
    out_stream.Position := 0;
    out_stream.SaveToFile('d:\1_encrypted.jpg');
  finally
    out_stream.Free;
    my_stream.Free;
  end;

end;

end.

JAVA代码:


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;

/**
 * @author wh445306
 * @version 1.0
 * @Description
 * @Date 2021-05-08 23:46
 */


public class AES {


   private static final String PASSWORD ="fy22moe2cobs4ygs";

    public static byte[] encrypt(byte[] Data) throws Exception {
        Key key = new SecretKeySpec(PASSWORD.getBytes(), "AES");
        // Cipher cipher =Cipher.getInstance("AES/ECB/PKCS5Padding");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = cipher.doFinal(Data);
        return encVal;
    }

    public static byte[] decrypt(byte[] encryptedData) throws Exception {
        Key key = new SecretKeySpec(PASSWORD.getBytes(), "AES");
        Cipher chiper = Cipher.getInstance("AES");
        chiper.init(Cipher.DECRYPT_MODE, key);
        byte[] decValue = chiper.doFinal(encryptedData);
        return decValue;
    }

    public static void encodeFile(String sourceFile,String outputFile) throws Exception {
        File file = new File(sourceFile);
        FileInputStream in = new FileInputStream(file);
        try{
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] tmpbuf = new byte[1024];
            int count = 0;
            while ((count = in.read(tmpbuf)) != -1) {
                bout.write(tmpbuf, 0, count);
                tmpbuf = new byte[1024];
            }
            byte[] orgData = bout.toByteArray();
            byte[] raw = encrypt(orgData);
            file = new File(outputFile);
            FileOutputStream out=null;
            try {
                out= new FileOutputStream(file);
                out.write(raw);
            } finally {
                out.close();
            }
        }finally{
            in.close();
        }
    }

    public static void decodeFile(String sourceFile,String outputFile) throws Exception{
        File file = new File(sourceFile);
        FileInputStream fis = new FileInputStream(file);
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] tmpbuf = new byte[1024];
            int count = 0;
            while ((count = fis.read(tmpbuf)) != -1) {
                bout.write(tmpbuf, 0, count);
                tmpbuf = new byte[1024];
            }
            byte[] orgData = bout.toByteArray();
            byte[] raws = decrypt(orgData);

            file = new File(outputFile);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(file);
                fos.write(raws);
            } finally {
                fos.close();
            }
        } finally {
            fis.close();
        }
    }

    public static void main(String[] args) {
//        String input_file="d:/1.jpg";
//        String output_file="d:/1_encrypted.jpg";
//        String after_decrypt_file="d:/2.jpg";
//        try {
//            encodeFile(input_file,output_file);
//            decodeFile(output_file,after_decrypt_file);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//        String input_file="D:\\Delphi_Project\\ETC\\bill_20210430_230103001_1_2.zip";
//        String output_file="D:\\Delphi_Project\\ETC\\bill_20210430_230103001_1_2_Decrypted.zip";
        String input_file="E:\\软件\\idea_setting.zip";
        String output_file="E:\\软件\\idea_setting_Eecrypted.zip";
        //String after_decrypt_file="d:/2.jpg";
        try {
            encodeFile(input_file,output_file);
           // decodeFile(input_file,output_file);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

posted @ 2022-10-04 00:13  IT情深  阅读(524)  评论(0编辑  收藏  举报