powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Microsoft Access [игнор отключен] [закрыт для гостей] / Алгоритмы несиметричного шифрования помогите найти
17 сообщений из 17, страница 1 из 1
Алгоритмы несиметричного шифрования помогите найти
    #32196908
Фотография Senin Viktor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Что-то я сам найти не смог :(
все муть какая-то попадается (м.б.давно хелпа к поиску по яндексу не читал )
Нужен именно несиметричный алгоритм (а так же не помешала русскоязычная инфа) или на крайняк (на самый) сильный симетричный.
Я подозреваю, что он и в Виндоусе есть, но где?
Есть примеры функции CryptDecrypt из advapi32.dll, но вроде тока это симетричный.
Помогите ламеру!


З.Ы,
Желательно чтобы это был исходник на VB. В крайнем случае dll, которую можно без проблем распространять.
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32196931
LG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Несимметричные
RSA,
E-Curves (элиптические кривые)
Реализация
PGP (поищи, информации море),
Windows Crypto API(MSDN)
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32196942
Фотография Senin Viktor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
То что RSA несиметричный - я знаю, но как реализовать, где почитать?
PGP - это хорошо (Good :) , но надо распространять dll с прогой, прийдется весь pgp в установщик пихать?
Про Windows Crypto API(MSDN) я и сам написал, если знаешь способ заставить работь несиметричныйм способом - дай знать как. У меня есть пример тока симетричным способом. В MSDN полно инфы, но тема для меня новая и я не сразу вьезжаю в предмет разговора - так что надо сперва по-русск4и почитать
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32197100
VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32197163
Фотография Senin Viktor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
VIG, спасибо. М.б. когда-нибудь и куплю
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32197378
Fat Lamer
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Общие слова про RSA можно почитать здесь:
http://shrek.stup.ac.ru/manual/admin/tcpip/rsa_642.htm
http://www.3ka.mipt.ru/vlib/citforum/internet/infsecure/its2000_42.shtml
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32197396
Фотография Senin Viktor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2Fat Lamer

спасибо,


2All
Не ужто Crypt API никто не юзал?
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198047
LG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Поиск по гуглю ... ~5 мин ...
http://www.sources.ru/cpp/cpp_pgp_crypt.shtml
http://www.codetoad.com/vb_crypto_api.asp
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198065
Фотография Senin Viktor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2LG

Спасибо,но
1 -я ссылка - примеры на С++ - я в нем ни бум бум
2 -я ссылка - некая dll - обертка над Win32API. Это и у меня есть висходниках на VB.
Мне нужно именно на VB. Вернее уже есть.
Нужно разъяснения, теория. На русском ибо, как я уже писал, чтобы понять англ. текст (MSDN) надо хотя бы немного разбираться в преметной области - а я в ней ну полнуй профан.
Пока только нахожу ссылки на 1-2 стран. документы и то с картинками :)

З.Ы.
Можно, конечно, перевернуть весь инет в поисках нужной жемчужины, потратив уйму времени, но все-таки м.б. кто-то даст ссычку. Сэконимит чайнику-от-шифрования время?
Вот, хорошая статья, http://alexeenko.prima.susu.ac.ru/crypto/cryptoapi/default.asp.html#IDARBYWC , но примеры для .NET Хотя есть и теория. Если ничего не найду - буду заниматься реинжирингом C# в VB6 :)
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198085
VIG
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Viktor здесь исходники к книге которую ты М.б. когда-нибудь и купишь
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198336
вадя
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2Viktor

если с PGP будешь, или уже что-то делаешь, раскажи как
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198351
Фотография Senin Viktor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
2вадя

Ээээх
Если бы я все свои идеи сразу реализововал....

Пока ничего кроме шифрации с использование Win32API (симетричный). По хрен знает какому алгоритму и с какой битностью.


K_ùÕþŒãWí’¡¾‰ˆvJù ­jtïÕ¨È×Jú¯U#×zE¼eß«¼fÖ¢1… š)ÀìVM5…•\4…ZÎ!Z¿÷î—`eïŠ7¡9ûÑé`l¬aaDWÕ+÷vOl–ZËHxje+ÿŠLÂßu—=ø=@—9WowÈÖ|BÞ92
½S7‘›lªê!Í.‚FŸ=šWŸàãà’èƒþ¯ñ¢"5?öâ
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198510
вадя
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
спасибо за растолковку
в последнем абзаце особено популяро изложены твои проблемы, сочувствую, если что получится сообщи
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198518
Фотография Senin Viktor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
В последнем абзаце тоже самое, что и в первом :)
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198554
Kach
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
>Есть примеры функции CryptDecrypt из advapi32.dll, но вроде тока это >симетричный.
если нетяжко то немог бы скинуть примерчик на личный
а то у меня течто никак крокодил неловиться не растет барбос
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198580
Фотография Senin Viktor
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Создай модуль класса
c именем clsCryptoAPI

Код: plaintext
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.
334.
335.
336.
337.
338.
339.
340.
341.
342.
343.
344.
345.
346.
347.
348.
349.
350.
351.
352.
353.
354.
355.
356.
357.
358.
359.
360.
361.
362.
363.
364.
365.
366.
367.
368.
369.
370.
371.
372.
373.
374.
375.
376.
377.
378.
379.
380.
381.
382.
383.
384.
385.
386.
387.
388.
389.
390.
391.
392.
393.
394.
395.
396.
397.
398.
399.
400.
401.
402.
403.
404.
405.
406.
407.
408.
409.
410.
411.
412.
413.
414.
415.
416.
417.
418.
419.
420.
421.
422.
423.
424.
425.
426.
427.
428.
429.
430.
431.
432.
433.
434.
435.
436.
437.
438.
439.
440.
441.
442.
443.
444.
445.
446.
447.
448.
449.
450.
451.
452.
453.
454.
455.
456.
457.
458.
459.
460.
461.
462.
463.
464.
465.
466.
467.
468.
469.
470.
471.
472.
473.
474.
475.
476.
477.
478.
479.
480.
481.
482.
483.
484.
485.
486.
487.
488.
489.
490.
491.
492.
493.
494.
495.
496.
497.
498.
499.
500.
501.
502.
503.
504.
505.
506.
507.
508.
509.
510.
511.
512.
513.
514.
515.
516.
517.
518.
519.
520.
521.
522.
523.
524.
525.
526.
527.
528.
529.
530.
531.
532.
533.
534.
535.
536.
537.
538.
539.
540.
541.
542.
543.
544.
545.
546.
547.
548.
549.
550.
551.
552.
553.
554.
555.
556.
557.
558.
559.
560.
561.
562.
563.
564.
565.
566.
567.
568.
569.
570.
571.
572.
573.
574.
575.
576.
577.
578.
579.
580.
581.
582.
583.
584.
585.
586.
587.
588.
589.
590.
591.
592.
593.
594.
595.
596.
597.
598.
599.
600.
601.
602.
603.
604.
605.
606.
607.
608.
609.
610.
611.
612.
613.
614.
615.
616.
617.
618.
619.
620.
621.
622.
623.
624.
625.
626.
627.
628.
629.
630.
631.
632.
633.
634.
635.
636.
637.
638.
639.
640.
641.
642.
643.
644.
645.
646.
647.
648.
649.
650.
651.
652.
653.
654.
655.
656.
657.
658.
659.
660.
661.
662.
663.
664.
665.
666.
667.
668.
669.
670.
671.
672.
673.
674.
Option Compare Database
Option Explicit


Private Declare Function CryptAcquireContext Lib  "advapi32.dll"  _
                                             Alias  "CryptAcquireContextA"  _
                                             (phProv As Long, pszContainer As String, _
                                              pszProvider As String, _
                                              ByVal dwProvType As Long, _
                                              ByVal dwFlags As Long) As Long

Private Declare Function CryptCreateHash Lib  "advapi32.dll"  _
                                         (ByVal hProv As Long, _
                                          ByVal Algid As Long, _
                                          ByVal hKey As Long, _
                                          ByVal dwFlags As Long, _
                                          phHash As Long) As Long

Private Declare Function CryptDeriveKey Lib  "advapi32.dll"  _
                                        (ByVal hProv As Long, _
                                         ByVal Algid As Long, _
                                         ByVal hBaseData As Long, _
                                         ByVal dwFlags As Long, _
                                         phKey As Long) As Long

Private Declare Function CryptDestroyHash Lib  "advapi32.dll"  _
                                          (ByVal hHash As Long) As Long

Private Declare Function CryptDestroyKey Lib  "advapi32.dll"  _
                                         (ByVal hKey As Long) As Long

Private Declare Function CryptEncrypt Lib  "advapi32.dll"  _
                                      (ByVal hKey As Long, _
                                       ByVal hHash As Long, _
                                       ByVal Final As Long, _
                                       ByVal dwFlags As Long, _
                                       ByVal pbData As String, _
                                       pdwDataLen As Long, _
                                       ByVal dwBufLen As Long) As Long

Private Declare Function CryptDecrypt Lib  "advapi32.dll"  _
                                      (ByVal hKey As Long, _
                                       ByVal hHash As Long, _
                                       ByVal Final As Long, _
                                       ByVal dwFlags As Long, _
                                       ByVal pbData As String, _
                                       pdwDataLen As Long) As Long

Private Declare Function CryptExportKey Lib  "advapi32.dll"  _
                                        (ByVal hKey As Long, _
                                         ByVal hExpKey As Long, _
                                         ByVal dwBlobType As Long, _
                                         ByVal dwFlags As Long, _
                                         ByVal pbData As String, _
                                         pdwDataLen As Long) As Long

Private Declare Function CryptGenKey Lib  "advapi32.dll"  _
                                     (ByVal hProv As Long, _
                                      ByVal Algid As Long, _
                                      ByVal dwFlags As Long, _
                                      phKey As Long) As Long

Private Declare Function CryptGetProvParam Lib  "advapi32.dll"  _
                                           (ByVal hProv As Long, _
                                            ByVal dwParam As Long, _
                                            pbData As Any, _
                                            pdwDataLen As Long, _
                                            ByVal dwFlags As Long) As Long

Private Declare Function CryptGetUserKey Lib  "advapi32.dll"  _
                                         (ByVal hProv As Long, _
                                          ByVal dwKeySpec As Long, _
                                          phUserKey As Long) As Long

Private Declare Function CryptHashData Lib  "advapi32.dll"  _
                                       (ByVal hHash As Long, _
                                        ByVal pbData As String, _
                                        ByVal dwDataLen As Long, _
                                        ByVal dwFlags As Long) As Long

Private Declare Function CryptReleaseContext Lib  "advapi32.dll"  _
                                             (ByVal hProv As Long, _
                                              ByVal dwFlags As Long) As Long

Private Declare Function CryptSignHash Lib  "advapi32.dll"  _
                                       Alias  "CryptSignHashA"  _
                                       (ByVal hHash As Long, _
                                        ByVal dwKeySpec As Long, _
                                        ByVal sDescription As String, _
                                        ByVal dwFlags As Long, _
                                        ByVal pbSignature As String, _
                                        pdwSigLen As Long) As Long

Private Declare Function CryptVerifySignature Lib  "advapi32.dll"  _
                                              Alias  "CryptVerifySignatureA"  _
                                              (ByVal hHash As Long, _
                                               ByVal pbSignature As String, _
                                               ByVal dwSigLen As Long, _
                                               ByVal hPubKey As Long, _
                                               ByVal sDescription As String, _
                                               ByVal dwFlags As Long) As Long

Private Declare Function GetLastError Lib  "kernel32"  () As Long

Private Declare Function GlobalAlloc Lib  "kernel32"  _
                                     (ByVal wFlags As Long, _
                                      ByVal dwBytes As Long) As Long

Private Declare Function GlobalFree Lib  "kernel32"  _
                                    (ByVal hMem As Long) As Long

Private Declare Function GlobalLock Lib  "kernel32"  _
                                    (ByVal hMem As Long) As Long

Private Declare Function GlobalUnlock Lib  "kernel32"  _
                                      (ByVal hMem As Long) As Long

Private Declare Sub CpyMemValAdrFromRefAdr Lib  "kernel32"  _
                                           Alias  "RtlMoveMemory"  _
                                           (ByVal hpvDest As Any, _
                                            hpvSource As Any, _
                                            ByVal cbCopy As Long)

Private Declare Sub CpyMemRefAdrFromValAdr Lib  "kernel32"  _
                                           Alias  "RtlMoveMemory"  _
                                           (hpvDest As Any, _
                                            ByVal hpvSource As Any, _
                                            ByVal cbCopy As Long)

Private Const GMEM_MOVEABLE = &H2
Private Const GMEM_ZEROINIT = &H40
Private Const GHND = (GMEM_MOVEABLE Or GMEM_ZEROINIT)

Private Const MS_DEF_PROV =  "Microsoft Base"  & _
         " Cryptographic Provider v1.0 "
''Note: Don’t let the v1. 0  in the name fool you as it fooled me. To find the real version, call the CSP’s CryptGetProvParam() function. The CSP name is a unique identifier of the CSP (it’s the key value of a registry call to look up the other pertinent information). If Microsoft changed the name when they changed the version, it wouldn’t be backward compatible with old programs that are looking for the old version in the Registry. Whoops! Someone’s underwear is hanging out in plain sight of the entire world. No serious criticism–I’ve made a few of those mistakes in my day, too
        
Private Const PROV_RSA_FULL =  1 
Private Const CRYPT_NEWKEYSET = &H8
Private Const PP_CONTAINER =  6 
Private Const AT_KEYEXCHANGE =  1 
Private Const AT_SIGNATURE =  2 

Private Const SIMPLEBLOB =  1 

Private Const ALG_CLASS_DATA_ENCRYPT =  24576 
Private Const ALG_CLASS_HASH =  32768 
Private Const ALG_TYPE_ANY =  0 
Private Const ALG_TYPE_BLOCK =  1536 
Private Const ALG_TYPE_STREAM =  2048 
Private Const ALG_SID_RC2 =  2 
Private Const ALG_SID_RC4 =  1 
Private Const ALG_SID_MD5 =  3 

Private Const CALG_MD5 = ((ALG_CLASS_HASH Or ALG_TYPE_ANY) _
                          Or ALG_SID_MD5)
Private Const CALG_RC2 = ((ALG_CLASS_DATA_ENCRYPT _
                           Or ALG_TYPE_BLOCK) _
                          Or ALG_SID_RC2)
Private Const CALG_RC4 = ((ALG_CLASS_DATA_ENCRYPT _
                           Or ALG_TYPE_STREAM) _
                          Or ALG_SID_RC4)

Private Const NTE_NO_KEY           As Long = - 2146893811     '0x8009000DL
Private Const NTE_BAD_SIGNATURE    As Long = -2146893818

Private Const CFB_BUSY = 0
Private Const CFB_READY = 1
Private Const CFB_VALID = 2

Private Const ENCRYPT_ALGORITHM = CALG_RC4
Private Const ENCRYPT_BLOCK_SIZE = 1

Private Const CRYPT_EXPORTABLE = 1

Private sInBuffer                  As String
Private sOutBuffer                 As String
Private sPassword                  As String
Private sSignature                 As String
Private lStatus                    As Long

Public Property Get InBuffer() As String
    InBuffer = sInBuffer
End Property

Public Property Let InBuffer(vNewValue As String)
    sInBuffer = vNewValue
End Property

Public Property Get OutBuffer() As String
    OutBuffer = sOutBuffer
End Property

Public Property Get Signature() As String
    Signature = sSignature
End Property

Public Property Let Signature(vNewValue As String)
    sSignature = vNewValue
End Property

Public Sub Sign()

    Dim sContainer                 As String
    Dim sDescription               As String
    Dim sProvider                  As String
    Dim lHCryptprov                As Long
    Dim lHHash                     As Long
    Dim lResult                    As Long
    Dim lSignatureLen              As Long

    On Error GoTo ErrSign

    lStatus = CFB_BUSY

    sSignature = ""

    sContainer = vbNullChar
    sProvider = MS_DEF_PROV & vbNullChar
    If Not CBool(CryptAcquireContext(lHCryptprov, _
                 ByVal sContainer, _
                 ByVal sProvider, _
                 PROV_RSA_FULL, 0)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptAcquireContext!")
        GoTo ReleaseHandles:
    End If

    If Not CBool(CryptCreateHash(lHCryptprov, _
                 CALG_MD5, 0, 0, lHHash)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptCreateHash!")
        GoTo ReleaseHandles:
    End If

    If Not CBool(CryptHashData(lHHash, sInBuffer, _
                 Len(sInBuffer), 0)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptHashData!")
        GoTo ReleaseHandles:
    End If

    sDescription = vbNullChar
    lResult = CryptSignHash(lHHash, AT_SIGNATURE, _
                            sDescription, 0, sSignature, _
                            lSignatureLen)

    sSignature = String(lSignatureLen, vbNullChar)

    If Not CBool(CryptSignHash(lHHash, AT_SIGNATURE, sDescription, _
                 0, sSignature, lSignatureLen)) Then
        MsgBox ("Error " & CStr(GetLastError()) & _
                " during CryptSignHash")
        GoTo ReleaseHandles:
    End If

ReleaseHandles:
    If lHHash Then lResult = CryptDestroyHash(lHHash)
    If lHCryptprov Then lResult = CryptReleaseContext(lHCryptprov, 0)

    lStatus = CFB_READY

    Exit Sub

ErrSign:
    MsgBox ("ErrSign " & Error$)
    GoTo ReleaseHandles
End Sub

Public Sub Validate()

    Dim bValid                     As Boolean
    Dim sContainer                 As String
    Dim sDescription               As String
    Dim sProvider                  As String
    Dim lDataLen                   As Long
    Dim lDataPoint                 As Long
    Dim lHCryptprov                As Long
    Dim lHHash                     As Long
    Dim lResult                    As Long
    Dim lSignatureLen              As Long
    Dim lHCryptKey                 As Long

    ReDim aByteData(0) As Byte

    On Error GoTo ErrValidate

    lStatus = CFB_BUSY

    bValid = True

    sContainer = vbNullChar
    sProvider = MS_DEF_PROV & vbNullChar
    If Not CBool(CryptAcquireContext(lHCryptprov, _
                 ByVal sContainer, ByVal sProvider, _
                 PROV_RSA_FULL, 0)) Then
        bValid = False
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptAcquireContext!")
        GoTo ReleaseHandles:
    End If

    If Not CBool(CryptCreateHash(lHCryptprov, _
                 CALG_MD5, 0, 0, lHHash)) Then
        bValid = False
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptCreateHash!")
        GoTo ReleaseHandles:
    End If

    If Not CBool(CryptHashData(lHHash, sInBuffer, _
                 Len(sInBuffer), 0)) Then
        bValid = False
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptHashData!")
        GoTo ReleaseHandles:
    End If

    If Not CBool(CryptGetUserKey(lHCryptprov, _
                 AT_SIGNATURE, lHCryptKey)) Then
        bValid = False
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptGetUserKey!")
        GoTo ReleaseHandles:
    End If

    lSignatureLen = Len(sSignature)

    If Not CBool(CryptVerifySignature(lHHash, sSignature, _
                 lSignatureLen, lHCryptKey, _
                 sDescription, 0)) Then

        If GetLastError = NTE_BAD_SIGNATURE Then
            bValid = False
            GoTo ReleaseHandles:
        Else
            bValid = False
            MsgBox ("Error " & CStr(GetLastError) & _
                    " during CryptVerifySignature!")
            GoTo ReleaseHandles:
        End If

    End If

ReleaseHandles:
    If lHCryptKey Then lResult = CryptDestroyKey(lHCryptKey)
    If lHHash Then lResult = CryptDestroyHash(lHHash)
    If lHCryptprov Then lResult = CryptReleaseContext(lHCryptprov, 0)

    Select Case bValid
        Case True
            lStatus = CFB_VALID
        Case Else
            lStatus = CFB_READY
    End Select

    Exit Sub

ErrValidate:
    MsgBox ("ErrValidate " & Error$)
    Resume

End Sub

Public Sub Encrypt()

    Dim lHExchgKey                 As Long
    Dim lHCryptprov                As Long
    Dim lHHash                     As Long
    Dim lHkey                      As Long
    Dim lResult                    As Long
    Dim sContainer                 As String
    Dim sProvider                  As String
    Dim sCryptBuffer               As String
    Dim lCryptLength               As Long
    Dim lCryptBufLen               As Long

    On Error GoTo ErrEncrypt

    lStatus = CFB_BUSY

    sContainer = vbNullChar
    sProvider = vbNullChar
    sProvider = MS_DEF_PROV & vbNullChar
    If Not CBool(CryptAcquireContext(lHCryptprov, _
                 ByVal sContainer, _
                 ByVal sProvider, _
                 PROV_RSA_FULL, 0)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptAcquireContext!")
        GoTo Done
    End If

    If Not CBool(CryptCreateHash(lHCryptprov, _
                 CALG_MD5, 0, 0, lHHash)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptCreateHash!")
        GoTo Done
    End If

    If Not CBool(CryptHashData(lHHash, sPassword, _
                 Len(sPassword), 0)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptHashData!")
        GoTo Done
    End If

    If Not CBool(CryptDeriveKey(lHCryptprov, _
                 ENCRYPT_ALGORITHM, _
                 lHHash, 0, lHkey)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptDeriveKey!")
        GoTo Done
    End If

    CryptDestroyHash (lHHash)
    lHHash = 0

    lCryptLength = Len(sInBuffer)
    lCryptBufLen = lCryptLength * 2
    sCryptBuffer = String(lCryptBufLen, vbNullChar)
    LSet sCryptBuffer = sInBuffer

    If Not CBool(CryptEncrypt(lHkey, 0, 1, 0, _
                 sCryptBuffer, lCryptLength, _
                 lCryptBufLen)) Then
        MsgBox ("bytes required:" & CStr(lCryptLength))
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptEncrypt!")
    End If

    sOutBuffer = Mid$(sCryptBuffer, 1, lCryptLength)

Done:

    If (lHkey) Then lResult = CryptDestroyKey(lHkey)

    If lHExchgKey Then CryptDestroyKey (lHExchgKey)

    If lHHash Then CryptDestroyHash (lHHash)

    If lHCryptprov Then lResult = CryptReleaseContext(lHCryptprov, 0)

    lStatus = CFB_READY

    Exit Sub

ErrEncrypt:

    MsgBox ("ErrEncrypt " & Error$)
    Resume

End Sub

Public Sub Decrypt()

    Dim lHExchgKey                 As Long
    Dim lHCryptprov                As Long
    Dim lHHash                     As Long
    Dim lHkey                      As Long
    Dim lResult                    As Long
    Dim sContainer                 As String
    Dim sProvider                  As String
    Dim sCryptBuffer               As String
    Dim lCryptBufLen               As Long
    Dim lCryptPoint                As Long
    Dim lPasswordPoint             As Long
    Dim lPasswordCount             As Long

    On Error GoTo ErrDecrypt

    lStatus = CFB_BUSY

    sOutBuffer = ""

    sContainer = vbNullChar
    sProvider = vbNullChar
    sProvider = MS_DEF_PROV & vbNullChar
    If Not CBool(CryptAcquireContext(lHCryptprov, _
                 ByVal sContainer, _
                 ByVal sProvider, _
                 PROV_RSA_FULL, 0)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptAcquireContext!")
        GoTo Done
    End If

    If Not CBool(CryptCreateHash(lHCryptprov, _
                 CALG_MD5, 0, 0, lHHash)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptCreateHash!")
        GoTo Done
    End If

    If Not CBool(CryptHashData(lHHash, sPassword, _
                 Len(sPassword), 0)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptHashData!")
        GoTo Done
    End If

    If Not CBool(CryptDeriveKey(lHCryptprov, _
                 ENCRYPT_ALGORITHM, _
                 lHHash, 0, lHkey)) Then
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptDeriveKey!")
        GoTo Done
    End If

    CryptDestroyHash (lHHash)
    lHHash = 0

    lCryptBufLen = Len(sInBuffer) * 2
    sCryptBuffer = String(lCryptBufLen, vbNullChar)
    LSet sCryptBuffer = sInBuffer

    If Not CBool(CryptDecrypt(lHkey, 0, 1, 0, _
                 sCryptBuffer, lCryptBufLen)) Then
        MsgBox ("bytes required:" & CStr(lCryptBufLen))
        MsgBox ("Error " & CStr(GetLastError) & _
                " during CryptDecrypt!")
        GoTo Done
    End If

    sOutBuffer = Mid$(sCryptBuffer, 1, Len(sInBuffer))

Done:

    If (lHkey) Then lResult = CryptDestroyKey(lHkey)

    If lHExchgKey Then CryptDestroyKey (lHExchgKey)

    If lHHash Then CryptDestroyHash (lHHash)

    If lHCryptprov Then lResult = CryptReleaseContext(lHCryptprov, 0)

    lStatus = CFB_READY

    Exit Sub

ErrDecrypt:
    MsgBox ("ErrDecrypt " & Error$)
    GoTo Done

End Sub

Public Property Get Status() As Long
    Status = lStatus
End Property

Private Function InitUser() As Long
    Dim lHCryptprov                As Long
    Dim lHCryptKey                 As Long
    Dim avProviderData(1000)       As Byte
    Dim lProviderDataAddress       As Long
    Dim lProviderDataLen           As Long
    Dim lDataSize                  As Long
    Dim lResult                    As Long
    Dim sContainer                 As String
    Dim sProvider                  As String
    Dim sUserName                  As String
    Dim lPoint                     As Long
    Dim lMemHandle                 As Long
    Dim lReturn                    As Long
    Dim sBuffer                    As String

    On Error GoTo ErrInitUser

    sContainer = vbNullChar
    sProvider = MS_DEF_PROV & vbNullChar

    If Not CBool(CryptAcquireContext(lHCryptprov, _
                 ByVal sContainer, _
                 ByVal sProvider, PROV_RSA_FULL, 0)) Then

        If Not CBool(CryptAcquireContext(lHCryptprov, _
                     ByVal sContainer, _
                     ByVal sProvider, _
                     PROV_RSA_FULL, _
                     CRYPT_NEWKEYSET)) Then
            MsgBox ("Error creating key container! " & _
                    CStr(GetLastError))
            Exit Function
        End If

        lProviderDataLen = Len(avProviderData(0)) * _
                           (UBound(avProviderData) + 1)
        If Not CBool(CryptGetProvParam(lHCryptprov, _
                     PP_CONTAINER, avProviderData(0), _
                     lProviderDataLen, 0)) Then
            MsgBox ("Error getting user name! " & CStr(GetLastError))
            avProviderData(0) = 0
        End If

        lPoint = LBound(avProviderData)
        While lPoint <= UBound(avProviderData)
            If avProviderData(lPoint) <> 0 Then
                sUserName = sUserName & Chr$(avProviderData(lPoint))
            Else
                lPoint = UBound(avProviderData)
            End If
            lPoint = lPoint + 1
        Wend

        MsgBox ("Create key container " & sUserName)

    End If

    If Not CBool(CryptGetUserKey(lHCryptprov, _
                 AT_SIGNATURE, _
                 lHCryptKey)) Then
        If GetLastError = NTE_NO_KEY Then
            MsgBox ("Create key exchange key pair")
            If Not CBool(CryptGenKey(lHCryptprov, _
                         AT_SIGNATURE, 0, _
                         lHCryptKey)) Then
                MsgBox ("Error during CryptGenKey! " & _
                        CStr(GetLastError))
                Exit Function
            Else
                lResult = CryptDestroyKey(lHCryptprov)
            End If
        Else
            MsgBox ("Error during CryptGetUserKey! " & _
                    CStr(GetLastError))
            Exit Function
        End If
    End If

    If Not CBool(CryptGetUserKey(lHCryptprov, _
                 AT_KEYEXCHANGE, lHCryptKey)) Then
        If GetLastError = NTE_NO_KEY Then
            MsgBox ("Create key exchange key pair")
            If Not CBool(CryptGenKey(lHCryptprov, _
                         AT_KEYEXCHANGE, 0, lHCryptKey)) Then
                MsgBox ("Error during CryptGenKey! " & _
                        CStr(GetLastError))
                Exit Function
            Else
                lResult = CryptDestroyKey(lHCryptprov)
            End If
        Else
            MsgBox ("Error during CryptGetUserKey! " & _
                    CStr(GetLastError))
            Exit Function
        End If
    End If

    lResult = CryptReleaseContext(lHCryptprov, 0)
    InitUser = True

    Exit Function

ErrInitUser:
    MsgBox ("ErrInitUser " & Error$)
    Resume

End Function

Private Sub Class_Initialize()
    If InitUser = True Then
        '        MsgBox ( "InitUser OK" )
    Else
        MsgBox ( "InitUser failed. " )
    End If
End Sub

Public Property Get Password() As String
    Password = sPassword
End Property

Public Property Let Password(vNewValue As String)
    sPassword = vNewValue
End Property


Вызов

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
    Dim t                          As New clsCryptoAPI
    '**************шифруем
    t.Password = "твой пароль"
    t.InBuffer = "твой текст"
    t.Encrypt
    Debug.Print t.OutBuffer ' зашифрованное сообщение

    '**************расшифровка

t.Password = "твой пароль"
    t.InBuffer = "зашифрованное сообщение"
    t.Decrypt
     Debug.Print t.OutBuffer ' расшифрованное сообщение
...
Рейтинг: 0 / 0
Алгоритмы несиметричного шифрования помогите найти
    #32198615
-=Alexey=-
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Недавно же\r
вопрос поднимали\r
\r
А что Виндоус может предложить из стандартных своих библиотек по шифрованию? \r
\r
CryptoAPI, COM для VB - CAPICOM \r
соостветсвующий класс в net\r
------------------\r
пример:\r
Код: plaintext
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.
Sub EncryptMessage(ByVal TobeEncrypted As String, ByVal hidden As String, ByVal filename As String)\r
On Error GoTo ErrorHandler\r
Dim message As New EncryptedData\r
Dim encryptedmessage As String\r
  message.Content = TobeEncrypted\r
  message.SetSecret hidden\r
  message.Algorithm.Name = CAPICOM_ENCRYPTION_ALGORITHM_3DES\r
  encryptedmessage = message.Encrypt\r
\r
  If Len(encryptedmessage) <  1  Then\r
    MsgBox  "no message encrypted. " \r
  Else\r
    MsgBox  " Message is "  & Len(encryptedmessage) &  " characters" \r
    Open filename For Output As # 1 \r
    Write # 1 , encryptedmessage\r
    Close # 1 \r
    MsgBox  "Encrypted message written to file " \r
  End If\r
  Set message = Nothing\r
  Exit Sub\r
\r
ErrorHandler:\r
  If Err.Number >  0  Then\r
    MsgBox  "VB Error found:"  & Err.Description\r
  Else\r
    MsgBox  "CAPICOM error found : "  & Err.Number\r
  End If\r
End Sub\r
\r
Sub DecryptMessage(ByVal hidden As String, ByVal filename As String)\r
On Error GoTo ErrorHandler\r
Dim message As New EncryptedData\r
Dim encrypted As String\r
\r
  Open filename For Input As # 1 \r
  Input # 1 , encrypted\r
  Close # 1 \r
  \r
  If Len(encrypted) >  0  Then\r
    message.SetSecret hidden\r
    message.Decrypt encrypted\r
    MsgBox message.Content\r
  Else\r
    MsgBox  "No encrypted message was read in." \r
  End If\r
\r
  Set message = Nothing\r
  Exit Sub\r
\r
ErrorHandler:\r
  If Err.Number >  0  Then\r
      MsgBox  "VB Error found:"  & Err.Description\r
  Else\r
    If Err.Number = - 2146893819  Then\r
      MsgBox  "Error. The password may not be correct." \r
    Else\r
      MsgBox  "CAPICOM error found : "  & Err.Number\r
    End If\r
  End If\r
End Sub\r
\r
\'пример вызова\r
EncryptMessage  "Жили были три ежа и четыре черепахи" ,  "hQk8_091mnX]z" ,  "c:\\1 .txt"\r
DecryptMessage  "hQk8_091mnX]z" , "c:\\1 .txt"\r
\r
1.txt:\r
"MIGUBgkrBgEEAYI3WAOggYYwgYMGCisGAQQBgjdYAwGgdTBzAgMCAAACAmYDAgIA\r
wAQIRHwpYrKLAfQEENNEveCb2rR0tCTFRd37QbwESPp1h88aEoOUXJhQmIWWkA+o\r
emz8MeF4PtC5HQKTV789rLbVvpEfpas8Z9A83NyxfyI+pQWJ8zct2oHSqrvjmk2X\r
/eaL8yvtYQ==\r
"\r
Возможные алгоритмы:\r
CAPICOM_ENCRYPTION_ALGORITHM_RC2 \r
Use RSA RC2 encryption. \r
CAPICOM_ENCRYPTION_ALGORITHM_RC4 \r
Use RSA RC4 encryption. \r
CAPICOM_ENCRYPTION_ALGORITHM_DES \r
Use DES encryption. \r
CAPICOM_ENCRYPTION_ALGORITHM_3DES \r
Use triple DES encryption. \r
CAPICOM_ENCRYPTION_ALGORITHM_AES\r
\r
для работы нужна ссылка на библиотеку CAPICOM. Ее описание и примеры можно взять здесь \r
\r
PS. CAPICOM работает значительно медленее чем CryptoAPI
...
Рейтинг: 0 / 0
17 сообщений из 17, страница 1 из 1
Форумы / Microsoft Access [игнор отключен] [закрыт для гостей] / Алгоритмы несиметричного шифрования помогите найти
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]