genkeypair.lpr 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. {$mode objfpc}
  2. {$h+}
  3. program genkeypair;
  4. uses sysutils, openssl;
  5. // This is normally only used when you specify a cipher for encoding the private key.
  6. function PasswordCallback(buf:PAnsiChar; size:Integer; rwflag:Integer; userdata: Pointer):Integer; cdecl;
  7. begin
  8. Result:=0;
  9. Buf^:=#0;
  10. end;
  11. procedure DoKey(Const FNPrivate, FNPublic : String; AKeySize : Integer = 1024);
  12. Procedure RaiseErr(Const Msg : String);
  13. Var
  14. Err : String;
  15. begin
  16. SetLength(Err,1024);
  17. ErrErrorString(ErrGetError,Err,1024);
  18. Raise Exception.Create(Msg+' : '+Err);
  19. end;
  20. Function GetKey(K : pBIO) : String;
  21. Var
  22. L : Integer;
  23. p : pchar;
  24. begin
  25. l:=BIO_ctrl(K,BIO_CTRL_INFO,0,PChar(@P));
  26. setlength(Result,l);
  27. move(P^,Result[1],l);
  28. end;
  29. Procedure WriteKey(Const FN,Key : String);
  30. Var
  31. F : Text;
  32. begin
  33. Assign(F,FN);
  34. Rewrite(F);
  35. try
  36. Write(F,Key);
  37. finally
  38. Close(F);
  39. end;
  40. end;
  41. Var
  42. rsa: PRSA;
  43. PK :PEVP_PKEY;
  44. PrivKey, PubKey: pBIO;
  45. Key : string;
  46. begin
  47. InitLibeaInterface(true);
  48. InitSSLEAInterface(true);
  49. InitSSLInterface(true);
  50. ERR_load_crypto_strings;
  51. OpenSSL_add_all_ciphers;
  52. pk := EvpPkeynew;
  53. if (pk=Nil) then
  54. Raise exception.Create('Could not create key structure.');
  55. rsa:=RsaGenerateKey(AKeySize,$10001,Nil,Nil);
  56. if rsa=nil then
  57. Raise exception.Create('Could not create RSA key.');
  58. if EvpPkeyAssign(pk, EVP_PKEY_RSA, rsa)=0 then
  59. Raise exception.Create('Could not assign created RSA key to key structure.');
  60. // Generate private key
  61. PrivKey:=BIOnew(BIOsmem);
  62. if PrivKey=Nil then
  63. Raise exception.Create('Could not allocate BIO structure for private key.');
  64. try
  65. if PEM_write_bio_PrivateKey(PrivKey, PK, nil, nil, 0, @PasswordCallBack, Nil)=0 then
  66. RaiseErr('Could not write private key');
  67. Key:=GetKey(PrivKey);
  68. WriteKey(FNPrivate,Key);
  69. finally
  70. BioFreeAll(PrivKey);
  71. end;
  72. // Get public key
  73. PubKey:= BIOnew(BIOsmem);
  74. if PubKey=Nil then
  75. Raise exception.Create('Could not allocate BIO structure for public key.');
  76. try
  77. if PEM_write_bio_PubKey(PubKey,PK)=0 then
  78. RaiseErr('Could not write public key');
  79. Key:=GetKey(PubKey);
  80. WriteKey(FNPublic,Key);
  81. finally
  82. BioFreeAll(PubKey);
  83. end;
  84. end;
  85. begin
  86. writeln('Writing private/public key of length 1024 to id_rsa/id_rsa.pub');
  87. DoKey('id_rsa','id_rsa.pub',1024);
  88. end.