Convert RSA Public Key format to X509 Subject Key Info format

Download source code

There are two simple functions that convert RSA Public Key format to X509 Subject Key Info format in base64 and PEM representation.

//converts from RSA Public Key format to X509 Subject Key Info format
function Rsa2X509Convert(const ARsaPublicKey: string): string;
var
  rsaKey: TclRsaKey;
  key: TclByteArray;
begin
  rsaKey := TclRsaKey.Create();
  try
    rsaKey.Init();
 
    key := TclEncoder.DecodeBytes(ARsaPublicKey, cmBase64);
 
    rsaKey.SetRsaPublicKey(key);
    key := rsaKey.GetPublicKeyInfo();
 
    Result := TclEncoder.EncodeBytes(key, cmBase64);
  finally
    rsaKey.Free();
  end;
end;
































//converts from RSA Public Key PEM format to X509 Subject Key Info PEM format
function Rsa2X509PemConvert(const ARsaPublicKey: string): string;
var
  rsaKey: TclRsaKey;
  key: TclByteArray;
begin
  rsaKey := TclRsaKey.Create();
  try
    rsaKey.Init();
 
    if TclCryptEncoder.GetDataType(ARsaPublicKey) <> edtRsaPublicKey then
    begin
      raise Exception.Create('Wrong key format');
    end;
 
    key := TclCryptEncoder.DecodePem(ARsaPublicKey);
 
    rsaKey.SetRsaPublicKey(key);
    key := rsaKey.GetPublicKeyInfo();
 
    Result := TclCryptEncoder.EncodePem(key, edtPublicKeyInfo);
  finally
    rsaKey.Free();
  end;
end;

procedure TForm1.btnTestClick(Sender: TObject);
var
  RsaKeyPem, x509KeyInfo: string;
begin
  x509KeyInfo := Rsa2X509Convert('MEgCQQDCiZulctu+Tp2pZ7wfTyKhpSkYzqkRAwdmvNdvUVwgh8mwBAOdt9Mvhx+O' +
      'VokrzfLIJqeBBkbwTzxfgVeU6CL3AgMBAAE=');
  ShowMessage(x509KeyInfo);
 
  RsaKeyPem :=
'-----BEGIN RSA PUBLIC KEY-----'#$D#$A +
'MEgCQQDCiZulctu+Tp2pZ7wfTyKhpSkYzqkRAwdmvNdvUVwgh8mwBAOdt9Mvhx+O'#$D#$A'VokrzfLIJqeBBkbwTzxfgVeU6CL3AgMBAAE='#$D#$A +
'-----END RSA PUBLIC KEY-----'#$D#$A;
  x509KeyInfo := Rsa2X509PemConvert(RsaKeyPem);
  ShowMessage(x509KeyInfo);
end;
































Article ID: 80, Created On: 11/24/2016, Modified: 11/24/2016