summaryrefslogtreecommitdiff
path: root/fpcsrc/packages/openssl/examples/genkeypair.lpr
blob: 3ec7cbba4a00c784457152477706dcbc583e31ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
{$mode objfpc}
{$h+}
program genkeypair;

uses sysutils, openssl;

// This is normally only used when you specify a cipher for encoding the private key.

function PasswordCallback(buf:PAnsiChar; size:Integer; rwflag:Integer; userdata: Pointer):Integer; cdecl;

begin
  Result:=0;
  Buf^:=#0;
end;

procedure DoKey(Const FNPrivate, FNPublic : String; AKeySize : Integer = 1024);

  Procedure RaiseErr(Const Msg : String);

  Var
    Err : String;

  begin
    SetLength(Err,1024);
    ErrErrorString(ErrGetError,Err,1024);
    Raise Exception.Create(Msg+' : '+Err);
  end;

  Function GetKey(K : pBIO) : String;

  Var
    L : Integer;
    p : pchar;

  begin
    l:=BIO_ctrl(K,BIO_CTRL_INFO,0,PChar(@P));
    setlength(Result,l);
    move(P^,Result[1],l);
  end;

  Procedure WriteKey(Const FN,Key : String);

  Var
    F : Text;

  begin
    Assign(F,FN);
    Rewrite(F);
    try
      Write(F,Key);
    finally
      Close(F);
    end;
  end;


Var
  rsa: PRSA;
  PK :PEVP_PKEY;
  PrivKey, PubKey: pBIO;
  Key : string;

begin
  InitLibeaInterface(true);
  InitSSLEAInterface(true);
  InitSSLInterface(true);
  ERR_load_crypto_strings;
  OpenSSL_add_all_ciphers;
  pk := EvpPkeynew;
  if (pk=Nil) then
    Raise exception.Create('Could not create key structure.');
  rsa:=RsaGenerateKey(AKeySize,$10001,Nil,Nil);
  if rsa=nil then
    Raise exception.Create('Could not create RSA key.');
  if EvpPkeyAssign(pk, EVP_PKEY_RSA, rsa)=0 then
    Raise exception.Create('Could not assign created RSA key to key structure.');
  // Generate private key
  PrivKey:=BIOnew(BIOsmem);
  if PrivKey=Nil then
    Raise exception.Create('Could not allocate BIO structure for private key.');
  try
    if PEM_write_bio_PrivateKey(PrivKey, PK, nil, nil, 0, @PasswordCallBack, Nil)=0 then
      RaiseErr('Could not write private key');
    Key:=GetKey(PrivKey);
    WriteKey(FNPrivate,Key);
  finally
    BioFreeAll(PrivKey);
  end;
  // Get public key
  PubKey:= BIOnew(BIOsmem);
  if PubKey=Nil then
    Raise exception.Create('Could not allocate BIO structure for public key.');
  try
    if PEM_write_bio_PubKey(PubKey,PK)=0 then
      RaiseErr('Could not write public key');
    Key:=GetKey(PubKey);
    WriteKey(FNPublic,Key);
  finally
    BioFreeAll(PubKey);
  end;
end;

begin
  writeln('Writing private/public key of length 1024 to id_rsa/id_rsa.pub');
  DoKey('id_rsa','id_rsa.pub',1024);
end.