Форум программистов, компьютерный форум, киберфорум
Delphi: WinAPI
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.62/13: Рейтинг темы: голосов - 13, средняя оценка - 4.62
0 / 0 / 0
Регистрация: 11.09.2021
Сообщений: 14
RAD XE3+

непонятки с библиотекой nss3.dll

11.09.2021, 04:10. Показов 2846. Ответов 15
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Delphi
1
2
3
4
5
6
7
8
  var
  // -------------------- описание функций из nss3.dll
  NSS_Init                    : function(configdir: pchar): dword; cdecl;
  NSS_Shutdown           : procedure; cdecl;
  PK11SDR_Decrypt        : function(data: PSECItem;  res: PSECItem; cx: pointer): dword; cdecl;
  // -------------------- описание функций из nss3.dll
 
  mozglue, nss : THandle;
Delphi
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
 Function LoadDll( path : string ) : boolean;
 
  begin
 
    Result:= False;
 
    mozglue:= LoadLibrary (pchar( path + '\mozglue.dll' ));
    nss:=     LoadLibrary (pchar( path + '\nss3.dll' ));
 
    @NSS_Init:=                GetProcAddress( nss, pchar('NSS_Init' ));
    @NSS_Shutdown:=            GetProcAddress( nss, pchar('NSS_Shutdown' ));
    @PK11SDR_Decrypt:=         GetProcAddress( nss, pchar('PK11SDR_Decrypt' ));
 
    if getlasterror = 127 then
    begin
    Writeln('Ошибка : Несовместимость разрядности exe и dll ');
    Result:= False;
    UnloadNss;
    readln;
    halt;
    end;
 
    Result:= true;
 
  end;
Delphi
1
2
3
4
5
6
7
Procedure SetProfile ( configdir : string );
 
  begin
 
  if NSS_Init(pchar( configdir )) = 0 then  Writeln('NSS инициализирован');
 
  end;
Delphi
1
2
3
4
5
6
7
  Procedure UnloadNss;
 
  begin
  NSS_Shutdown;
  FreeLibrary( mozglue );
  FreeLibrary( nss );
  end;

Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
begin
  try
 
  if LoadDll('C:\Program Files\Mozilla Firefox') then Writeln('Библиотеки загруженны');
 
  SetProfile( 'C:\Users\админ\AppData\Roaming\Mozilla\Firefox\Profiles\hcywzoac.default-release-1628541442949'); 
 
  UnloadNss;
 
  except
    on E: Exception do
     begin
      Writeln(E.ClassName, ': ', E.Message);
      readln;
     end;
  end;
end.
не получается заюзать nss3.dll.
не проходит инициализация.
Delphi
1
if NSS_Init(pchar( configdir )) = 0 then  Writeln('NSS инициализирован');
судя по исходникам написанных на с++ и с# NSS_Init должна возрашать 0, но у меня выходит 429496. Кто знает в чем дело ?
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
11.09.2021, 04:10
Ответы с готовыми решениями:

Программа с Dll библиотекой
Подскажите вот есть формула, по ней надо написать программу которая будет делать расчёт под цифрой 8 формула, написанная с помощью Dll...

Работа с библиотекой dll в delphi
Приветствую программистов, нужна помощь с созданием библиотеки. Точнее с правильным оформлением кода. Суть задания состоит в том чтобы...

Не получается подключить библиотеку Unmanaged.dll (Firefox nss3.dll)
Здравствуйте, начал изучать c#, очень понравилась тема декриптования, для начала решил из исходников собрать приложение для декриптования и...

15
Нарушитель
10225 / 5655 / 1257
Регистрация: 12.03.2015
Сообщений: 26,180
11.09.2021, 12:24
Цитата Сообщение от bispahegnu Посмотреть сообщение
судя по исходникам написанных на с++ и с#
Покаж
0
68 / 55 / 13
Регистрация: 26.07.2021
Сообщений: 191
11.09.2021, 14:38
Цитата Сообщение от bispahegnu Посмотреть сообщение
Delphi
1
2
3
4
5
6
7
Procedure SetProfile ( configdir : string );
 
 begin
 
 if NSS_Init(pchar( configdir )) = 0  then Writeln('NSS инициализирован');
 
 end;
Я не знаком с интимными подробностями Delphy. pchar( configdir ) - это точно указатель на строку, а не интерпретация её первых байтов как указателя? Может, нужно писать NSS_Init(@configdir)?
0
0 / 0 / 0
Регистрация: 11.09.2021
Сообщений: 14
11.09.2021, 18:49  [ТС]
Цитата Сообщение от Verevkin Посмотреть сообщение
Покаж
C#
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
using System;
using System.Text;
using System.Runtime.InteropServices;
 
namespace Fox.Helpers
{
    internal sealed class WinApi
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        internal static extern IntPtr LoadLibrary(string sFileName);
 
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool FreeLibrary(IntPtr hModule);
 
        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
        internal static extern IntPtr GetProcAddress(IntPtr hModule, string sProcName);
    }
 
    internal sealed class Nss3
    {
        public struct TSECItem
        {
            public int SECItemType;
            public IntPtr SECItemData;
            public int SECItemLen;
        }
 
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate long NssInit(string sDirectory);
 
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate long NssShutdown();
 
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate int Pk11SdrDecrypt(ref TSECItem tsData, ref TSECItem tsResult, int iContent);
    }
    public static class Decryptor
    {
        private static IntPtr hNss3;
        private static IntPtr hMozGlue;
 
        private static Nss3.NssInit fpNssInit;
        private static Nss3.Pk11SdrDecrypt fpPk11SdrDecrypt;
        private static Nss3.NssShutdown fpNssShutdown;
 
        public static bool LoadNSS(string sPath)
        {
            try
            {
                hMozGlue = WinApi.LoadLibrary(sPath + "\\mozglue.dll");
                hNss3 = WinApi.LoadLibrary(sPath + "\\nss3.dll");
 
                IntPtr ipNssInitAddr = WinApi.GetProcAddress(hNss3, "NSS_Init");
                IntPtr ipNssPk11SdrDecrypt = WinApi.GetProcAddress(hNss3, "PK11SDR_Decrypt");
                IntPtr ipNssShutdown = WinApi.GetProcAddress(hNss3, "NSS_Shutdown");
 
                fpNssInit = (Nss3.NssInit)Marshal.GetDelegateForFunctionPointer(ipNssInitAddr, typeof(Nss3.NssInit));
                fpPk11SdrDecrypt = (Nss3.Pk11SdrDecrypt)Marshal.GetDelegateForFunctionPointer(ipNssPk11SdrDecrypt, typeof(Nss3.Pk11SdrDecrypt));
                fpNssShutdown = (Nss3.NssShutdown)Marshal.GetDelegateForFunctionPointer(ipNssShutdown, typeof(Nss3.NssShutdown));
 
                return true;
            }
            catch (Exception ex) { Console.WriteLine("Failed to load NSS\n" + ex); return false; }
 
        }
 
        public static void UnLoadNSS()
        {
            fpNssShutdown();
            WinApi.FreeLibrary(hNss3);
            WinApi.FreeLibrary(hMozGlue);
        }
 
        public static bool SetProfile(string sProfile)
        {
            return (fpNssInit(sProfile) == 0);
        }
 
        public static string DecryptPassword(string sEncPass)
        {
            IntPtr lpMemory = IntPtr.Zero;
 
            try
            {
                byte[] bPassDecoded = Convert.FromBase64String(sEncPass);
 
                lpMemory = Marshal.AllocHGlobal(bPassDecoded.Length);
                Marshal.Copy(bPassDecoded, 0, lpMemory, bPassDecoded.Length);
 
                Nss3.TSECItem tsiOut = new Nss3.TSECItem();
                Nss3.TSECItem tsiItem = new Nss3.TSECItem();
 
                tsiItem.SECItemType = 0;
                tsiItem.SECItemData = lpMemory;
                tsiItem.SECItemLen = bPassDecoded.Length;
 
                if (fpPk11SdrDecrypt(ref tsiItem, ref tsiOut, 0) == 0)
                {
                    if (tsiOut.SECItemLen != 0)
                    {
                        byte[] bDecrypted = new byte[tsiOut.SECItemLen];
                        Marshal.Copy(tsiOut.SECItemData, bDecrypted, 0, tsiOut.SECItemLen);
 
                        return Encoding.UTF8.GetString(bDecrypted);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return null;
            }
            finally
            {
                if (lpMemory != IntPtr.Zero)
                    Marshal.FreeHGlobal(lpMemory);
            }
 
            return null;
        }
 
        public static string GetUTF8(string sNonUtf8)
        {
            try
            {
                byte[] bData = Encoding.Default.GetBytes(sNonUtf8);
                return Encoding.UTF8.GetString(bData);
            }
            catch { return sNonUtf8; }
        }
    }
}
0
Нарушитель
10225 / 5655 / 1257
Регистрация: 12.03.2015
Сообщений: 26,180
11.09.2021, 20:00
bispahegnu, Я хотел бы увидеть исходник самой dll или экспортируемой из неё функции NSS_Init().
Или документацию. Ибо можно только гадать, строку в какой кодировке эта функция ждёт на входе.
0
0 / 0 / 0
Регистрация: 11.09.2021
Сообщений: 14
11.09.2021, 21:22  [ТС]
Цитата Сообщение от Verevkin Посмотреть сообщение
Я хотел бы увидеть исходник самой dll или экспортируемой из неё функции NSS_Init().
C++
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/*
 * NSS utility functions
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
#ifndef __nss_h_
#define __nss_h_
 
/* The private macro _NSS_CUSTOMIZED is for NSS internal use only. */
#if defined(NSS_ALLOW_UNSUPPORTED_CRITICAL)
#define _NSS_CUSTOMIZED " (Customized build)"
#else
#define _NSS_CUSTOMIZED
#endif
 
/*
 * NSS's major version, minor version, patch level, build number, and whether
 * this is a beta release.
 *
 * The format of the version string should be
 *     "<major version>.<minor version>[.<patch level>[.<build number>]][ <ECC>][ <Beta>]"
 */
#define NSS_VERSION "3.69" _NSS_CUSTOMIZED
#define NSS_VMAJOR 3
#define NSS_VMINOR 69
#define NSS_VPATCH 0
#define NSS_VBUILD 0
#define NSS_BETA PR_FALSE
 
#ifndef RC_INVOKED
 
#include "seccomon.h"
 
typedef struct NSSInitParametersStr NSSInitParameters;
 
/*
 * parameters used to initialize softoken. Mostly strings used to
 * internationalize softoken. Memory for the strings are owned by the caller,
 * who is free to free them once NSS_ContextInit returns. If the string
 * parameter is NULL (as opposed to empty, zero length), then the softoken
 * default is used. These are equivalent to the parameters for
 * PK11_ConfigurePKCS11().
 *
 * field names match their equivalent parameter names for softoken strings
 * documented at https://developer.mozilla.org/en/PKCS11_Module_Specs.
 *
 * minPWLen
 *     Minimum password length in bytes.
 * manufacturerID
 *     Override the default manufactureID value for the module returned in
 *     the CK_INFO, CK_SLOT_INFO, and CK_TOKEN_INFO structures with an
 *     internationalize string (UTF8). This value will be truncated at 32
 *     bytes (not including the trailing NULL, partial UTF8 characters will be
 *     dropped).
 * libraryDescription
 *     Override the default libraryDescription value for the module returned in
 *     the CK_INFO structure with an internationalize string (UTF8). This value
 *     will be truncated at 32 bytes(not including the trailing NULL, partial
 *     UTF8 characters will be dropped).
 * cryptoTokenDescription
 *     Override the default label value for the internal crypto token returned
 *     in the CK_TOKEN_INFO structure with an internationalize string (UTF8).
 *     This value will be truncated at 32 bytes (not including the trailing
 *     NULL, partial UTF8 characters will be dropped).
 * dbTokenDescription
 *     Override the default label value for the internal DB token returned in
 *     the CK_TOKEN_INFO structure with an internationalize string (UTF8). This
 *     value will be truncated at 32 bytes (not including the trailing NULL,
 *     partial UTF8 characters will be dropped).
 * FIPSTokenDescription
 *     Override the default label value for the internal FIPS token returned in
 *     the CK_TOKEN_INFO structure with an internationalize string (UTF8). This
 *     value will be truncated at 32 bytes (not including the trailing NULL,
 *     partial UTF8 characters will be dropped).
 * cryptoSlotDescription
 *     Override the default slotDescription value for the internal crypto token
 *     returned in the CK_SLOT_INFO structure with an internationalize string
 *     (UTF8). This value will be truncated at 64 bytes (not including the
 *     trailing NULL, partial UTF8 characters will be dropped).
 * dbSlotDescription
 *     Override the default slotDescription value for the internal DB token
 *     returned in the CK_SLOT_INFO structure with an internationalize string
 *     (UTF8). This value will be truncated at 64 bytes (not including the
 *     trailing NULL, partial UTF8 characters will be dropped).
 * FIPSSlotDescription
 *     Override the default slotDecription value for the internal FIPS token
 *     returned in the CK_SLOT_INFO structure with an internationalize string
 *     (UTF8). This value will be truncated at 64 bytes (not including the
 *     trailing NULL, partial UTF8 characters will be dropped).
 *
 */
struct NSSInitParametersStr {
    unsigned int length; /* allow this structure to grow in the future,
                                * must be set */
    PRBool passwordRequired;
    int minPWLen;
    char *manufactureID;      /* variable names for strings match the */
    char *libraryDescription; /*   parameter name in softoken */
    char *cryptoTokenDescription;
    char *dbTokenDescription;
    char *FIPSTokenDescription;
    char *cryptoSlotDescription;
    char *dbSlotDescription;
    char *FIPSSlotDescription;
};
 
SEC_BEGIN_PROTOS
 
/*
 * Return a boolean that indicates whether the underlying library
 * will perform as the caller expects.
 *
 * The only argument is a string, which should be the version
 * identifier of the NSS library. That string will be compared
 * against a string that represents the actual build version of
 * the NSS library.
 */
extern PRBool NSS_VersionCheck(const char *importedVersion);
 
/*
 * Returns a const string of the NSS library version.
 */
extern const char *NSS_GetVersion(void);
 
/*
 * Open the Cert, Key, and Security Module databases, read only.
 * Initialize the Random Number Generator.
 * Does not initialize the cipher policies or enables.
 * Default policy settings disallow all ciphers.
 */
extern SECStatus NSS_Init(const char *configdir);
 
/*
 * Returns whether NSS has already been initialized or not.
 */
extern PRBool NSS_IsInitialized(void);
 
/*
 * Open the Cert, Key, and Security Module databases, read/write.
 * Initialize the Random Number Generator.
 * Does not initialize the cipher policies or enables.
 * Default policy settings disallow all ciphers.
 */
extern SECStatus NSS_InitReadWrite(const char *configdir);
 
/*
 * Open the Cert, Key, and Security Module databases, read/write.
 * Initialize the Random Number Generator.
 * Does not initialize the cipher policies or enables.
 * Default policy settings disallow all ciphers.
 *
 * This allows using application defined prefixes for the cert and key db's
 * and an alternate name for the secmod database. NOTE: In future releases,
 * the database prefixes my not necessarily map to database names.
 *
 * configdir - base directory where all the cert, key, and module datbases live.
 * certPrefix - prefix added to the beginning of the cert database example: "
 *                      "https-server1-"
 * keyPrefix - prefix added to the beginning of the key database example: "
 *                      "https-server1-"
 * secmodName - name of the security module database (usually "secmod.db").
 * flags - change the open options of NSS_Initialize as follows:
 *      NSS_INIT_READONLY - Open the databases read only.
 *      NSS_INIT_NOCERTDB - Don't open the cert DB and key DB's, just
 *                      initialize the volatile certdb.
 *      NSS_INIT_NOMODDB  - Don't open the security module DB, just
 *                      initialize the  PKCS #11 module.
 *      NSS_INIT_FORCEOPEN - Continue to force initializations even if the
 *                      databases cannot be opened.
 *      NSS_INIT_NOROOTINIT - Don't try to look for the root certs module
 *                      automatically.
 *      NSS_INIT_OPTIMIZESPACE - Use smaller tables and caches.
 *      NSS_INIT_PK11THREADSAFE - only load PKCS#11 modules that are
 *                      thread-safe, ie. that support locking - either OS
 *                      locking or NSS-provided locks . If a PKCS#11
 *                      module isn't thread-safe, don't serialize its
 *                      calls; just don't load it instead. This is necessary
 *                      if another piece of code is using the same PKCS#11
 *                      modules that NSS is accessing without going through
 *                      NSS, for example the Java SunPKCS11 provider.
 *      NSS_INIT_PK11RELOAD - ignore the CKR_CRYPTOKI_ALREADY_INITIALIZED
 *                      error when loading PKCS#11 modules. This is necessary
 *                      if another piece of code is using the same PKCS#11
 *                      modules that NSS is accessing without going through
 *                      NSS, for example Java SunPKCS11 provider.
 *      NSS_INIT_NOPK11FINALIZE - never call C_Finalize on any
 *                      PKCS#11 module. This may be necessary in order to
 *                      ensure continuous operation and proper shutdown
 *                      sequence if another piece of code is using the same
 *                      PKCS#11 modules that NSS is accessing without going
 *                      through NSS, for example Java SunPKCS11 provider.
 *                      The following limitation applies when this is set :
 *                      SECMOD_WaitForAnyTokenEvent will not use
 *                      C_WaitForSlotEvent, in order to prevent the need for
 *                      C_Finalize. This call will be emulated instead.
 *      NSS_INIT_RESERVED - Currently has no effect, but may be used in the
 *                      future to trigger better cooperation between PKCS#11
 *                      modules used by both NSS and the Java SunPKCS11
 *                      provider. This should occur after a new flag is defined
 *                      for C_Initialize by the PKCS#11 working group.
 *      NSS_INIT_COOPERATE - Sets 4 recommended options for applications that
 *                      use both NSS and the Java SunPKCS11 provider.
 *
 * Also NOTE: This is not the recommended method for initializing NSS.
 * The preferred method is NSS_init().
 */
#define NSS_INIT_READONLY 0x1
#define NSS_INIT_NOCERTDB 0x2
#define NSS_INIT_NOMODDB 0x4
#define NSS_INIT_FORCEOPEN 0x8
#define NSS_INIT_NOROOTINIT 0x10
#define NSS_INIT_OPTIMIZESPACE 0x20
#define NSS_INIT_PK11THREADSAFE 0x40
#define NSS_INIT_PK11RELOAD 0x80
#define NSS_INIT_NOPK11FINALIZE 0x100
#define NSS_INIT_RESERVED 0x200
 
#define NSS_INIT_COOPERATE NSS_INIT_PK11THREADSAFE |     \
                               NSS_INIT_PK11RELOAD |     \
                               NSS_INIT_NOPK11FINALIZE | \
                               NSS_INIT_RESERVED
 
#define SECMOD_DB "secmod.db"
 
typedef struct NSSInitContextStr NSSInitContext;
 
extern SECStatus NSS_Initialize(const char *configdir,
                                const char *certPrefix, const char *keyPrefix,
                                const char *secmodName, PRUint32 flags);
 
extern NSSInitContext *NSS_InitContext(const char *configdir,
                                       const char *certPrefix, const char *keyPrefix,
                                       const char *secmodName, NSSInitParameters *initParams, PRUint32 flags);
 
extern SECStatus NSS_ShutdownContext(NSSInitContext *);
 
/*
 * same as NSS_Init, but checks to see if we need to merge an
 * old database in.
 *   updatedir is the directory where the old database lives.
 *   updCertPrefix is the certPrefix for the old database.
 *   updKeyPrefix is the keyPrefix for the old database.
 *   updateID is a unique identifier chosen by the application for
 *      the specific database.
 *   updatName is the name the user will be prompted for when
 *      asking to authenticate to the old database  */
extern SECStatus NSS_InitWithMerge(const char *configdir,
                                   const char *certPrefix, const char *keyPrefix, const char *secmodName,
                                   const char *updatedir, const char *updCertPrefix,
                                   const char *updKeyPrefix, const char *updateID,
                                   const char *updateName, PRUint32 flags);
/*
 * initialize NSS without a creating cert db's, key db's, or secmod db's.
 */
SECStatus NSS_NoDB_Init(const char *configdir);
 
/*
 * Allow applications and libraries to register with NSS so that they are called
 * when NSS shuts down.
 *
 * void *appData application specific data passed in by the application at
 * NSS_RegisterShutdown() time.
 * void *nssData is NULL in this release, but is reserved for future versions of
 * NSS to pass some future status information * back to the shutdown function.
 *
 * If the shutdown function returns SECFailure,
 * Shutdown will still complete, but NSS_Shutdown() will return SECFailure.
 */
typedef SECStatus (*NSS_ShutdownFunc)(void *appData, void *nssData);
 
/*
 * Register a shutdown function.
 */
SECStatus NSS_RegisterShutdown(NSS_ShutdownFunc sFunc, void *appData);
 
/*
 * Remove an existing shutdown function (you may do this if your library is
 * complete and going away, but NSS is still running).
 */
SECStatus NSS_UnregisterShutdown(NSS_ShutdownFunc sFunc, void *appData);
 
/* Available options for NSS_OptionSet() and NSS_OptionGet().
 */
#define NSS_RSA_MIN_KEY_SIZE 0x001
#define NSS_DH_MIN_KEY_SIZE 0x002
#define NSS_DSA_MIN_KEY_SIZE 0x004
#define NSS_TLS_VERSION_MIN_POLICY 0x008
#define NSS_TLS_VERSION_MAX_POLICY 0x009
#define NSS_DTLS_VERSION_MIN_POLICY 0x00a
#define NSS_DTLS_VERSION_MAX_POLICY 0x00b
 
/* Until NSS 3.30, the PKCS#12 implementation used BMPString encoding
 * for all passwords.  This changed to use UTF-8 for non-PKCS#12 PBEs
 * in NSS 3.31.
 *
 * For backward compatibility, this option reverts the behavior to the
 * old NSS versions.  This option might be removed in the future NSS
 * releases; don't rely on it. */
#define __NSS_PKCS12_DECODE_FORCE_UNICODE 0x00c
#define NSS_DEFAULT_LOCKS 0x00d /* lock default values */
#define NSS_DEFAULT_SSL_LOCK 1  /* lock the ssl default values */
 
/*
 * Set and get global options for the NSS library.
 */
SECStatus NSS_OptionSet(PRInt32 which, PRInt32 value);
SECStatus NSS_OptionGet(PRInt32 which, PRInt32 *value);
 
/*
 * Close the Cert, Key databases.
 */
extern SECStatus NSS_Shutdown(void);
 
/*
 * set the PKCS #11 strings for the internal token.
 */
void PK11_ConfigurePKCS11(const char *man, const char *libdesc,
                          const char *tokdesc, const char *ptokdesc, const char *slotdesc,
                          const char *pslotdesc, const char *fslotdesc, const char *fpslotdesc,
                          int minPwd, int pwRequired);
 
/*
 * Dump the contents of the certificate cache and the temporary cert store.
 * Use to detect leaked references of certs at shutdown time.
 */
void nss_DumpCertificateCacheInfo(void);
 
SEC_END_PROTOS
 
#endif /* RC_INVOKED */
#endif /* __nss_h_ */
0
0 / 0 / 0
Регистрация: 11.09.2021
Сообщений: 14
11.09.2021, 21:52  [ТС]
nss.zip
0
 Аватар для snake32
3502 / 1685 / 236
Регистрация: 26.02.2009
Сообщений: 8,368
Записей в блоге: 6
11.09.2021, 23:50
bispahegnu, попробуйте заменить в Delphi везде PChar на PAnsiChar.
В XE3 sizeof(char)=2
sizeof(AnsiChar)=1
0
Нарушитель
10225 / 5655 / 1257
Регистрация: 12.03.2015
Сообщений: 26,180
12.09.2021, 00:36
Цитата Сообщение от snake32 Посмотреть сообщение
попробуйте заменить в Delphi везде PChar на PAnsiChar.
Ну таки да. Неизвестно, что подразумевалось под char при компиляции - один или 2 байта.
0
0 / 0 / 0
Регистрация: 11.09.2021
Сообщений: 14
12.09.2021, 01:57  [ТС]
Цитата Сообщение от snake32 Посмотреть сообщение
попробуйте заменить в Delphi везде PChar на PAnsiChar.
пробовал. тот же результат.

дээ. как-то с делфи они траблы да костыли выходят.
0
пофигист широкого профиля
4769 / 3204 / 862
Регистрация: 15.07.2013
Сообщений: 18,608
12.09.2021, 03:38
Цитата Сообщение от bispahegnu Посмотреть сообщение
как-то с делфи они траблы да костыли выходят.
Байку про плохого танцора слушали?
0
0 / 0 / 0
Регистрация: 11.09.2021
Сообщений: 14
12.09.2021, 04:34  [ТС]
Цитата Сообщение от northener Посмотреть сообщение
Байку про плохого танцора слушали?
конечно слышал, но ясности в ситуацию никакой не вносит.

я не могу понять, в чем собственно проблема. что я делаю не так ? Куда смотреть ?

примеров на делфи по использованию сторонних библиотек написанных на других языках просто нет.
Как описывать и использовать их функции додумывай сам.
0
 Аватар для snake32
3502 / 1685 / 236
Регистрация: 26.02.2009
Сообщений: 8,368
Записей в блоге: 6
12.09.2021, 08:10
Цитата Сообщение от bispahegnu Посмотреть сообщение
пробовал. тот же результат.
Дык, в структурах и описаниях ф-ий тоже надо
Где посмотреть код модуля seccomon.h?
Как вы его заменили?
0
0 / 0 / 0
Регистрация: 11.09.2021
Сообщений: 14
12.09.2021, 08:45  [ТС]
Цитата Сообщение от snake32 Посмотреть сообщение
Дык, в структурах и описаниях ф-ий тоже надо
так и сделал. исправил везде.

Цитата Сообщение от snake32 Посмотреть сообщение
Где посмотреть код модуля seccomon.h?
C++
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
/*
 * seccomon.h - common data structures for security libraries
 *
 * This file should have lowest-common-denominator datastructures
 * for security libraries.  It should not be dependent on any other
 * headers, and should not require linking with any libraries.
 */
 
#ifndef _SECCOMMON_H_
#define _SECCOMMON_H_
 
#include "utilrename.h"
#include "prtypes.h"
 
#ifdef __cplusplus
#define SEC_BEGIN_PROTOS extern "C" {
#define SEC_END_PROTOS }
#else
#define SEC_BEGIN_PROTOS
#define SEC_END_PROTOS
#endif
 
#include "secport.h"
 
typedef enum {
    siBuffer = 0,
    siClearDataBuffer = 1,
    siCipherDataBuffer = 2,
    siDERCertBuffer = 3,
    siEncodedCertBuffer = 4,
    siDERNameBuffer = 5,
    siEncodedNameBuffer = 6,
    siAsciiNameString = 7,
    siAsciiString = 8,
    siDEROID = 9,
    siUnsignedInteger = 10,
    siUTCTime = 11,
    siGeneralizedTime = 12,
    siVisibleString = 13,
    siUTF8String = 14,
    siBMPString = 15
} SECItemType;
 
typedef struct SECItemStr SECItem;
 
struct SECItemStr {
    SECItemType type;
    unsigned char *data;
    unsigned int len;
};
 
typedef struct SECItemArrayStr SECItemArray;
 
struct SECItemArrayStr {
    SECItem *items;
    unsigned int len;
};
 
/*
** A status code. Statuses are used by procedures that return status
** values. Again the motivation is so that a compiler can generate
** warnings when return values are wrong. Correct testing of status codes:
**
**  SECStatus rv;
**  rv = some_function (some_argument);
**  if (rv != SECSuccess)
**      do_an_error_thing();
**
*/
typedef enum _SECStatus {
    SECWouldBlock = -2,
    SECFailure = -1,
    SECSuccess = 0
} SECStatus;
 
/*
** A comparison code. Used for procedures that return comparison
** values. Again the motivation is so that a compiler can generate
** warnings when return values are wrong.
*/
typedef enum _SECComparison {
    SECLessThan = -1,
    SECEqual = 0,
    SECGreaterThan = 1
} SECComparison;
 
#endif /* _SECCOMMON_H_ */
Цитата Сообщение от snake32 Посмотреть сообщение
Как вы его заменили?
Delphi
1
2
3
4
5
6
7
type
  TSECItem =  record
  SECItemType: dword;
  SECItemData: pansichar;
  SECItemLen: dword;
  end;
  PSECItem = ^TSECItem;
0
 Аватар для snake32
3502 / 1685 / 236
Регистрация: 26.02.2009
Сообщений: 8,368
Записей в блоге: 6
12.09.2021, 11:00
Цитата Сообщение от bispahegnu Посмотреть сообщение
SECItemType: dword;
Вообще не факт, конечно, что sizeof(SECItemType) = 4 но обычно это так.
Можно поиграть с выравниванием через директиву Z, а так же с типом вызова stdcall или cdecl;
Delphi
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
type
  {$Z1} // выравнивание в 1 байт для enum'ов (доступны варианты Z2 Z4 Z8)
  TSECItemType = (
    siBuffer = 0,
    siClearDataBuffer = 1,
    siCipherDataBuffer = 2,
    siDERCertBuffer = 3,
    siEncodedCertBuffer = 4,
    siDERNameBuffer = 5,
    siEncodedNameBuffer = 6,
    siAsciiNameString = 7,
    siAsciiString = 8,
    siDEROID = 9,
    siUnsignedInteger = 10,
    siUTCTime = 11,
    siGeneralizedTime = 12,
    siVisibleString = 13,
    siUTF8String = 14,
    siBMPString = 15
  );
 
  TSECStatus = (
    SECWouldBlock = -2,
    SECFailure = -1,
    SECSuccess = 0
  );
 
  TSECComparison = (
    SECLessThan = -1,
    SECEqual = 0,
    SECGreaterThan = 1
  );
 
  TNSSInit = function( configdir:Pointer ):TSECStatus; //stdcall; //cdecl;
1
0 / 0 / 0
Регистрация: 11.09.2021
Сообщений: 14
12.09.2021, 14:39  [ТС]
спасибо за код. буду разбираться.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
12.09.2021, 14:39
Помогаю со студенческими работами здесь

Работа с библиотекой dll
Здравствуйте, помогите, очень нужна помощь. Объясните как проект windows form засунуть в библиотеку dll и подключить его в другом проекте...

Работа с dll библиотекой
Есть проект VS 2008 winApi. Использую компилятор Си. В одной из функций запускаю, поток с параметрами. Все функции находятся в...

Ошибка с библиотекой userenv.dll
Добрый вечер! Возникла следующая ошибка. Невозможно открыть или установить браузер, установить антивирусник и т.д. Откат системы,...

Сборка со статической библиотекой DLL
Я создал DLL. Затем эту библиотеку подключил к проеку с помощью References. Всё работает как надо. Но для выполнения программы требуется...

Работа с библиотекой Padeg.dll
В одном проекте библиотека работает нормально, а подключил к другому выдает ошибку: &quot;Была сделана попытка загрузить программу, имеющую...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
16
Ответ Создать тему
Новые блоги и статьи
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
Фото: Daniel Greenwood
kumehtar 13.11.2025
Расскажи мне о Мире, бродяга
kumehtar 12.11.2025
— Расскажи мне о Мире, бродяга, Ты же видел моря и метели. Как сменялись короны и стяги, Как эпохи стрелою летели. - Этот мир — это крылья и горы, Снег и пламя, любовь и тревоги, И бескрайние. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru