]> git.saurik.com Git - apt.git/blob - apt-pkg/contrib/sha2.cc
dcdbef6e757a7877c7b00652ec10b86b77be8a03
[apt.git] / apt-pkg / contrib / sha2.cc
1 /*
2 * Cryptographic API. {{{
3 *
4 * SHA-512, as specified in
5 * http://csrc.nist.gov/cryptval/shs/sha256-384-512.pdf
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the Free
9 * Software Foundation; either version 2 of the License, or (at your option)
10 * any later version.
11 *
12 */ /*}}}*/
13
14 #ifdef __GNUG__
15 #pragma implementation "apt-pkg/sha2.h"
16 #endif
17
18 #include <apt-pkg/sha2.h>
19 #include <apt-pkg/strutl.h>
20
21
22
23
24 SHA512Summation::SHA512Summation() /*{{{*/
25 {
26 SHA512_Init(&ctx);
27 Done = false;
28 }
29 /*}}}*/
30
31 SHA512SumValue SHA512Summation::Result() /*{{{*/
32 {
33 if (!Done) {
34 SHA512_Final(Sum, &ctx);
35 Done = true;
36 }
37
38 SHA512SumValue res;
39 res.Set(Sum);
40 return res;
41 }
42 /*}}}*/
43 bool SHA512Summation::Add(const unsigned char *inbuf,unsigned long len) /*{{{*/
44 {
45 if (Done)
46 return false;
47 SHA512_Update(&ctx, inbuf, len);
48 return true;
49 }
50 /*}}}*/
51 // SHA512Summation::AddFD - Add content of file into the checksum /*{{{*/
52 // ---------------------------------------------------------------------
53 /* */
54 bool SHA512Summation::AddFD(int Fd,unsigned long Size)
55 {
56 unsigned char Buf[64 * 64];
57 int Res = 0;
58 int ToEOF = (Size == 0);
59 while (Size != 0 || ToEOF)
60 {
61 unsigned n = sizeof(Buf);
62 if (!ToEOF) n = min(Size,(unsigned long)n);
63 Res = read(Fd,Buf,n);
64 if (Res < 0 || (!ToEOF && (unsigned) Res != n)) // error, or short read
65 return false;
66 if (ToEOF && Res == 0) // EOF
67 break;
68 Size -= Res;
69 Add(Buf,Res);
70 }
71 return true;
72 }
73 /*}}}*/
74
75 SHA256Summation::SHA256Summation() /*{{{*/
76 {
77 SHA256_Init(&ctx);
78 Done = false;
79 }
80 /*}}}*/
81 bool SHA256Summation::Add(const unsigned char *inbuf,unsigned long len) /*{{{*/
82 {
83 if (Done)
84 return false;
85 SHA256_Update(&ctx, inbuf, len);
86 return true;
87 }
88 /*}}}*/
89 SHA256SumValue SHA256Summation::Result() /*{{{*/
90 {
91 if (!Done) {
92 SHA256_Final(Sum, &ctx);
93 Done = true;
94 }
95
96 SHA256SumValue res;
97 res.Set(Sum);
98 return res;
99 }
100 /*}}}*/
101 // SHA256Summation::AddFD - Add content of file into the checksum /*{{{*/
102 // ---------------------------------------------------------------------
103 /* */
104 bool SHA256Summation::AddFD(int Fd,unsigned long Size)
105 {
106 unsigned char Buf[64 * 64];
107 int Res = 0;
108 int ToEOF = (Size == 0);
109 while (Size != 0 || ToEOF)
110 {
111 unsigned n = sizeof(Buf);
112 if (!ToEOF) n = min(Size,(unsigned long)n);
113 Res = read(Fd,Buf,n);
114 if (Res < 0 || (!ToEOF && (unsigned) Res != n)) // error, or short read
115 return false;
116 if (ToEOF && Res == 0) // EOF
117 break;
118 Size -= Res;
119 Add(Buf,Res);
120 }
121 return true;
122 }
123 /*}}}*/
124