Produced by Araxis Merge on 9/25/2018 2:13:10 PM Central Daylight Time. See www.araxis.com for information about Merge. This report uses XHTML and CSS2, and is best viewed with a modern standards-compliant browser. For optimum results when printing this report, use landscape orientation and enable printing of background images and colours in your browser.
# | Location | File | Last Modified |
---|---|---|---|
1 | build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\javax\crypto | Cipher.java | Mon Jan 22 14:46:52 2018 UTC |
2 | build 3.zip\build 3\MHLTH_YS_137_Source\JavaScript\resources\javaJDF-1.8.0\src\javax\crypto | Cipher.java | Wed Sep 12 17:18:25 2018 UTC |
Description | Between Files 1 and 2 |
|
---|---|---|
Text Blocks | Lines | |
Unchanged | 2 | 5522 |
Changed | 1 | 2 |
Inserted | 0 | 0 |
Removed | 0 | 0 |
Whitespace | |
---|---|
Character case | Differences in character case are significant |
Line endings | Differences in line endings (CR and LF characters) are ignored |
CR/LF characters | Not shown in the comparison detail |
No regular expressions were active.
1 | /* | |
2 | * Copyrig ht (c) 199 7, 2014, O racle and/ or its aff iliates. A ll rights reserved. | |
3 | * DO NOT ALTER OR R EMOVE COPY RIGHT NOTI CES OR THI S FILE HEA DER. | |
4 | * | |
5 | * This co de is free software; you can r edistribut e it and/o r modify i t | |
6 | * under t he terms o f the GNU General Pu blic Licen se version 2 only, a s | |
7 | * publish ed by the Free Softw are Founda tion. Ora cle design ates this | |
8 | * particu lar file a s subject to the "Cl asspath" e xception a s provided | |
9 | * by Orac le in the LICENSE fi le that ac companied this code. | |
10 | * | |
11 | * This co de is dist ributed in the hope that it wi ll be usef ul, but WI THOUT | |
12 | * ANY WAR RANTY; wit hout even the implie d warranty of MERCHA NTABILITY or | |
13 | * FITNESS FOR A PAR TICULAR PU RPOSE. Se e the GNU General Pu blic Licen se | |
14 | * version 2 for mor e details (a copy is included in the LIC ENSE file that | |
15 | * accompa nied this code). | |
16 | * | |
17 | * You sho uld have r eceived a copy of th e GNU Gene ral Public License v ersion | |
18 | * 2 along with this work; if not, write to the Fr ee Softwar e Foundati on, | |
19 | * Inc., 5 1 Franklin St, Fifth Floor, Bo ston, MA 0 2110-1301 USA. | |
20 | * | |
21 | * Please contact Or acle, 500 Oracle Par kway, Redw ood Shores , CA 94065 USA | |
22 | * or visi t www.orac le.com if you need a dditional informatio n or have any | |
23 | * questio ns. | |
24 | */ | |
25 | ||
26 | package ja vax.crypto ; | |
27 | ||
28 | import jav a.util.*; | |
29 | import jav a.util.con current.Co ncurrentHa shMap; | |
30 | import jav a.util.con current.Co ncurrentMa p; | |
31 | import jav a.util.reg ex.*; | |
32 | ||
33 | ||
34 | import jav a.security .*; | |
35 | import jav a.security .Provider. Service; | |
36 | import jav a.security .spec.Algo rithmParam eterSpec; | |
37 | import jav a.security .spec.Inva lidParamet erSpecExce ption; | |
38 | import jav a.security .cert.Cert ificate; | |
39 | import jav a.security .cert.X509 Certificat e; | |
40 | ||
41 | import jav ax.crypto. spec.*; | |
42 | ||
43 | import jav a.nio.Byte Buffer; | |
44 | import jav a.nio.Read OnlyBuffer Exception; | |
45 | ||
46 | import sun .security. util.Debug ; | |
47 | import sun .security. jca.*; | |
48 | ||
49 | /** | |
50 | * This cl ass provid es the fun ctionality of a cryp tographic cipher for | |
51 | * encrypt ion and de cryption. It forms t he core of the Java Cryptograp hic | |
52 | * Extensi on (JCE) f ramework. | |
53 | * | |
54 | * <p>In o rder to cr eate a Cip her object , the appl ication ca lls the | |
55 | * Cipher' s <code>ge tInstance< /code> met hod, and p asses the name of th e | |
56 | * request ed <i>tran sformation </i> to it . Optional ly, the na me of a pr ovider | |
57 | * may be specified. | |
58 | * | |
59 | * <p>A <i >transform ation</i> is a strin g that des cribes the operation (or | |
60 | * set of operations ) to be pe rformed on the given input, to produce s ome | |
61 | * output. A transfo rmation al ways inclu des the na me of a cr yptographi c | |
62 | * algorit hm (e.g., <i>DES</i> ), and may be follow ed by a fe edback mod e and | |
63 | * padding scheme. | |
64 | * | |
65 | * <p> A t ransformat ion is of the form: | |
66 | * | |
67 | * <ul> | |
68 | * <li>"<i >algorithm /mode/padd ing</i>" o r | |
69 | * | |
70 | * <li>"<i >algorithm </i>" | |
71 | * </ul> | |
72 | * | |
73 | * <P> (in the latte r case, | |
74 | * provide r-specific default v alues for the mode a nd padding scheme ar e used). | |
75 | * For exa mple, the following is a valid transform ation: | |
76 | * | |
77 | * <pre> | |
78 | * Cip her c = Ci pher.getIn stance("<i >DES/CBC/P KCS5Paddin g</i>"); | |
79 | * </pre> | |
80 | * | |
81 | * Using m odes such as <code>C FB</code> and <code> OFB</code> , block | |
82 | * ciphers can encry pt data in units sma ller than the cipher 's actual | |
83 | * block s ize. When requestin g such a m ode, you m ay optiona lly specif y | |
84 | * the num ber of bit s to be pr ocessed at a time by appending this numb er | |
85 | * to the mode name as shown i n the "<co de>DES/CFB 8/NoPaddin g</code>" and | |
86 | * "<code> DES/OFB32/ PKCS5Paddi ng</code>" transform ations. If no such | |
87 | * number is specifi ed, a prov ider-speci fic defaul t is used. (For | |
88 | * example , the SunJ CE provide r uses a d efault of 64 bits fo r DES.) | |
89 | * Thus, b lock ciphe rs can be turned int o byte-ori ented stre am ciphers by | |
90 | * using a n 8 bit mo de such as CFB8 or O FB8. | |
91 | * <p> | |
92 | * Modes s uch as Aut henticated Encryptio n with Ass ociated Da ta (AEAD) | |
93 | * provide authentic ity assura nces for b oth confid ential dat a and | |
94 | * Additio nal Associ ated Data (AAD) that is not en crypted. (Please se e | |
95 | * <a href ="http://w ww.ietf.or g/rfc/rfc5 116.txt"> RFC 5116 < /a> for mo re | |
96 | * informa tion on AE AD and AEA D algorith ms such as GCM/CCM.) Both | |
97 | * confide ntial and AAD data c an be used when calc ulating th e | |
98 | * authent ication ta g (similar to a {@li nk Mac}). This tag is appende d | |
99 | * to the ciphertext during en cryption, and is ver ified on d ecryption. | |
100 | * <p> | |
101 | * AEAD mo des such a s GCM/CCM perform al l AAD auth enticity c alculation s | |
102 | * before starting t he ciphert ext authen ticity cal culations. To avoid | |
103 | * impleme ntations h aving to i nternally buffer cip hertext, a ll AAD dat a | |
104 | * must be supplied to GCM/CCM implement ations (vi a the {@co de | |
105 | * updateA AD} method s) <b>befo re</b> the ciphertex t is proce ssed (via | |
106 | * the {@c ode update } and {@co de doFinal } methods) . | |
107 | * <p> | |
108 | * Note th at GCM mod e has a un iqueness r equirement on IVs us ed in | |
109 | * encrypt ion with a given key . When IVs are repea ted for GC M | |
110 | * encrypt ion, such usages are subject t o forgery attacks. T hus, after | |
111 | * each en cryption o peration u sing GCM m ode, calle rs should re-initial ize | |
112 | * the cip her object s with GCM parameter s which ha s a differ ent IV val ue. | |
113 | * <pre> | |
114 | * GCM ParameterS pec s = .. .; | |
115 | * cip her.init(. .., s); | |
116 | * | |
117 | * // If the GCM parameter s were gen erated by the provid er, it can | |
118 | * // be retriev ed by: | |
119 | * // cipher.get Parameters ().getPara meterSpec( GCMParamet erSpec.cla ss); | |
120 | * | |
121 | * cip her.update AAD(...); // AAD | |
122 | * cip her.update (...); // Multi- part updat e | |
123 | * cip her.doFina l(...); // conclu sion of op eration | |
124 | * | |
125 | * // Use a diff erent IV v alue for e very encry ption | |
126 | * byt e[] newIv = ...; | |
127 | * s = new GCMPa rameterSpe c(s.getTLe n(), newIv ); | |
128 | * cip her.init(. .., s); | |
129 | * ... | |
130 | * | |
131 | * </pre> | |
132 | * Every i mplementat ion of the Java plat form is re quired to support | |
133 | * the fol lowing sta ndard <cod e>Cipher</ code> tran sformation s with the keysizes | |
134 | * in pare ntheses: | |
135 | * <ul> | |
136 | * <li><tt >AES/CBC/N oPadding</ tt> (128)< /li> | |
137 | * <li><tt >AES/CBC/P KCS5Paddin g</tt> (12 8)</li> | |
138 | * <li><tt >AES/ECB/N oPadding</ tt> (128)< /li> | |
139 | * <li><tt >AES/ECB/P KCS5Paddin g</tt> (12 8)</li> | |
140 | * <li><tt >DES/CBC/N oPadding</ tt> (56)</ li> | |
141 | * <li><tt >DES/CBC/P KCS5Paddin g</tt> (56 )</li> | |
142 | * <li><tt >DES/ECB/N oPadding</ tt> (56)</ li> | |
143 | * <li><tt >DES/ECB/P KCS5Paddin g</tt> (56 )</li> | |
144 | * <li><tt >DESede/CB C/NoPaddin g</tt> (16 8)</li> | |
145 | * <li><tt >DESede/CB C/PKCS5Pad ding</tt> (168)</li> | |
146 | * <li><tt >DESede/EC B/NoPaddin g</tt> (16 8)</li> | |
147 | * <li><tt >DESede/EC B/PKCS5Pad ding</tt> (168)</li> | |
148 | * <li><tt >RSA/ECB/P KCS1Paddin g</tt> (10 24, 2048)< /li> | |
149 | * <li><tt >RSA/ECB/O AEPWithSHA -1AndMGF1P adding</tt > (1024, 2 048)</li> | |
150 | * <li><tt >RSA/ECB/O AEPWithSHA -256AndMGF 1Padding</ tt> (1024, 2048)</li > | |
151 | * </ul> | |
152 | * These t ransformat ions are d escribed i n the | |
153 | * <a href ="{@docRoo t}/../tech notes/guid es/securit y/Standard Names.html #Cipher"> | |
154 | * Cipher section</a > of the | |
155 | * Java Cr yptography Architect ure Standa rd Algorit hm Name Do cumentatio n. | |
156 | * Consult the relea se documen tation for your impl ementation to see if any | |
157 | * other t ransformat ions are s upported. | |
158 | * | |
159 | * @author Jan Luehe | |
160 | * @see Ke yGenerator | |
161 | * @see Se cretKey | |
162 | * @since 1.4 | |
163 | */ | |
164 | ||
165 | public cla ss Cipher { | |
166 | ||
167 | privat e static f inal Debug debug = | |
168 | Debug. getInstanc e("jca", " Cipher"); | |
169 | ||
170 | privat e static f inal Debug pdebug = | |
171 | Debug. getInstanc e("provide r", "Provi der"); | |
172 | privat e static f inal boole an skipDeb ug = | |
173 | De bug.isOn(" engine=") && !Debug. isOn("ciph er"); | |
174 | ||
175 | /** | |
176 | * Con stant used to initia lize ciphe r to encry ption mode . | |
177 | */ | |
178 | public static fi nal int EN CRYPT_MODE = 1; | |
179 | ||
180 | /** | |
181 | * Con stant used to initia lize ciphe r to decry ption mode . | |
182 | */ | |
183 | public static fi nal int DE CRYPT_MODE = 2; | |
184 | ||
185 | /** | |
186 | * Con stant used to initia lize ciphe r to key-w rapping mo de. | |
187 | */ | |
188 | public static fi nal int WR AP_MODE = 3; | |
189 | ||
190 | /** | |
191 | * Con stant used to initia lize ciphe r to key-u nwrapping mode. | |
192 | */ | |
193 | public static fi nal int UN WRAP_MODE = 4; | |
194 | ||
195 | /** | |
196 | * Con stant used to indica te the to- be-unwrapp ed key is a "public key". | |
197 | */ | |
198 | public static fi nal int PU BLIC_KEY = 1; | |
199 | ||
200 | /** | |
201 | * Con stant used to indica te the to- be-unwrapp ed key is a "private key". | |
202 | */ | |
203 | public static fi nal int PR IVATE_KEY = 2; | |
204 | ||
205 | /** | |
206 | * Constant used to i ndicate th e to-be-un wrapped ke y is a " PW key". | |
207 | */ | |
208 | public static fi nal int SE CRET_KEY = 3; | |
209 | ||
210 | // The provider | |
211 | privat e Provider provider; | |
212 | ||
213 | // The provider implementa tion (dele gate) | |
214 | privat e CipherSp i spi; | |
215 | ||
216 | // The transform ation | |
217 | privat e String t ransformat ion; | |
218 | ||
219 | // Cry pto permis sion repre senting th e maximum allowable cryptograp hic | |
220 | // str ength that this Ciph er object can be use d for. (Th e cryptogr aphic | |
221 | // str ength is a function of the key size and a lgorithm p arameters encoded | |
222 | // in the crypto permissio n.) | |
223 | privat e CryptoPe rmission c ryptoPerm; | |
224 | ||
225 | // The exemption mechanism that need s to be en forced | |
226 | privat e Exemptio nMechanism exmech; | |
227 | ||
228 | // Fla g which in dicates wh ether or n ot this ci pher has b een initia lized | |
229 | privat e boolean initialize d = false; | |
230 | ||
231 | // The operation mode - st ore the op eration mo de after t he | |
232 | // cip her has be en initial ized. | |
233 | privat e int opmo de = 0; | |
234 | ||
235 | // The OID for t he KeyUsag e extensio n in an X. 509 v3 cer tificate | |
236 | privat e static f inal Strin g KEY_USAG E_EXTENSIO N_OID = "2 .5.29.15"; | |
237 | ||
238 | // nex t SPI to try in pro vider sele ction | |
239 | // nul l once pro vider is s elected | |
240 | privat e CipherSp i firstSpi ; | |
241 | ||
242 | // nex t service to try in provider s election | |
243 | // nul l once pro vider is s elected | |
244 | privat e Service firstServi ce; | |
245 | ||
246 | // rem aining ser vices to t ry in prov ider selec tion | |
247 | // nul l once pro vider is s elected | |
248 | privat e Iterator <Service> serviceIte rator; | |
249 | ||
250 | // lis t of trans form Strin gs to look up in the provider | |
251 | privat e List<Tra nsform> tr ansforms; | |
252 | ||
253 | privat e final Ob ject lock; | |
254 | ||
255 | /** | |
256 | * Cre ates a Cip her object . | |
257 | * | |
258 | * @pa ram cipher Spi the de legate | |
259 | * @pa ram provid er the pro vider | |
260 | * @pa ram transf ormation t he transfo rmation | |
261 | */ | |
262 | protec ted Cipher (CipherSpi cipherSpi , | |
263 | Provider provider, | |
264 | String tr ansformati on) { | |
265 | // See bug 4 341369 & 4 334690 for more info . | |
266 | // If the ca ller is tr usted, the n okey. | |
267 | // Otherwise throw a N ullPointer Exception. | |
268 | if (!JceSecu rityManage r.INSTANCE .isCallerT rusted()) { | |
269 | throw ne w NullPoin terExcepti on(); | |
270 | } | |
271 | th is.spi = c ipherSpi; | |
272 | th is.provide r = provid er; | |
273 | th is.transfo rmation = transforma tion; | |
274 | th is.cryptoP erm = Cryp toAllPermi ssion.INST ANCE; | |
275 | th is.lock = null; | |
276 | } | |
277 | ||
278 | /** | |
279 | * Cre ates a Cip her object . Called i nternally and by Nul lCipher. | |
280 | * | |
281 | * @pa ram cipher Spi the de legate | |
282 | * @pa ram transf ormation t he transfo rmation | |
283 | */ | |
284 | Cipher (CipherSpi cipherSpi , String t ransformat ion) { | |
285 | th is.spi = c ipherSpi; | |
286 | th is.transfo rmation = transforma tion; | |
287 | th is.cryptoP erm = Cryp toAllPermi ssion.INST ANCE; | |
288 | th is.lock = null; | |
289 | } | |
290 | ||
291 | privat e Cipher(C ipherSpi f irstSpi, S ervice fir stService, | |
292 | Iterator <Service> serviceIte rator, Str ing transf ormation, | |
293 | List<Tra nsform> tr ansforms) { | |
294 | th is.firstSp i = firstS pi; | |
295 | th is.firstSe rvice = fi rstService ; | |
296 | th is.service Iterator = serviceIt erator; | |
297 | th is.transfo rms = tran sforms; | |
298 | th is.transfo rmation = transforma tion; | |
299 | th is.lock = new Object (); | |
300 | } | |
301 | ||
302 | privat e static S tring[] to kenizeTran sformation (String tr ansformati on) | |
303 | throws N oSuchAlgor ithmExcept ion { | |
304 | if (transfor mation == null) { | |
305 | throw ne w NoSuchAl gorithmExc eption("No transform ation give n"); | |
306 | } | |
307 | /* | |
308 | * array con taining th e componen ts of a Ci pher trans formation: | |
309 | * | |
310 | * index 0: algorithm component (e.g., DES ) | |
311 | * index 1: feedback c omponent ( e.g., CFB) | |
312 | * index 2: padding co mponent (e .g., PKCS5 Padding) | |
313 | * / | |
314 | St ring[] par ts = new S tring[3]; | |
315 | in t count = 0; | |
316 | St ringTokeni zer parser = new Str ingTokeniz er(transfo rmation, " /"); | |
317 | tr y { | |
318 | while (p arser.hasM oreTokens( ) && count < 3) { | |
319 | part s[count++] = parser. nextToken( ).trim(); | |
320 | } | |
321 | if (coun t == 0 || count == 2 || parser .hasMoreTo kens()) { | |
322 | thro w new NoSu chAlgorith mException ("Invalid transforma tion" | |
323 | + " format:" + | |
324 | tra nsformatio n); | |
325 | } | |
326 | } catch (NoS uchElement Exception e) { | |
327 | throw ne w NoSuchAl gorithmExc eption("In valid tran sformation " + | |
328 | "format :" + trans formation) ; | |
329 | } | |
330 | if ((parts[0 ] == null) || (parts [0].length () == 0)) { | |
331 | throw ne w NoSuchAl gorithmExc eption("In valid tran sformation :" + | |
332 | "algo rithm not specified- " | |
333 | + tra nsformatio n); | |
334 | } | |
335 | re turn parts ; | |
336 | } | |
337 | ||
338 | // Pro vider attr ibute name for suppo rted chain ing mode | |
339 | privat e final st atic Strin g ATTR_MOD E = "Suppo rtedModes" ; | |
340 | // Pro vider attr ibute name for suppo rted paddi ng names | |
341 | privat e final st atic Strin g ATTR_PAD = "Suppo rtedPaddin gs"; | |
342 | ||
343 | // con stants ind icating wh ether the provider s upports | |
344 | // a g iven mode or padding | |
345 | privat e final st atic int S _NO = 0 ; // does not support | |
346 | privat e final st atic int S _MAYBE = 1 ; // unable to determine | |
347 | privat e final st atic int S _YES = 2 ; // does supp ort | |
348 | ||
349 | /** | |
350 | * Nes ted class to deal wi th modes a nd padding s. | |
351 | */ | |
352 | privat e static c lass Trans form { | |
353 | // transform string to lookup in the provi der | |
354 | fi nal String transform ; | |
355 | // the mode/ padding su ffix in up per case. for exampl e, if the algorithm | |
356 | // to lookup is "DES/C BC/PKCS5Pa dding" suf fix is "/C BC/PKCS5PA DDING" | |
357 | // if loopup is "DES", suffix is the empty string | |
358 | // needed be cause alia ses preven t straight transform .equals() | |
359 | fi nal String suffix; | |
360 | // value to pass to se tMode() or null if n o such cal l required | |
361 | fi nal String mode; | |
362 | // value to pass to se tPadding() or null i f no such call requi red | |
363 | fi nal String pad; | |
364 | Tr ansform(St ring alg, String suf fix, Strin g mode, St ring pad) { | |
365 | this.tra nsform = a lg + suffi x; | |
366 | this.suf fix = suff ix.toUpper Case(Local e.ENGLISH) ; | |
367 | this.mod e = mode; | |
368 | this.pad = pad; | |
369 | } | |
370 | // set mode and paddin g for the given SPI | |
371 | vo id setMode Padding(Ci pherSpi sp i) throws NoSuchAlgo rithmExcep tion, | |
372 | NoSu chPaddingE xception { | |
373 | if (mode != null) { | |
374 | spi. engineSetM ode(mode); | |
375 | } | |
376 | if (pad != null) { | |
377 | spi. engineSetP adding(pad ); | |
378 | } | |
379 | } | |
380 | // check whe ther the g iven servi ces suppor ts the mod e and | |
381 | // padding d escribed b y this Tra nsform | |
382 | in t supports ModePaddin g(Service s) { | |
383 | int smod e = suppor tsMode(s); | |
384 | if (smod e == S_NO) { | |
385 | retu rn smode; | |
386 | } | |
387 | int spad = support sPadding(s ); | |
388 | // our c onstants a re defined so that M ath.min() is a tri-v alued AND | |
389 | return M ath.min(sm ode, spad) ; | |
390 | } | |
391 | ||
392 | // separate methods fo r mode and padding | |
393 | // called di rectly by Cipher onl y to throw the corre ct excepti on | |
394 | in t supports Mode(Servi ce s) { | |
395 | return s upports(s, ATTR_MODE , mode); | |
396 | } | |
397 | in t supports Padding(Se rvice s) { | |
398 | return s upports(s, ATTR_PAD, pad); | |
399 | } | |
400 | ||
401 | pr ivate stat ic int sup ports(Serv ice s, Str ing attrNa me, String value) { | |
402 | if (valu e == null) { | |
403 | retu rn S_YES; | |
404 | } | |
405 | String r egexp = s. getAttribu te(attrNam e); | |
406 | if (rege xp == null ) { | |
407 | retu rn S_MAYBE ; | |
408 | } | |
409 | return m atches(reg exp, value ) ? S_YES : S_NO; | |
410 | } | |
411 | ||
412 | // Concurren tMap<Strin g,Pattern> for previ ously comp iled patte rns | |
413 | pr ivate fina l static C oncurrentM ap<String, Pattern> patternCac he = | |
414 | new Conc urrentHash Map<String , Pattern> (); | |
415 | ||
416 | pr ivate stat ic boolean matches(S tring rege xp, String str) { | |
417 | Pattern pattern = patternCac he.get(reg exp); | |
418 | if (patt ern == nul l) { | |
419 | patt ern = Patt ern.compil e(regexp); | |
420 | patt ernCache.p utIfAbsent (regexp, p attern); | |
421 | } | |
422 | return p attern.mat cher(str.t oUpperCase (Locale.EN GLISH)).ma tches(); | |
423 | } | |
424 | ||
425 | } | |
426 | ||
427 | privat e static L ist<Transf orm> getTr ansforms(S tring tran sformation ) | |
428 | throws N oSuchAlgor ithmExcept ion { | |
429 | St ring[] par ts = token izeTransfo rmation(tr ansformati on); | |
430 | ||
431 | St ring alg = parts[0]; | |
432 | St ring mode = parts[1] ; | |
433 | St ring pad = parts[2]; | |
434 | if ((mode != null) && (mode.leng th() == 0) ) { | |
435 | mode = n ull; | |
436 | } | |
437 | if ((pad != null) && ( pad.length () == 0)) { | |
438 | pad = nu ll; | |
439 | } | |
440 | ||
441 | if ((mode == null) && (pad == nu ll)) { | |
442 | // DES | |
443 | Transfor m tr = new Transform (alg, "", null, null ); | |
444 | return C ollections .singleton List(tr); | |
445 | } else { // if ((mode != null) & & (pad != null)) { | |
446 | // DES/C BC/PKCS5Pa dding | |
447 | List<Tra nsform> li st = new A rrayList<> (4); | |
448 | list.add (new Trans form(alg, "/" + mode + "/" + p ad, null, null)); | |
449 | list.add (new Trans form(alg, "/" + mode , null, pa d)); | |
450 | list.add (new Trans form(alg, "//" + pad , mode, nu ll)); | |
451 | list.add (new Trans form(alg, "", mode, pad)); | |
452 | return l ist; | |
453 | } | |
454 | } | |
455 | ||
456 | // get the trans form match ing the sp ecified se rvice | |
457 | privat e static T ransform g etTransfor m(Service s, | |
458 | List<Tra nsform> tr ansforms) { | |
459 | St ring alg = s.getAlgo rithm().to UpperCase( Locale.ENG LISH); | |
460 | fo r (Transfo rm tr : tr ansforms) { | |
461 | if (alg. endsWith(t r.suffix)) { | |
462 | retu rn tr; | |
463 | } | |
464 | } | |
465 | re turn null; | |
466 | } | |
467 | ||
468 | /** | |
469 | * Ret urns a <co de>Cipher< /code> obj ect that i mplements the specif ied | |
470 | * tra nsformatio n. | |
471 | * | |
472 | * <p> This meth od travers es the lis t of regis tered secu rity Provi ders, | |
473 | * sta rting with the most preferred Provider. | |
474 | * A n ew Cipher object enc apsulating the | |
475 | * Cip herSpi imp lementatio n from the first | |
476 | * Pro vider that supports the specif ied algori thm is ret urned. | |
477 | * | |
478 | * <p> Note that the list of registe red provid ers may be retrieved via | |
479 | * the {@link Se curity#get Providers( ) Security .getProvid ers()} met hod. | |
480 | * | |
481 | * @pa ram transf ormation t he name of the trans formation, e.g., | |
482 | * <i> DES/CBC/PK CS5Padding </i>. | |
483 | * See the Ciphe r section in the <a href= | |
484 | * " {@docRoot} /../techno tes/guides /security/ StandardNa mes.html#C ipher"> | |
485 | * Jav a Cryptogr aphy Archi tecture St andard Alg orithm Nam e Document ation</a> | |
486 | * for informati on about s tandard tr ansformati on names. | |
487 | * | |
488 | * @re turn a cip her that i mplements the reques ted transf ormation. | |
489 | * | |
490 | * @ex ception No SuchAlgori thmExcepti on if <cod e>transfor mation</co de> | |
491 | * is n ull, empty , in an in valid form at, | |
492 | * or i f no Provi der suppor ts a Ciphe rSpi imple mentation for the | |
493 | * spec ified algo rithm. | |
494 | * | |
495 | * @ex ception No SuchPaddin gException if <code> transforma tion</code > | |
496 | * cont ains a pad ding schem e that is not availa ble. | |
497 | * | |
498 | * @se e java.sec urity.Prov ider | |
499 | */ | |
500 | public static fi nal Cipher getInstan ce(String transforma tion) | |
501 | throws N oSuchAlgor ithmExcept ion, NoSuc hPaddingEx ception | |
502 | { | |
503 | Li st<Transfo rm> transf orms = get Transforms (transform ation); | |
504 | Li st<Service Id> cipher Services = new Array List<>(tra nsforms.si ze()); | |
505 | fo r (Transfo rm transfo rm : trans forms) { | |
506 | cipherSe rvices.add (new Servi ceId("Ciph er", trans form.trans form)); | |
507 | } | |
508 | Li st<Service > services = GetInst ance.getSe rvices(cip herService s); | |
509 | // make sure there is at least o ne service from a si gned provi der | |
510 | // and that it can use the speci fied mode and paddin g | |
511 | It erator<Ser vice> t = services.i terator(); | |
512 | Ex ception fa ilure = nu ll; | |
513 | wh ile (t.has Next()) { | |
514 | Service s = t.next (); | |
515 | if (JceS ecurity.ca nUseProvid er(s.getPr ovider()) == false) { | |
516 | cont inue; | |
517 | } | |
518 | Transfor m tr = get Transform( s, transfo rms); | |
519 | if (tr = = null) { | |
520 | // s hould neve r happen | |
521 | cont inue; | |
522 | } | |
523 | int canu se = tr.su pportsMode Padding(s) ; | |
524 | if (canu se == S_NO ) { | |
525 | // d oes not su pport mode or paddin g we need, ignore | |
526 | cont inue; | |
527 | } | |
528 | if (canu se == S_YE S) { | |
529 | retu rn new Cip her(null, s, t, tran sformation , transfor ms); | |
530 | } else { // S_MAYB E, try out if it wor ks | |
531 | try { | |
532 | CipherSpi spi = (Cip herSpi)s.n ewInstance (null); | |
533 | tr.setMode Padding(sp i); | |
534 | return new Cipher(sp i, s, t, t ransformat ion, trans forms); | |
535 | } ca tch (Excep tion e) { | |
536 | failure = e; | |
537 | } | |
538 | } | |
539 | } | |
540 | th row new No SuchAlgori thmExcepti on | |
541 | ("Cannot find any provider s upporting " + transf ormation, failure); | |
542 | } | |
543 | ||
544 | /** | |
545 | * Ret urns a <co de>Cipher< /code> obj ect that i mplements the specif ied | |
546 | * tra nsformatio n. | |
547 | * | |
548 | * <p> A new Cip her object encapsula ting the | |
549 | * Cip herSpi imp lementatio n from the specified provider | |
550 | * is returned. The speci fied provi der must b e register ed | |
551 | * in the securi ty provide r list. | |
552 | * | |
553 | * <p> Note that the list of registe red provid ers may be retrieved via | |
554 | * the {@link Se curity#get Providers( ) Security .getProvid ers()} met hod. | |
555 | * | |
556 | * @pa ram transf ormation t he name of the trans formation, | |
557 | * e.g ., <i>DES/ CBC/PKCS5P adding</i> . | |
558 | * See the Ciphe r section in the <a href= | |
559 | * " {@docRoot} /../techno tes/guides /security/ StandardNa mes.html#C ipher"> | |
560 | * Jav a Cryptogr aphy Archi tecture St andard Alg orithm Nam e Document ation</a> | |
561 | * for informati on about s tandard tr ansformati on names. | |
562 | * | |
563 | * @pa ram provid er the nam e of the p rovider. | |
564 | * | |
565 | * @re turn a cip her that i mplements the reques ted transf ormation. | |
566 | * | |
567 | * @ex ception No SuchAlgori thmExcepti on if <cod e>transfor mation</co de> | |
568 | * is n ull, empty , in an in valid form at, | |
569 | * or i f a Cipher Spi implem entation f or the spe cified alg orithm | |
570 | * is n ot availab le from th e specifie d provider . | |
571 | * | |
572 | * @ex ception No SuchProvid erExceptio n if the s pecified p rovider is not | |
573 | * regi stered in the securi ty provide r list. | |
574 | * | |
575 | * @ex ception No SuchPaddin gException if <code> transforma tion</code > | |
576 | * cont ains a pad ding schem e that is not availa ble. | |
577 | * | |
578 | * @ex ception Il legalArgum entExcepti on if the <code>prov ider</code > | |
579 | * is n ull or emp ty. | |
580 | * | |
581 | * @se e java.sec urity.Prov ider | |
582 | */ | |
583 | public static fi nal Cipher getInstan ce(String transforma tion, | |
584 | String provider) | |
585 | throws N oSuchAlgor ithmExcept ion, NoSuc hProviderE xception, | |
586 | NoSuchPa ddingExcep tion | |
587 | { | |
588 | if ((provide r == null) || (provi der.length () == 0)) { | |
589 | throw ne w IllegalA rgumentExc eption("Mi ssing prov ider"); | |
590 | } | |
591 | Pr ovider p = Security. getProvide r(provider ); | |
592 | if (p == nul l) { | |
593 | throw ne w NoSuchPr oviderExce ption("No such provi der: " + | |
594 | prov ider); | |
595 | } | |
596 | re turn getIn stance(tra nsformatio n, p); | |
597 | } | |
598 | ||
599 | /** | |
600 | * Ret urns a <co de>Cipher< /code> obj ect that i mplements the specif ied | |
601 | * tra nsformatio n. | |
602 | * | |
603 | * <p> A new Cip her object encapsula ting the | |
604 | * Cip herSpi imp lementatio n from the specified Provider | |
605 | * obj ect is ret urned. No te that th e specifie d Provider object | |
606 | * doe s not have to be reg istered in the provi der list. | |
607 | * | |
608 | * @pa ram transf ormation t he name of the trans formation, | |
609 | * e.g ., <i>DES/ CBC/PKCS5P adding</i> . | |
610 | * See the Ciphe r section in the <a href= | |
611 | * " {@docRoot} /../techno tes/guides /security/ StandardNa mes.html#C ipher"> | |
612 | * Jav a Cryptogr aphy Archi tecture St andard Alg orithm Nam e Document ation</a> | |
613 | * for informati on about s tandard tr ansformati on names. | |
614 | * | |
615 | * @pa ram provid er the pro vider. | |
616 | * | |
617 | * @re turn a cip her that i mplements the reques ted transf ormation. | |
618 | * | |
619 | * @ex ception No SuchAlgori thmExcepti on if <cod e>transfor mation</co de> | |
620 | * is n ull, empty , in an in valid form at, | |
621 | * or i f a Cipher Spi implem entation f or the spe cified alg orithm | |
622 | * is n ot availab le from th e specifie d Provider object. | |
623 | * | |
624 | * @ex ception No SuchPaddin gException if <code> transforma tion</code > | |
625 | * cont ains a pad ding schem e that is not availa ble. | |
626 | * | |
627 | * @ex ception Il legalArgum entExcepti on if the <code>prov ider</code > | |
628 | * is n ull. | |
629 | * | |
630 | * @se e java.sec urity.Prov ider | |
631 | */ | |
632 | public static fi nal Cipher getInstan ce(String transforma tion, | |
633 | Provide r provider ) | |
634 | throws N oSuchAlgor ithmExcept ion, NoSuc hPaddingEx ception | |
635 | { | |
636 | if (provider == null) { | |
637 | throw ne w IllegalA rgumentExc eption("Mi ssing prov ider"); | |
638 | } | |
639 | Ex ception fa ilure = nu ll; | |
640 | Li st<Transfo rm> transf orms = get Transforms (transform ation); | |
641 | bo olean prov iderChecke d = false; | |
642 | St ring paddi ngError = null; | |
643 | fo r (Transfo rm tr : tr ansforms) { | |
644 | Service s = provid er.getServ ice("Ciphe r", tr.tra nsform); | |
645 | if (s == null) { | |
646 | cont inue; | |
647 | } | |
648 | if (prov iderChecke d == false ) { | |
649 | // f or compati bility, fi rst do the lookup an d then ver ify | |
650 | // t he provide r. this ma kes the di fference b etween a N SAE | |
651 | // a nd a Secur ityExcepti on if the | |
652 | // p rovider do es not sup port the a lgorithm. | |
653 | Exce ption ve = JceSecuri ty.getVeri ficationRe sult(provi der); | |
654 | if ( ve != null ) { | |
655 | String msg = "JCE ca nnot authe nticate th e provider " | |
656 | + prov ider.getNa me(); | |
657 | throw new SecurityEx ception(ms g, ve); | |
658 | } | |
659 | prov iderChecke d = true; | |
660 | } | |
661 | if (tr.s upportsMod e(s) == S_ NO) { | |
662 | cont inue; | |
663 | } | |
664 | if (tr.s upportsPad ding(s) == S_NO) { | |
665 | padd ingError = tr.pad; | |
666 | cont inue; | |
667 | } | |
668 | try { | |
669 | Ciph erSpi spi = (CipherS pi)s.newIn stance(nul l); | |
670 | tr.s etModePadd ing(spi); | |
671 | Ciph er cipher = new Ciph er(spi, tr ansformati on); | |
672 | ciph er.provide r = s.getP rovider(); | |
673 | ciph er.initCry ptoPermiss ion(); | |
674 | retu rn cipher; | |
675 | } catch (Exception e) { | |
676 | fail ure = e; | |
677 | } | |
678 | } | |
679 | ||
680 | // throw NoS uchPadding Exception if the pro blem is wi th padding | |
681 | if (failure instanceof NoSuchPad dingExcept ion) { | |
682 | throw (N oSuchPaddi ngExceptio n)failure; | |
683 | } | |
684 | if (paddingE rror != nu ll) { | |
685 | throw ne w NoSuchPa ddingExcep tion | |
686 | ("Pa dding not supported: " + paddi ngError); | |
687 | } | |
688 | th row new No SuchAlgori thmExcepti on | |
689 | ("No such algo rithm: " + transform ation, fai lure); | |
690 | } | |
691 | ||
692 | // If the reques ted crypto service i s export-c ontrolled, | |
693 | // det ermine the maximum a llowable k eysize. | |
694 | privat e void ini tCryptoPer mission() throws NoS uchAlgorit hmExceptio n { | |
695 | if (JceSecur ity.isRest ricted() = = false) { | |
696 | cryptoPe rm = Crypt oAllPermis sion.INSTA NCE; | |
697 | exmech = null; | |
698 | return; | |
699 | } | |
700 | cr yptoPerm = getConfig uredPermis sion(trans formation) ; | |
701 | // Instantia te the exe mption mec hanism (if required) | |
702 | St ring exmec hName = cr yptoPerm.g etExemptio nMechanism (); | |
703 | if (exmechNa me != null ) { | |
704 | exmech = Exemption Mechanism. getInstanc e(exmechNa me); | |
705 | } | |
706 | } | |
707 | ||
708 | // max number of debug war nings to p rint from chooseFirs tProvider( ) | |
709 | privat e static i nt warnCou nt = 10; | |
710 | ||
711 | /** | |
712 | * Cho ose the Sp i from the first pro vider avai lable. Use d if | |
713 | * del ayed provi der select ion is not possible because in it() | |
714 | * is not the fi rst method called. | |
715 | */ | |
716 | void c hooseFirst Provider() { | |
717 | if (spi != n ull) { | |
718 | return; | |
719 | } | |
720 | sy nchronized (lock) { | |
721 | if (spi != null) { | |
722 | retu rn; | |
723 | } | |
724 | if (debu g != null) { | |
725 | int w = --warn Count; | |
726 | if ( w >= 0) { | |
727 | debug.prin tln("Ciphe r.init() n ot first m ethod " | |
728 | + "cal led, disab ling delay ed provide r selectio n"); | |
729 | if (w == 0 ) { | |
730 | debug. println("F urther war nings of t his type w ill " | |
731 | + "be suppre ssed"); | |
732 | } | |
733 | new Except ion("Call trace").pr intStackTr ace(); | |
734 | } | |
735 | } | |
736 | Exceptio n lastExce ption = nu ll; | |
737 | while (( firstServi ce != null ) || servi ceIterator .hasNext() ) { | |
738 | Serv ice s; | |
739 | Ciph erSpi this Spi; | |
740 | if ( firstServi ce != null ) { | |
741 | s = firstS ervice; | |
742 | thisSpi = firstSpi; | |
743 | firstServi ce = null; | |
744 | firstSpi = null; | |
745 | } el se { | |
746 | s = servic eIterator. next(); | |
747 | thisSpi = null; | |
748 | } | |
749 | if ( JceSecurit y.canUsePr ovider(s.g etProvider ()) == fal se) { | |
750 | continue; | |
751 | } | |
752 | Tran sform tr = getTransf orm(s, tra nsforms); | |
753 | if ( tr == null ) { | |
754 | // should never happ en | |
755 | continue; | |
756 | } | |
757 | if ( tr.support sModePaddi ng(s) == S _NO) { | |
758 | continue; | |
759 | } | |
760 | try { | |
761 | if (thisSp i == null) { | |
762 | Object obj = s.n ewInstance (null); | |
763 | if (ob j instance of CipherS pi == fals e) { | |
764 | co ntinue; | |
765 | } | |
766 | thisSp i = (Ciphe rSpi)obj; | |
767 | } | |
768 | tr.setMode Padding(th isSpi); | |
769 | initCrypto Permission (); | |
770 | spi = this Spi; | |
771 | provider = s.getProv ider(); | |
772 | // not nee ded any mo re | |
773 | firstServi ce = null; | |
774 | serviceIte rator = nu ll; | |
775 | transforms = null; | |
776 | return; | |
777 | } ca tch (Excep tion e) { | |
778 | lastExcept ion = e; | |
779 | } | |
780 | } | |
781 | Provider Exception e = new Pr oviderExce ption | |
782 | ("Could no t construc t CipherSp i instance "); | |
783 | if (last Exception != null) { | |
784 | e.in itCause(la stExceptio n); | |
785 | } | |
786 | throw e; | |
787 | } | |
788 | } | |
789 | ||
790 | privat e final st atic int I _KEY = 1; | |
791 | privat e final st atic int I _PARAMSPEC = 2; | |
792 | privat e final st atic int I _PARAMS = 3; | |
793 | privat e final st atic int I _CERT = 4; | |
794 | ||
795 | privat e void imp lInit(Ciph erSpi this Spi, int t ype, int o pmode, Key key, | |
796 | Algorith mParameter Spec param Spec, Algo rithmParam eters para ms, | |
797 | SecureRa ndom rando m) throws InvalidKey Exception, | |
798 | InvalidA lgorithmPa rameterExc eption { | |
799 | sw itch (type ) { | |
800 | ca se I_KEY: | |
801 | checkCry ptoPerm(th isSpi, key ); | |
802 | thisSpi. engineInit (opmode, k ey, random ); | |
803 | break; | |
804 | ca se I_PARAM SPEC: | |
805 | checkCry ptoPerm(th isSpi, key , paramSpe c); | |
806 | thisSpi. engineInit (opmode, k ey, paramS pec, rando m); | |
807 | break; | |
808 | ca se I_PARAM S: | |
809 | checkCry ptoPerm(th isSpi, key , params); | |
810 | thisSpi. engineInit (opmode, k ey, params , random); | |
811 | break; | |
812 | ca se I_CERT: | |
813 | checkCry ptoPerm(th isSpi, key ); | |
814 | thisSpi. engineInit (opmode, k ey, random ); | |
815 | break; | |
816 | de fault: | |
817 | throw ne w Assertio nError("In ternal Cip her error: " + type) ; | |
818 | } | |
819 | } | |
820 | ||
821 | privat e void cho oseProvide r(int init Type, int opmode, Ke y key, | |
822 | Algorith mParameter Spec param Spec, | |
823 | Algorith mParameter s params, SecureRand om random) | |
824 | throws I nvalidKeyE xception, InvalidAlg orithmPara meterExcep tion { | |
825 | sy nchronized (lock) { | |
826 | if (spi != null) { | |
827 | impl Init(spi, initType, opmode, ke y, paramSp ec, params , random); | |
828 | retu rn; | |
829 | } | |
830 | Exceptio n lastExce ption = nu ll; | |
831 | while (( firstServi ce != null ) || servi ceIterator .hasNext() ) { | |
832 | Serv ice s; | |
833 | Ciph erSpi this Spi; | |
834 | if ( firstServi ce != null ) { | |
835 | s = firstS ervice; | |
836 | thisSpi = firstSpi; | |
837 | firstServi ce = null; | |
838 | firstSpi = null; | |
839 | } el se { | |
840 | s = servic eIterator. next(); | |
841 | thisSpi = null; | |
842 | } | |
843 | // i f provider says it d oes not su pport this key, igno re it | |
844 | if ( s.supports Parameter( key) == fa lse) { | |
845 | continue; | |
846 | } | |
847 | if ( JceSecurit y.canUsePr ovider(s.g etProvider ()) == fal se) { | |
848 | continue; | |
849 | } | |
850 | Tran sform tr = getTransf orm(s, tra nsforms); | |
851 | if ( tr == null ) { | |
852 | // should never happ en | |
853 | continue; | |
854 | } | |
855 | if ( tr.support sModePaddi ng(s) == S _NO) { | |
856 | continue; | |
857 | } | |
858 | try { | |
859 | if (thisSp i == null) { | |
860 | thisSp i = (Ciphe rSpi)s.new Instance(n ull); | |
861 | } | |
862 | tr.setMode Padding(th isSpi); | |
863 | initCrypto Permission (); | |
864 | implInit(t hisSpi, in itType, op mode, key, paramSpec , | |
865 | para ms, random ); | |
866 | provider = s.getProv ider(); | |
867 | this.spi = thisSpi; | |
868 | firstServi ce = null; | |
869 | serviceIte rator = nu ll; | |
870 | transforms = null; | |
871 | return; | |
872 | } ca tch (Excep tion e) { | |
873 | // NoSuchA lgorithmEx ception fr om newInst ance() | |
874 | // Invalid KeyExcepti on from in it() | |
875 | // Runtime Exception (ProviderE xception) from init( ) | |
876 | // Securit yException from cryp to permiss ion check | |
877 | if (lastEx ception == null) { | |
878 | lastEx ception = e; | |
879 | } | |
880 | } | |
881 | } | |
882 | // no wo rking prov ider found , fail | |
883 | if (last Exception instanceof InvalidKe yException ) { | |
884 | thro w (Invalid KeyExcepti on)lastExc eption; | |
885 | } | |
886 | if (last Exception instanceof InvalidAl gorithmPar ameterExce ption) { | |
887 | thro w (Invalid AlgorithmP arameterEx ception)la stExceptio n; | |
888 | } | |
889 | if (last Exception instanceof RuntimeEx ception) { | |
890 | thro w (Runtime Exception) lastExcept ion; | |
891 | } | |
892 | String k Name = (ke y != null) ? key.get Class().ge tName() : "(null)"; | |
893 | throw ne w InvalidK eyExceptio n | |
894 | ("No installed provider supports t his key: " | |
895 | + kN ame, lastE xception); | |
896 | } | |
897 | } | |
898 | ||
899 | /** | |
900 | * Ret urns the p rovider of this <cod e>Cipher</ code> obje ct. | |
901 | * | |
902 | * @re turn the p rovider of this <cod e>Cipher</ code> obje ct | |
903 | */ | |
904 | public final Pro vider getP rovider() { | |
905 | ch ooseFirstP rovider(); | |
906 | re turn this. provider; | |
907 | } | |
908 | ||
909 | /** | |
910 | * Ret urns the a lgorithm n ame of thi s <code>Ci pher</code > object. | |
911 | * | |
912 | * <p> This is th e same nam e that was specified in one of the | |
913 | * <co de>getInst ance</code > calls th at created this <cod e>Cipher</ code> | |
914 | * obj ect.. | |
915 | * | |
916 | * @re turn the a lgorithm n ame of thi s <code>Ci pher</code > object. | |
917 | */ | |
918 | public final Str ing getAlg orithm() { | |
919 | re turn this. transforma tion; | |
920 | } | |
921 | ||
922 | /** | |
923 | * Ret urns the b lock size (in bytes) . | |
924 | * | |
925 | * @re turn the b lock size (in bytes) , or 0 if the underl ying algor ithm is | |
926 | * not a block c ipher | |
927 | */ | |
928 | public final int getBlockS ize() { | |
929 | ch ooseFirstP rovider(); | |
930 | re turn spi.e ngineGetBl ockSize(); | |
931 | } | |
932 | ||
933 | /** | |
934 | * Ret urns the l ength in b ytes that an output buffer wou ld need to be in | |
935 | * ord er to hold the resul t of the n ext <code> update</co de> or | |
936 | * <co de>doFinal </code> op eration, g iven the i nput lengt h | |
937 | * <co de>inputLe n</code> ( in bytes). | |
938 | * | |
939 | * <p> This call takes into account a ny unproce ssed (buff ered) data from a | |
940 | * pre vious <cod e>update</ code> call , padding, and AEAD tagging. | |
941 | * | |
942 | * <p> The actual output le ngth of th e next <co de>update< /code> or | |
943 | * <co de>doFinal </code> ca ll may be smaller th an the len gth return ed by | |
944 | * thi s method. | |
945 | * | |
946 | * @pa ram inputL en the inp ut length (in bytes) | |
947 | * | |
948 | * @re turn the r equired ou tput buffe r size (in bytes) | |
949 | * | |
950 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
951 | * (e. g., has no t yet been initializ ed) | |
952 | */ | |
953 | public final int getOutput Size(int i nputLen) { | |
954 | ||
955 | if (!initial ized && !( this insta nceof Null Cipher)) { | |
956 | throw ne w IllegalS tateExcept ion("Ciphe r not init ialized"); | |
957 | } | |
958 | if (inputLen < 0) { | |
959 | throw ne w IllegalA rgumentExc eption("In put size m ust be equ al " + | |
960 | "to or greate r than zer o"); | |
961 | } | |
962 | ch ooseFirstP rovider(); | |
963 | re turn spi.e ngineGetOu tputSize(i nputLen); | |
964 | } | |
965 | ||
966 | /** | |
967 | * Ret urns the i nitializat ion vector (IV) in a new buffe r. | |
968 | * | |
969 | * <p> This is us eful in th e case whe re a rando m IV was c reated, | |
970 | * or in the con text of pa ssword-bas ed encrypt ion or | |
971 | * dec ryption, w here the I V is deriv ed from a user-suppl ied passwo rd. | |
972 | * | |
973 | * @re turn the i nitializat ion vector in a new buffer, or null if t he | |
974 | * und erlying al gorithm do es not use an IV, or if the IV has not y et | |
975 | * bee n set. | |
976 | */ | |
977 | public final byt e[] getIV( ) { | |
978 | ch ooseFirstP rovider(); | |
979 | re turn spi.e ngineGetIV (); | |
980 | } | |
981 | ||
982 | /** | |
983 | * Ret urns the p arameters used with this ciphe r. | |
984 | * | |
985 | * <p> The return ed paramet ers may be the same that were used to in itialize | |
986 | * thi s cipher, or may con tain a com bination o f default and random | |
987 | * par ameter val ues used b y the unde rlying cip her implem entation i f this | |
988 | * cip her requir es algorit hm paramet ers but wa s not init ialized wi th any. | |
989 | * | |
990 | * @re turn the p arameters used with this ciphe r, or null if this c ipher | |
991 | * doe s not use any parame ters. | |
992 | */ | |
993 | public final Alg orithmPara meters get Parameters () { | |
994 | ch ooseFirstP rovider(); | |
995 | re turn spi.e ngineGetPa rameters() ; | |
996 | } | |
997 | ||
998 | /** | |
999 | * Ret urns the e xemption m echanism o bject used with this cipher. | |
1000 | * | |
1001 | * @re turn the e xemption m echanism o bject used with this cipher, o r | |
1002 | * nul l if this cipher doe s not use any exempt ion mechan ism. | |
1003 | */ | |
1004 | public final Exe mptionMech anism getE xemptionMe chanism() { | |
1005 | ch ooseFirstP rovider(); | |
1006 | re turn exmec h; | |
1007 | } | |
1008 | ||
1009 | // | |
1010 | // Cry pto permis sion check code belo w | |
1011 | // | |
1012 | privat e void che ckCryptoPe rm(CipherS pi checkSp i, Key key ) | |
1013 | throws I nvalidKeyE xception { | |
1014 | if (cryptoPe rm == Cryp toAllPermi ssion.INST ANCE) { | |
1015 | return; | |
1016 | } | |
1017 | // Check if key size a nd default parameter s are with in legal l imits | |
1018 | Al gorithmPar ameterSpec params; | |
1019 | tr y { | |
1020 | params = getAlgori thmParamet erSpec(che ckSpi.engi neGetParam eters()); | |
1021 | } catch (Inv alidParame terSpecExc eption ips e) { | |
1022 | throw ne w InvalidK eyExceptio n | |
1023 | ("Un supported default al gorithm pa rameters") ; | |
1024 | } | |
1025 | if (!passCry ptoPermChe ck(checkSp i, key, pa rams)) { | |
1026 | throw ne w InvalidK eyExceptio n( | |
1027 | "Ill egal key s ize or def ault param eters"); | |
1028 | } | |
1029 | } | |
1030 | ||
1031 | privat e void che ckCryptoPe rm(CipherS pi checkSp i, Key key , | |
1032 | Algorith mParameter Spec param s) throws InvalidKey Exception, | |
1033 | InvalidA lgorithmPa rameterExc eption { | |
1034 | if (cryptoPe rm == Cryp toAllPermi ssion.INST ANCE) { | |
1035 | return; | |
1036 | } | |
1037 | // Determine keysize a nd check i f it is wi thin legal limits | |
1038 | if (!passCry ptoPermChe ck(checkSp i, key, nu ll)) { | |
1039 | throw ne w InvalidK eyExceptio n("Illegal key size" ); | |
1040 | } | |
1041 | if ((params != null) & & (!passCr yptoPermCh eck(checkS pi, key, p arams))) { | |
1042 | throw ne w InvalidA lgorithmPa rameterExc eption("Il legal para meters"); | |
1043 | } | |
1044 | } | |
1045 | ||
1046 | privat e void che ckCryptoPe rm(CipherS pi checkSp i, Key key , | |
1047 | Algorith mParameter s params) | |
1048 | throws I nvalidKeyE xception, InvalidAlg orithmPara meterExcep tion { | |
1049 | if (cryptoPe rm == Cryp toAllPermi ssion.INST ANCE) { | |
1050 | return; | |
1051 | } | |
1052 | // Convert t he specifi ed paramet ers into s pecs and t hen delega te. | |
1053 | Al gorithmPar ameterSpec pSpec; | |
1054 | tr y { | |
1055 | pSpec = getAlgorit hmParamete rSpec(para ms); | |
1056 | } catch (Inv alidParame terSpecExc eption ips e) { | |
1057 | throw ne w InvalidA lgorithmPa rameterExc eption | |
1058 | ("Fa iled to re trieve alg orithm par ameter spe cification "); | |
1059 | } | |
1060 | ch eckCryptoP erm(checkS pi, key, p Spec); | |
1061 | } | |
1062 | ||
1063 | privat e boolean passCrypto PermCheck( CipherSpi checkSpi, Key key, | |
1064 | AlgorithmP arameterSp ec params) | |
1065 | throws I nvalidKeyE xception { | |
1066 | St ring em = cryptoPerm .getExempt ionMechani sm(); | |
1067 | in t keySize = checkSpi .engineGet KeySize(ke y); | |
1068 | // Use the " algorithm" component of the ci pher | |
1069 | // transform ation so t hat the pe rm check w ould | |
1070 | // work when the key h as the "al iased" alg o. | |
1071 | St ring algCo mponent; | |
1072 | in t index = transforma tion.index Of('/'); | |
1073 | if (index != -1) { | |
1074 | algCompo nent = tra nsformatio n.substrin g(0, index ); | |
1075 | } else { | |
1076 | algCompo nent = tra nsformatio n; | |
1077 | } | |
1078 | Cr yptoPermis sion check Perm = | |
1079 | new Cryp toPermissi on(algComp onent, key Size, para ms, em); | |
1080 | ||
1081 | if (!cryptoP erm.implie s(checkPer m)) { | |
1082 | if (debu g != null) { | |
1083 | debu g.println( "Crypto Pe rmission c heck faile d"); | |
1084 | debu g.println( "granted: " + crypto Perm); | |
1085 | debu g.println( "requestin g: " + che ckPerm); | |
1086 | } | |
1087 | return f alse; | |
1088 | } | |
1089 | if (exmech = = null) { | |
1090 | return t rue; | |
1091 | } | |
1092 | tr y { | |
1093 | if (!exm ech.isCryp toAllowed( key)) { | |
1094 | if ( debug != n ull) { | |
1095 | debug.prin tln(exmech .getName() + " isn't enforced" ); | |
1096 | } | |
1097 | retu rn false; | |
1098 | } | |
1099 | } catch (Exe mptionMech anismExcep tion eme) { | |
1100 | if (debu g != null) { | |
1101 | debu g.println( "Cannot de termine wh ether "+ | |
1102 | exmech.get Name() + " has been enforced") ; | |
1103 | eme. printStack Trace(); | |
1104 | } | |
1105 | return f alse; | |
1106 | } | |
1107 | re turn true; | |
1108 | } | |
1109 | ||
1110 | // che ck if opmo de is one of the def ined const ants | |
1111 | // thr ow Invalid ParameterE xeption if not | |
1112 | privat e static v oid checkO pmode(int opmode) { | |
1113 | if ((opmode < ENCRYPT_ MODE) || ( opmode > U NWRAP_MODE )) { | |
1114 | throw ne w InvalidP arameterEx ception("I nvalid ope ration mod e"); | |
1115 | } | |
1116 | } | |
1117 | ||
1118 | privat e static S tring getO pmodeStrin g(int opmo de) { | |
1119 | sw itch (opmo de) { | |
1120 | case ENC RYPT_MODE: | |
1121 | retu rn "encryp tion"; | |
1122 | case DEC RYPT_MODE: | |
1123 | retu rn "decryp tion"; | |
1124 | case WRA P_MODE: | |
1125 | retu rn "key wr apping"; | |
1126 | case UNW RAP_MODE: | |
1127 | retu rn "key un wrapping"; | |
1128 | default: | |
1129 | retu rn ""; | |
1130 | } | |
1131 | } | |
1132 | ||
1133 | /** | |
1134 | * Ini tializes t his cipher with a ke y. | |
1135 | * | |
1136 | * <p> The cipher is initia lized for one of the following four oper ations: | |
1137 | * enc ryption, d ecryption, key wrapp ing or key unwrappin g, dependi ng | |
1138 | * on the value of <code>o pmode</cod e>. | |
1139 | * | |
1140 | * <p> If this ci pher requi res any al gorithm pa rameters t hat cannot be | |
1141 | * der ived from the given <code>key< /code>, th e underlyi ng cipher | |
1142 | * imp lementatio n is suppo sed to gen erate the required p arameters itself | |
1143 | * (us ing provid er-specifi c default or random values) if it is bei ng | |
1144 | * ini tialized f or encrypt ion or key wrapping, and raise an | |
1145 | * <co de>Invalid KeyExcepti on</code> if it is b eing | |
1146 | * ini tialized f or decrypt ion or key unwrappin g. | |
1147 | * The generated parameter s can be r etrieved u sing | |
1148 | * {@l ink #getPa rameters() getParame ters} or | |
1149 | * {@l ink #getIV () getIV} (if the pa rameter is an IV). | |
1150 | * | |
1151 | * <p> If this ci pher requi res algori thm parame ters that cannot be | |
1152 | * der ived from the input parameters , and ther e are no r easonable | |
1153 | * pro vider-spec ific defau lt values, initializ ation will | |
1154 | * nec essarily f ail. | |
1155 | * | |
1156 | * <p> If this ci pher (incl uding its underlying feedback or padding scheme) | |
1157 | * req uires any random byt es (e.g., for parame ter genera tion), it will get | |
1158 | * the m using th e {@link j ava.securi ty.SecureR andom} | |
1159 | * imp lementatio n of the h ighest-pri ority | |
1160 | * ins talled pro vider as t he source of randomn ess. | |
1161 | * (If none of t he install ed provide rs supply an impleme ntation of | |
1162 | * Sec ureRandom, a system- provided s ource of r andomness will be us ed.) | |
1163 | * | |
1164 | * <p> Note that when a Cip her object is initia lized, it loses all | |
1165 | * pre viously-ac quired sta te. In oth er words, initializi ng a Ciphe r is | |
1166 | * equ ivalent to creating a new inst ance of th at Cipher and initia lizing | |
1167 | * it. | |
1168 | * | |
1169 | * @pa ram opmode the opera tion mode of this ci pher (this is one of | |
1170 | * the following : | |
1171 | * <co de>ENCRYPT _MODE</cod e>, <code> DECRYPT_MO DE</code>, | |
1172 | * <co de>WRAP_MO DE</code> or <code>U NWRAP_MODE </code>) | |
1173 | * @pa ram key th e key | |
1174 | * | |
1175 | * @ex ception In validKeyEx ception if the given key is in appropriat e for | |
1176 | * ini tializing this ciphe r, or requ ires | |
1177 | * alg orithm par ameters th at cannot be | |
1178 | * det ermined fr om the giv en key, or if the gi ven key ha s a keysiz e that | |
1179 | * exc eeds the m aximum all owable key size (as d etermined from the | |
1180 | * con figured ju risdiction policy fi les). | |
1181 | * @th rows Unsup portedOper ationExcep tion if (@ code opmod e} is | |
1182 | * {@c ode WRAP_M ODE} or {@ code UNWRA P_MODE} bu t the mode is not im plemented | |
1183 | * by the underl ying {@cod e CipherSp i}. | |
1184 | */ | |
1185 | public final voi d init(int opmode, K ey key) th rows Inval idKeyExcep tion { | |
1186 | in it(opmode, key, JceS ecurity.RA NDOM); | |
1187 | } | |
1188 | ||
1189 | /** | |
1190 | * Ini tializes t his cipher with a ke y and a so urce of ra ndomness. | |
1191 | * | |
1192 | * <p> The cipher is initia lized for one of the following four oper ations: | |
1193 | * enc ryption, d ecryption, key wrapp ing or ke y unwrappi ng, depend ing | |
1194 | * on the value of <code>o pmode</cod e>. | |
1195 | * | |
1196 | * <p> If this ci pher requi res any al gorithm pa rameters t hat cannot be | |
1197 | * der ived from the given <code>key< /code>, th e underlyi ng cipher | |
1198 | * imp lementatio n is suppo sed to gen erate the required p arameters itself | |
1199 | * (us ing provid er-specifi c default or random values) if it is bei ng | |
1200 | * ini tialized f or encrypt ion or key wrapping, and raise an | |
1201 | * <co de>Invalid KeyExcepti on</code> if it is b eing | |
1202 | * ini tialized f or decrypt ion or key unwrappin g. | |
1203 | * The generated parameter s can be r etrieved u sing | |
1204 | * {@l ink #getPa rameters() getParame ters} or | |
1205 | * {@l ink #getIV () getIV} (if the pa rameter is an IV). | |
1206 | * | |
1207 | * <p> If this ci pher requi res algori thm parame ters that cannot be | |
1208 | * der ived from the input parameters , and ther e are no r easonable | |
1209 | * pro vider-spec ific defau lt values, initializ ation will | |
1210 | * nec essarily f ail. | |
1211 | * | |
1212 | * <p> If this ci pher (incl uding its underlying feedback or padding scheme) | |
1213 | * req uires any random byt es (e.g., for parame ter genera tion), it will get | |
1214 | * the m from <co de>random< /code>. | |
1215 | * | |
1216 | * <p> Note that when a Cip her object is initia lized, it loses all | |
1217 | * pre viously-ac quired sta te. In oth er words, initializi ng a Ciphe r is | |
1218 | * equ ivalent to creating a new inst ance of th at Cipher and initia lizing | |
1219 | * it. | |
1220 | * | |
1221 | * @pa ram opmode the opera tion mode of this ci pher (this is one of the | |
1222 | * fol lowing: | |
1223 | * <co de>ENCRYPT _MODE</cod e>, <code> DECRYPT_MO DE</code>, | |
1224 | * <co de>WRAP_MO DE</code> or <code>U NWRAP_MODE </code>) | |
1225 | * @pa ram key th e encrypti on key | |
1226 | * @pa ram random the sourc e of rando mness | |
1227 | * | |
1228 | * @ex ception In validKeyEx ception if the given key is in appropriat e for | |
1229 | * ini tializing this ciphe r, or requ ires | |
1230 | * alg orithm par ameters th at cannot be | |
1231 | * det ermined fr om the giv en key, or if the gi ven key ha s a keysiz e that | |
1232 | * exc eeds the m aximum all owable key size (as d etermined from the | |
1233 | * con figured ju risdiction policy fi les). | |
1234 | * @th rows Unsup portedOper ationExcep tion if (@ code opmod e} is | |
1235 | * {@c ode WRAP_M ODE} or {@ code UNWRA P_MODE} bu t the mode is not im plemented | |
1236 | * by the underl ying {@cod e CipherSp i}. | |
1237 | */ | |
1238 | public final voi d init(int opmode, K ey key, Se cureRandom random) | |
1239 | throws I nvalidKeyE xception | |
1240 | { | |
1241 | in itialized = false; | |
1242 | ch eckOpmode( opmode); | |
1243 | ||
1244 | if (spi != n ull) { | |
1245 | checkCry ptoPerm(sp i, key); | |
1246 | spi.engi neInit(opm ode, key, random); | |
1247 | } else { | |
1248 | try { | |
1249 | choo seProvider (I_KEY, op mode, key, null, nul l, random) ; | |
1250 | } catch (InvalidAl gorithmPar ameterExce ption e) { | |
1251 | // s hould neve r occur | |
1252 | thro w new Inva lidKeyExce ption(e); | |
1253 | } | |
1254 | } | |
1255 | ||
1256 | in itialized = true; | |
1257 | th is.opmode = opmode; | |
1258 | ||
1259 | if (!skipDeb ug && pdeb ug != null ) { | |
1260 | pdebug.p rintln("Ci pher." + t ransformat ion + " " + | |
1261 | getO pmodeStrin g(opmode) + " algori thm from: " + | |
1262 | this .provider. getName()) ; | |
1263 | } | |
1264 | } | |
1265 | ||
1266 | /** | |
1267 | * Ini tializes t his cipher with a ke y and a se t of algor ithm | |
1268 | * par ameters. | |
1269 | * | |
1270 | * <p> The cipher is initia lized for one of the following four oper ations: | |
1271 | * enc ryption, d ecryption, key wrapp ing or ke y unwrappi ng, depend ing | |
1272 | * on the value of <code>o pmode</cod e>. | |
1273 | * | |
1274 | * <p> If this ci pher requi res any al gorithm pa rameters a nd | |
1275 | * <co de>params< /code> is null, the underlying cipher im plementati on is | |
1276 | * sup posed to g enerate th e required parameter s itself ( using | |
1277 | * pro vider-spec ific defau lt or rand om values) if it is being | |
1278 | * ini tialized f or encrypt ion or key wrapping, and raise an | |
1279 | * <co de>Invalid AlgorithmP arameterEx ception</c ode> if it is being | |
1280 | * ini tialized f or decrypt ion or key unwrappin g. | |
1281 | * The generated parameter s can be r etrieved u sing | |
1282 | * {@l ink #getPa rameters() getParame ters} or | |
1283 | * {@l ink #getIV () getIV} (if the pa rameter is an IV). | |
1284 | * | |
1285 | * <p> If this ci pher requi res algori thm parame ters that cannot be | |
1286 | * der ived from the input parameters , and ther e are no r easonable | |
1287 | * pro vider-spec ific defau lt values, initializ ation will | |
1288 | * nec essarily f ail. | |
1289 | * | |
1290 | * <p> If this ci pher (incl uding its underlying feedback or padding scheme) | |
1291 | * req uires any random byt es (e.g., for parame ter genera tion), it will get | |
1292 | * the m using th e {@link j ava.securi ty.SecureR andom} | |
1293 | * imp lementatio n of the h ighest-pri ority | |
1294 | * ins talled pro vider as t he source of randomn ess. | |
1295 | * (If none of t he install ed provide rs supply an impleme ntation of | |
1296 | * Sec ureRandom, a system- provided s ource of r andomness will be us ed.) | |
1297 | * | |
1298 | * <p> Note that when a Cip her object is initia lized, it loses all | |
1299 | * pre viously-ac quired sta te. In oth er words, initializi ng a Ciphe r is | |
1300 | * equ ivalent to creating a new inst ance of th at Cipher and initia lizing | |
1301 | * it. | |
1302 | * | |
1303 | * @pa ram opmode the opera tion mode of this ci pher (this is one of the | |
1304 | * fol lowing: | |
1305 | * <co de>ENCRYPT _MODE</cod e>, <code> DECRYPT_MO DE</code>, | |
1306 | * <co de>WRAP_MO DE</code> or <code>U NWRAP_MODE </code>) | |
1307 | * @pa ram key th e encrypti on key | |
1308 | * @pa ram params the algor ithm param eters | |
1309 | * | |
1310 | * @ex ception In validKeyEx ception if the given key is in appropriat e for | |
1311 | * ini tializing this ciphe r, or its keysize ex ceeds the maximum al lowable | |
1312 | * key size (as d etermined from the c onfigured jurisdicti on policy files). | |
1313 | * @ex ception In validAlgor ithmParame terExcepti on if the given algo rithm | |
1314 | * par ameters ar e inapprop riate for this ciphe r, | |
1315 | * or this ciphe r requires | |
1316 | * alg orithm par ameters an d <code>pa rams</code > is null, or the gi ven | |
1317 | * alg orithm par ameters im ply a cryp tographic strength t hat would exceed | |
1318 | * the legal lim its (as de termined f rom the co nfigured j urisdictio n | |
1319 | * pol icy files) . | |
1320 | * @th rows Unsup portedOper ationExcep tion if (@ code opmod e} is | |
1321 | * {@c ode WRAP_M ODE} or {@ code UNWRA P_MODE} bu t the mode is not im plemented | |
1322 | * by the underl ying {@cod e CipherSp i}. | |
1323 | */ | |
1324 | public final voi d init(int opmode, K ey key, Al gorithmPar ameterSpec params) | |
1325 | throws I nvalidKeyE xception, InvalidAlg orithmPara meterExcep tion | |
1326 | { | |
1327 | in it(opmode, key, para ms, JceSec urity.RAND OM); | |
1328 | } | |
1329 | ||
1330 | /** | |
1331 | * Ini tializes t his cipher with a ke y, a set o f algorith m | |
1332 | * par ameters, a nd a sourc e of rando mness. | |
1333 | * | |
1334 | * <p> The cipher is initia lized for one of the following four oper ations: | |
1335 | * enc ryption, d ecryption, key wrapp ing or ke y unwrappi ng, depend ing | |
1336 | * on the value of <code>o pmode</cod e>. | |
1337 | * | |
1338 | * <p> If this ci pher requi res any al gorithm pa rameters a nd | |
1339 | * <co de>params< /code> is null, the underlying cipher im plementati on is | |
1340 | * sup posed to g enerate th e required parameter s itself ( using | |
1341 | * pro vider-spec ific defau lt or rand om values) if it is being | |
1342 | * ini tialized f or encrypt ion or key wrapping, and raise an | |
1343 | * <co de>Invalid AlgorithmP arameterEx ception</c ode> if it is being | |
1344 | * ini tialized f or decrypt ion or key unwrappin g. | |
1345 | * The generated parameter s can be r etrieved u sing | |
1346 | * {@l ink #getPa rameters() getParame ters} or | |
1347 | * {@l ink #getIV () getIV} (if the pa rameter is an IV). | |
1348 | * | |
1349 | * <p> If this ci pher requi res algori thm parame ters that cannot be | |
1350 | * der ived from the input parameters , and ther e are no r easonable | |
1351 | * pro vider-spec ific defau lt values, initializ ation will | |
1352 | * nec essarily f ail. | |
1353 | * | |
1354 | * <p> If this ci pher (incl uding its underlying feedback or padding scheme) | |
1355 | * req uires any random byt es (e.g., for parame ter genera tion), it will get | |
1356 | * the m from <co de>random< /code>. | |
1357 | * | |
1358 | * <p> Note that when a Cip her object is initia lized, it loses all | |
1359 | * pre viously-ac quired sta te. In oth er words, initializi ng a Ciphe r is | |
1360 | * equ ivalent to creating a new inst ance of th at Cipher and initia lizing | |
1361 | * it. | |
1362 | * | |
1363 | * @pa ram opmode the opera tion mode of this ci pher (this is one of the | |
1364 | * fol lowing: | |
1365 | * <co de>ENCRYPT _MODE</cod e>, <code> DECRYPT_MO DE</code>, | |
1366 | * <co de>WRAP_MO DE</code> or <code>U NWRAP_MODE </code>) | |
1367 | * @pa ram key th e encrypti on key | |
1368 | * @pa ram params the algor ithm param eters | |
1369 | * @pa ram random the sourc e of rando mness | |
1370 | * | |
1371 | * @ex ception In validKeyEx ception if the given key is in appropriat e for | |
1372 | * ini tializing this ciphe r, or its keysize ex ceeds the maximum al lowable | |
1373 | * key size (as d etermined from the c onfigured jurisdicti on policy files). | |
1374 | * @ex ception In validAlgor ithmParame terExcepti on if the given algo rithm | |
1375 | * par ameters ar e inapprop riate for this ciphe r, | |
1376 | * or this ciphe r requires | |
1377 | * alg orithm par ameters an d <code>pa rams</code > is null, or the gi ven | |
1378 | * alg orithm par ameters im ply a cryp tographic strength t hat would exceed | |
1379 | * the legal lim its (as de termined f rom the co nfigured j urisdictio n | |
1380 | * pol icy files) . | |
1381 | * @th rows Unsup portedOper ationExcep tion if (@ code opmod e} is | |
1382 | * {@c ode WRAP_M ODE} or {@ code UNWRA P_MODE} bu t the mode is not im plemented | |
1383 | * by the underl ying {@cod e CipherSp i}. | |
1384 | */ | |
1385 | public final voi d init(int opmode, K ey key, Al gorithmPar ameterSpec params, | |
1386 | Sec ureRandom random) | |
1387 | throws I nvalidKeyE xception, InvalidAlg orithmPara meterExcep tion | |
1388 | { | |
1389 | in itialized = false; | |
1390 | ch eckOpmode( opmode); | |
1391 | ||
1392 | if (spi != n ull) { | |
1393 | checkCry ptoPerm(sp i, key, pa rams); | |
1394 | spi.engi neInit(opm ode, key, params, ra ndom); | |
1395 | } else { | |
1396 | choosePr ovider(I_P ARAMSPEC, opmode, ke y, params, null, ran dom); | |
1397 | } | |
1398 | ||
1399 | in itialized = true; | |
1400 | th is.opmode = opmode; | |
1401 | ||
1402 | if (!skipDeb ug && pdeb ug != null ) { | |
1403 | pdebug.p rintln("Ci pher." + t ransformat ion + " " + | |
1404 | getO pmodeStrin g(opmode) + " algori thm from: " + | |
1405 | this .provider. getName()) ; | |
1406 | } | |
1407 | } | |
1408 | ||
1409 | /** | |
1410 | * Ini tializes t his cipher with a ke y and a se t of algor ithm | |
1411 | * par ameters. | |
1412 | * | |
1413 | * <p> The cipher is initia lized for one of the following four oper ations: | |
1414 | * enc ryption, d ecryption, key wrapp ing or ke y unwrappi ng, depend ing | |
1415 | * on the value of <code>o pmode</cod e>. | |
1416 | * | |
1417 | * <p> If this ci pher requi res any al gorithm pa rameters a nd | |
1418 | * <co de>params< /code> is null, the underlying cipher im plementati on is | |
1419 | * sup posed to g enerate th e required parameter s itself ( using | |
1420 | * pro vider-spec ific defau lt or rand om values) if it is being | |
1421 | * ini tialized f or encrypt ion or key wrapping, and raise an | |
1422 | * <co de>Invalid AlgorithmP arameterEx ception</c ode> if it is being | |
1423 | * ini tialized f or decrypt ion or key unwrappin g. | |
1424 | * The generated parameter s can be r etrieved u sing | |
1425 | * {@l ink #getPa rameters() getParame ters} or | |
1426 | * {@l ink #getIV () getIV} (if the pa rameter is an IV). | |
1427 | * | |
1428 | * <p> If this ci pher requi res algori thm parame ters that cannot be | |
1429 | * der ived from the input parameters , and ther e are no r easonable | |
1430 | * pro vider-spec ific defau lt values, initializ ation will | |
1431 | * nec essarily f ail. | |
1432 | * | |
1433 | * <p> If this ci pher (incl uding its underlying feedback or padding scheme) | |
1434 | * req uires any random byt es (e.g., for parame ter genera tion), it will get | |
1435 | * the m using th e {@link j ava.securi ty.SecureR andom} | |
1436 | * imp lementatio n of the h ighest-pri ority | |
1437 | * ins talled pro vider as t he source of randomn ess. | |
1438 | * (If none of t he install ed provide rs supply an impleme ntation of | |
1439 | * Sec ureRandom, a system- provided s ource of r andomness will be us ed.) | |
1440 | * | |
1441 | * <p> Note that when a Cip her object is initia lized, it loses all | |
1442 | * pre viously-ac quired sta te. In oth er words, initializi ng a Ciphe r is | |
1443 | * equ ivalent to creating a new inst ance of th at Cipher and initia lizing | |
1444 | * it. | |
1445 | * | |
1446 | * @pa ram opmode the opera tion mode of this ci pher (this is one of the | |
1447 | * fol lowing: <c ode>ENCRYP T_MODE</co de>, | |
1448 | * <co de>DECRYPT _MODE</cod e>, <code> WRAP_MODE< /code> | |
1449 | * or <code>UNWR AP_MODE</c ode>) | |
1450 | * @pa ram key th e encrypti on key | |
1451 | * @pa ram params the algor ithm param eters | |
1452 | * | |
1453 | * @ex ception In validKeyEx ception if the given key is in appropriat e for | |
1454 | * ini tializing this ciphe r, or its keysize ex ceeds the maximum al lowable | |
1455 | * key size (as d etermined from the c onfigured jurisdicti on policy files). | |
1456 | * @ex ception In validAlgor ithmParame terExcepti on if the given algo rithm | |
1457 | * par ameters ar e inapprop riate for this ciphe r, | |
1458 | * or this ciphe r requires | |
1459 | * alg orithm par ameters an d <code>pa rams</code > is null, or the gi ven | |
1460 | * alg orithm par ameters im ply a cryp tographic strength t hat would exceed | |
1461 | * the legal lim its (as de termined f rom the co nfigured j urisdictio n | |
1462 | * pol icy files) . | |
1463 | * @th rows Unsup portedOper ationExcep tion if (@ code opmod e} is | |
1464 | * {@c ode WRAP_M ODE} or {@ code UNWRA P_MODE} bu t the mode is not im plemented | |
1465 | * by the underl ying {@cod e CipherSp i}. | |
1466 | */ | |
1467 | public final voi d init(int opmode, K ey key, Al gorithmPar ameters pa rams) | |
1468 | throws I nvalidKeyE xception, InvalidAlg orithmPara meterExcep tion | |
1469 | { | |
1470 | in it(opmode, key, para ms, JceSec urity.RAND OM); | |
1471 | } | |
1472 | ||
1473 | /** | |
1474 | * Ini tializes t his cipher with a ke y, a set o f algorith m | |
1475 | * par ameters, a nd a sourc e of rando mness. | |
1476 | * | |
1477 | * <p> The cipher is initia lized for one of the following four oper ations: | |
1478 | * enc ryption, d ecryption, key wrapp ing or ke y unwrappi ng, depend ing | |
1479 | * on the value of <code>o pmode</cod e>. | |
1480 | * | |
1481 | * <p> If this ci pher requi res any al gorithm pa rameters a nd | |
1482 | * <co de>params< /code> is null, the underlying cipher im plementati on is | |
1483 | * sup posed to g enerate th e required parameter s itself ( using | |
1484 | * pro vider-spec ific defau lt or rand om values) if it is being | |
1485 | * ini tialized f or encrypt ion or key wrapping, and raise an | |
1486 | * <co de>Invalid AlgorithmP arameterEx ception</c ode> if it is being | |
1487 | * ini tialized f or decrypt ion or key unwrappin g. | |
1488 | * The generated parameter s can be r etrieved u sing | |
1489 | * {@l ink #getPa rameters() getParame ters} or | |
1490 | * {@l ink #getIV () getIV} (if the pa rameter is an IV). | |
1491 | * | |
1492 | * <p> If this ci pher requi res algori thm parame ters that cannot be | |
1493 | * der ived from the input parameters , and ther e are no r easonable | |
1494 | * pro vider-spec ific defau lt values, initializ ation will | |
1495 | * nec essarily f ail. | |
1496 | * | |
1497 | * <p> If this ci pher (incl uding its underlying feedback or padding scheme) | |
1498 | * req uires any random byt es (e.g., for parame ter genera tion), it will get | |
1499 | * the m from <co de>random< /code>. | |
1500 | * | |
1501 | * <p> Note that when a Cip her object is initia lized, it loses all | |
1502 | * pre viously-ac quired sta te. In oth er words, initializi ng a Ciphe r is | |
1503 | * equ ivalent to creating a new inst ance of th at Cipher and initia lizing | |
1504 | * it. | |
1505 | * | |
1506 | * @pa ram opmode the opera tion mode of this ci pher (this is one of the | |
1507 | * fol lowing: <c ode>ENCRYP T_MODE</co de>, | |
1508 | * <co de>DECRYPT _MODE</cod e>, <code> WRAP_MODE< /code> | |
1509 | * or <code>UNWR AP_MODE</c ode>) | |
1510 | * @pa ram key th e encrypti on key | |
1511 | * @pa ram params the algor ithm param eters | |
1512 | * @pa ram random the sourc e of rando mness | |
1513 | * | |
1514 | * @ex ception In validKeyEx ception if the given key is in appropriat e for | |
1515 | * ini tializing this ciphe r, or its keysize ex ceeds the maximum al lowable | |
1516 | * key size (as d etermined from the c onfigured jurisdicti on policy files). | |
1517 | * @ex ception In validAlgor ithmParame terExcepti on if the given algo rithm | |
1518 | * par ameters ar e inapprop riate for this ciphe r, | |
1519 | * or this ciphe r requires | |
1520 | * alg orithm par ameters an d <code>pa rams</code > is null, or the gi ven | |
1521 | * alg orithm par ameters im ply a cryp tographic strength t hat would exceed | |
1522 | * the legal lim its (as de termined f rom the co nfigured j urisdictio n | |
1523 | * pol icy files) . | |
1524 | * @th rows Unsup portedOper ationExcep tion if (@ code opmod e} is | |
1525 | * {@c ode WRAP_M ODE} or {@ code UNWRA P_MODE} bu t the mode is not im plemented | |
1526 | * by the underl ying {@cod e CipherSp i}. | |
1527 | */ | |
1528 | public final voi d init(int opmode, K ey key, Al gorithmPar ameters pa rams, | |
1529 | Sec ureRandom random) | |
1530 | throws I nvalidKeyE xception, InvalidAlg orithmPara meterExcep tion | |
1531 | { | |
1532 | in itialized = false; | |
1533 | ch eckOpmode( opmode); | |
1534 | ||
1535 | if (spi != n ull) { | |
1536 | checkCry ptoPerm(sp i, key, pa rams); | |
1537 | spi.engi neInit(opm ode, key, params, ra ndom); | |
1538 | } else { | |
1539 | choosePr ovider(I_P ARAMS, opm ode, key, null, para ms, random ); | |
1540 | } | |
1541 | ||
1542 | in itialized = true; | |
1543 | th is.opmode = opmode; | |
1544 | ||
1545 | if (!skipDeb ug && pdeb ug != null ) { | |
1546 | pdebug.p rintln("Ci pher." + t ransformat ion + " " + | |
1547 | getO pmodeStrin g(opmode) + " algori thm from: " + | |
1548 | this .provider. getName()) ; | |
1549 | } | |
1550 | } | |
1551 | ||
1552 | /** | |
1553 | * Ini tializes t his cipher with the public key from the given cert ificate. | |
1554 | * <p> The ciphe r is initi alized for one of th e followin g four ope rations: | |
1555 | * enc ryption, d ecryption, key wrapp ing or ke y unwrappi ng, depend ing | |
1556 | * on the value of <code>o pmode</cod e>. | |
1557 | * | |
1558 | * <p> If the cer tificate i s of type X.509 and has a <i>k ey usage</ i> | |
1559 | * ext ension fie ld marked as critica l, and the value of the <i>key usage</i> | |
1560 | * ext ension fie ld implies that the public key in | |
1561 | * the certifica te and its correspon ding priva te key are not | |
1562 | * sup posed to b e used for the opera tion repre sented by the value | |
1563 | * of <code>opmo de</code>, | |
1564 | * an <code>Inva lidKeyExce ption</cod e> | |
1565 | * is thrown. | |
1566 | * | |
1567 | * <p> If this c ipher requ ires any a lgorithm p arameters that canno t be | |
1568 | * der ived from the public key in th e given ce rtificate, the under lying | |
1569 | * cip her | |
1570 | * imp lementatio n is suppo sed to gen erate the required p arameters itself | |
1571 | * (us ing provid er-specifi c default or random values) if it is bei ng | |
1572 | * ini tialized f or encrypt ion or key wrapping, and raise an <code> | |
1573 | * Inv alidKeyExc eption</co de> if it is being i nitialized for decry ption or | |
1574 | * key unwrappin g. | |
1575 | * The generated parameter s can be r etrieved u sing | |
1576 | * {@l ink #getPa rameters() getParame ters} or | |
1577 | * {@l ink #getIV () getIV} (if the pa rameter is an IV). | |
1578 | * | |
1579 | * <p> If this ci pher requi res algori thm parame ters that cannot be | |
1580 | * der ived from the input parameters , and ther e are no r easonable | |
1581 | * pro vider-spec ific defau lt values, initializ ation will | |
1582 | * nec essarily f ail. | |
1583 | * | |
1584 | * <p> If this ci pher (incl uding its underlying feedback or padding scheme) | |
1585 | * req uires any random byt es (e.g., for parame ter genera tion), it will get | |
1586 | * the m using th e | |
1587 | * <co de>SecureR andom</cod e> | |
1588 | * imp lementatio n of the h ighest-pri ority | |
1589 | * ins talled pro vider as t he source of randomn ess. | |
1590 | * (If none of t he install ed provide rs supply an impleme ntation of | |
1591 | * Sec ureRandom, a system- provided s ource of r andomness will be us ed.) | |
1592 | * | |
1593 | * <p> Note that when a Cip her object is initia lized, it loses all | |
1594 | * pre viously-ac quired sta te. In oth er words, initializi ng a Ciphe r is | |
1595 | * equ ivalent to creating a new inst ance of th at Cipher and initia lizing | |
1596 | * it. | |
1597 | * | |
1598 | * @pa ram opmode the opera tion mode of this ci pher (this is one of the | |
1599 | * fol lowing: | |
1600 | * <co de>ENCRYPT _MODE</cod e>, <code> DECRYPT_MO DE</code>, | |
1601 | * <co de>WRAP_MO DE</code> or <code>U NWRAP_MODE </code>) | |
1602 | * @pa ram certif icate the certificat e | |
1603 | * | |
1604 | * @ex ception In validKeyEx ception if the publi c key in t he given | |
1605 | * cer tificate i s inapprop riate for initializi ng this ci pher, or t his | |
1606 | * cip her requir es algorit hm paramet ers that c annot be d etermined from the | |
1607 | * pub lic key in the given certifica te, or the keysize o f the publ ic key | |
1608 | * in the given certificat e has a ke ysize that exceeds t he maximum | |
1609 | * all owable key size (as d etermined by the con figured ju risdiction policy | |
1610 | * fil es). | |
1611 | * @th rows Unsup portedOper ationExcep tion if (@ code opmod e} is | |
1612 | * {@c ode WRAP_M ODE} or {@ code UNWRA P_MODE} bu t the mode is not im plemented | |
1613 | * by the underl ying {@cod e CipherSp i}. | |
1614 | */ | |
1615 | public final voi d init(int opmode, C ertificate certifica te) | |
1616 | throws I nvalidKeyE xception | |
1617 | { | |
1618 | in it(opmode, certifica te, JceSec urity.RAND OM); | |
1619 | } | |
1620 | ||
1621 | /** | |
1622 | * Ini tializes t his cipher with the public key from the given cert ificate | |
1623 | * and | |
1624 | * a s ource of r andomness. | |
1625 | * | |
1626 | * <p> The cipher is initia lized for one of the following four oper ations: | |
1627 | * enc ryption, d ecryption, key wrapp ing | |
1628 | * or key unwrap ping, depe nding on | |
1629 | * the value of <code>opmo de</code>. | |
1630 | * | |
1631 | * <p> If the cer tificate i s of type X.509 and has a <i>k ey usage</ i> | |
1632 | * ext ension fie ld marked as critica l, and the value of the <i>key usage</i> | |
1633 | * ext ension fie ld implies that the public key in | |
1634 | * the certifica te and its correspon ding priva te key are not | |
1635 | * sup posed to b e used for the opera tion repre sented by the value of | |
1636 | * <co de>opmode< /code>, | |
1637 | * an <code>Inva lidKeyExce ption</cod e> | |
1638 | * is thrown. | |
1639 | * | |
1640 | * <p> If this ci pher requi res any al gorithm pa rameters t hat cannot be | |
1641 | * der ived from the public key in th e given <c ode>certif icate</cod e>, | |
1642 | * the underlyin g cipher | |
1643 | * imp lementatio n is suppo sed to gen erate the required p arameters itself | |
1644 | * (us ing provid er-specifi c default or random values) if it is bei ng | |
1645 | * ini tialized f or encrypt ion or key wrapping, and raise an | |
1646 | * <co de>Invalid KeyExcepti on</code> if it is b eing | |
1647 | * ini tialized f or decrypt ion or key unwrappin g. | |
1648 | * The generated parameter s can be r etrieved u sing | |
1649 | * {@l ink #getPa rameters() getParame ters} or | |
1650 | * {@l ink #getIV () getIV} (if the pa rameter is an IV). | |
1651 | * | |
1652 | * <p> If this ci pher requi res algori thm parame ters that cannot be | |
1653 | * der ived from the input parameters , and ther e are no r easonable | |
1654 | * pro vider-spec ific defau lt values, initializ ation will | |
1655 | * nec essarily f ail. | |
1656 | * | |
1657 | * <p> If this ci pher (incl uding its underlying feedback or padding scheme) | |
1658 | * req uires any random byt es (e.g., for parame ter genera tion), it will get | |
1659 | * the m from <co de>random< /code>. | |
1660 | * | |
1661 | * <p> Note that when a Cip her object is initia lized, it loses all | |
1662 | * pre viously-ac quired sta te. In oth er words, initializi ng a Ciphe r is | |
1663 | * equ ivalent to creating a new inst ance of th at Cipher and initia lizing | |
1664 | * it. | |
1665 | * | |
1666 | * @pa ram opmode the opera tion mode of this ci pher (this is one of the | |
1667 | * fol lowing: | |
1668 | * <co de>ENCRYPT _MODE</cod e>, <code> DECRYPT_MO DE</code>, | |
1669 | * <co de>WRAP_MO DE</code> or <code>U NWRAP_MODE </code>) | |
1670 | * @pa ram certif icate the certificat e | |
1671 | * @pa ram random the sourc e of rando mness | |
1672 | * | |
1673 | * @ex ception In validKeyEx ception if the publi c key in t he given | |
1674 | * cer tificate i s inapprop riate for initializi ng this ci pher, or t his | |
1675 | * cip her | |
1676 | * req uires algo rithm para meters tha t cannot b e determin ed from th e | |
1677 | * pub lic key in the given certifica te, or the keysize o f the publ ic key | |
1678 | * in the given certificat e has a ke ysize that exceeds t he maximum | |
1679 | * all owable key size (as d etermined by the con figured ju risdiction policy | |
1680 | * fil es). | |
1681 | * @th rows Unsup portedOper ationExcep tion if (@ code opmod e} is | |
1682 | * {@c ode WRAP_M ODE} or {@ code UNWRA P_MODE} bu t the mode is not im plemented | |
1683 | * by the underl ying {@cod e CipherSp i}. | |
1684 | */ | |
1685 | public final voi d init(int opmode, C ertificate certifica te, | |
1686 | Sec ureRandom random) | |
1687 | throws I nvalidKeyE xception | |
1688 | { | |
1689 | in itialized = false; | |
1690 | ch eckOpmode( opmode); | |
1691 | ||
1692 | // Check key usage if the certif icate is o f | |
1693 | // type X.50 9. | |
1694 | if (certific ate instan ceof java. security.c ert.X509Ce rtificate) { | |
1695 | // Check whether t he cert ha s a key us age extens ion | |
1696 | // marke d as a cri tical exte nsion. | |
1697 | X509Cert ificate ce rt = (X509 Certificat e)certific ate; | |
1698 | Set<Stri ng> critSe t = cert.g etCritical ExtensionO IDs(); | |
1699 | ||
1700 | if (crit Set != nul l && !crit Set.isEmpt y() | |
1701 | && c ritSet.con tains(KEY_ USAGE_EXTE NSION_OID) ) { | |
1702 | bool ean[] keyU sageInfo = cert.getK eyUsage(); | |
1703 | // k eyUsageInf o[2] is fo r keyEncip herment; | |
1704 | // k eyUsageInf o[3] is fo r dataEnci pherment. | |
1705 | if ( (keyUsageI nfo != nul l) && | |
1706 | (((opmode == Cipher. ENCRYPT_MO DE) && | |
1707 | (keyUsag eInfo.leng th > 3) && | |
1708 | (keyUsag eInfo[3] = = false)) || | |
1709 | ((opmode == Cipher. WRAP_MODE) && | |
1710 | (keyUsag eInfo.leng th > 2) && | |
1711 | (keyUsag eInfo[2] = = false))) ) { | |
1712 | throw new InvalidKey Exception( "Wrong key usage"); | |
1713 | } | |
1714 | } | |
1715 | } | |
1716 | ||
1717 | Pu blicKey pu blicKey = | |
1718 | (certifi cate==null ? null:cer tificate.g etPublicKe y()); | |
1719 | ||
1720 | if (spi != n ull) { | |
1721 | checkCry ptoPerm(sp i, publicK ey); | |
1722 | spi.engi neInit(opm ode, publi cKey, rand om); | |
1723 | } else { | |
1724 | try { | |
1725 | choo seProvider (I_CERT, o pmode, pub licKey, nu ll, null, random); | |
1726 | } catch (InvalidAl gorithmPar ameterExce ption e) { | |
1727 | // s hould neve r occur | |
1728 | thro w new Inva lidKeyExce ption(e); | |
1729 | } | |
1730 | } | |
1731 | ||
1732 | in itialized = true; | |
1733 | th is.opmode = opmode; | |
1734 | ||
1735 | if (!skipDeb ug && pdeb ug != null ) { | |
1736 | pdebug.p rintln("Ci pher." + t ransformat ion + " " + | |
1737 | getO pmodeStrin g(opmode) + " algori thm from: " + | |
1738 | this .provider. getName()) ; | |
1739 | } | |
1740 | } | |
1741 | ||
1742 | /** | |
1743 | * Ens ures that Cipher is in a valid state for update() and doFina l() | |
1744 | * cal ls - shoul d be initi alized and in ENCRYP T_MODE or DECRYPT_MO DE. | |
1745 | * @th rows Illeg alStateExc eption if Cipher obj ect is not in valid state. | |
1746 | */ | |
1747 | privat e void che ckCipherSt ate() { | |
1748 | if (!(this i nstanceof NullCipher )) { | |
1749 | if (!ini tialized) { | |
1750 | thro w new Ille galStateEx ception("C ipher not initialize d"); | |
1751 | } | |
1752 | if ((opm ode != Cip her.ENCRYP T_MODE) && | |
1753 | (opm ode != Cip her.DECRYP T_MODE)) { | |
1754 | thro w new Ille galStateEx ception("C ipher not initialize d " + | |
1755 | "f or encrypt ion/decryp tion"); | |
1756 | } | |
1757 | } | |
1758 | } | |
1759 | ||
1760 | /** | |
1761 | * Con tinues a m ultiple-pa rt encrypt ion or dec ryption op eration | |
1762 | * (de pending on how this cipher was initializ ed), proce ssing anot her data | |
1763 | * par t. | |
1764 | * | |
1765 | * <p> The bytes in the <co de>input</ code> buff er are pro cessed, an d the | |
1766 | * res ult is sto red in a n ew buffer. | |
1767 | * | |
1768 | * <p> If <code>i nput</code > has a le ngth of ze ro, this m ethod retu rns | |
1769 | * <co de>null</c ode>. | |
1770 | * | |
1771 | * @pa ram input the input buffer | |
1772 | * | |
1773 | * @re turn the n ew buffer with the r esult, or null if th e underlyi ng | |
1774 | * cip her is a b lock ciphe r and the input data is too sh ort to res ult in a | |
1775 | * new block. | |
1776 | * | |
1777 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
1778 | * (e. g., has no t been ini tialized) | |
1779 | */ | |
1780 | public final byt e[] update (byte[] in put) { | |
1781 | ch eckCipherS tate(); | |
1782 | ||
1783 | // Input san ity check | |
1784 | if (input == null) { | |
1785 | throw ne w IllegalA rgumentExc eption("Nu ll input b uffer"); | |
1786 | } | |
1787 | ||
1788 | ch ooseFirstP rovider(); | |
1789 | if (input.le ngth == 0) { | |
1790 | return n ull; | |
1791 | } | |
1792 | re turn spi.e ngineUpdat e(input, 0 , input.le ngth); | |
1793 | } | |
1794 | ||
1795 | /** | |
1796 | * Con tinues a m ultiple-pa rt encrypt ion or dec ryption op eration | |
1797 | * (de pending on how this cipher was initializ ed), proce ssing anot her data | |
1798 | * par t. | |
1799 | * | |
1800 | * <p> The first <code>inpu tLen</code > bytes in the <code >input</co de> | |
1801 | * buf fer, start ing at <co de>inputOf fset</code > inclusiv e, are pro cessed, | |
1802 | * and the resul t is store d in a new buffer. | |
1803 | * | |
1804 | * <p> If <code>i nputLen</c ode> is ze ro, this m ethod retu rns | |
1805 | * <co de>null</c ode>. | |
1806 | * | |
1807 | * @pa ram input the input buffer | |
1808 | * @pa ram inputO ffset the offset in <code>inpu t</code> w here the i nput | |
1809 | * sta rts | |
1810 | * @pa ram inputL en the inp ut length | |
1811 | * | |
1812 | * @re turn the n ew buffer with the r esult, or null if th e underlyi ng | |
1813 | * cip her is a b lock ciphe r and the input data is too sh ort to res ult in a | |
1814 | * new block. | |
1815 | * | |
1816 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
1817 | * (e. g., has no t been ini tialized) | |
1818 | */ | |
1819 | public final byt e[] update (byte[] in put, int i nputOffset , int inpu tLen) { | |
1820 | ch eckCipherS tate(); | |
1821 | ||
1822 | // Input san ity check | |
1823 | if (input == null || i nputOffset < 0 | |
1824 | || input Len > (inp ut.length - inputOff set) || in putLen < 0 ) { | |
1825 | throw ne w IllegalA rgumentExc eption("Ba d argument s"); | |
1826 | } | |
1827 | ||
1828 | ch ooseFirstP rovider(); | |
1829 | if (inputLen == 0) { | |
1830 | return n ull; | |
1831 | } | |
1832 | re turn spi.e ngineUpdat e(input, i nputOffset , inputLen ); | |
1833 | } | |
1834 | ||
1835 | /** | |
1836 | * Con tinues a m ultiple-pa rt encrypt ion or dec ryption op eration | |
1837 | * (de pending on how this cipher was initializ ed), proce ssing anot her data | |
1838 | * par t. | |
1839 | * | |
1840 | * <p> The first <code>inpu tLen</code > bytes in the <code >input</co de> | |
1841 | * buf fer, start ing at <co de>inputOf fset</code > inclusiv e, are pro cessed, | |
1842 | * and the resul t is store d in the < code>outpu t</code> b uffer. | |
1843 | * | |
1844 | * <p> If the <co de>output< /code> buf fer is too small to hold the r esult, | |
1845 | * a < code>Short BufferExce ption</cod e> is thro wn. In thi s case, re peat this | |
1846 | * cal l with a l arger outp ut buffer. Use | |
1847 | * {@l ink #getOu tputSize(i nt) getOut putSize} t o determin e how big | |
1848 | * the output bu ffer shoul d be. | |
1849 | * | |
1850 | * <p> If <code>i nputLen</c ode> is ze ro, this m ethod retu rns | |
1851 | * a l ength of z ero. | |
1852 | * | |
1853 | * <p> Note: this method sh ould be co py-safe, w hich means the | |
1854 | * <co de>input</ code> and <code>outp ut</code> buffers ca n referenc e | |
1855 | * the same byte array and no unproc essed inpu t data is overwritte n | |
1856 | * whe n the resu lt is copi ed into th e output b uffer. | |
1857 | * | |
1858 | * @pa ram input the input buffer | |
1859 | * @pa ram inputO ffset the offset in <code>inpu t</code> w here the i nput | |
1860 | * sta rts | |
1861 | * @pa ram inputL en the inp ut length | |
1862 | * @pa ram output the buffe r for the result | |
1863 | * | |
1864 | * @re turn the n umber of b ytes store d in <code >output</c ode> | |
1865 | * | |
1866 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
1867 | * (e. g., has no t been ini tialized) | |
1868 | * @ex ception Sh ortBufferE xception i f the give n output b uffer is t oo small | |
1869 | * to hold the r esult | |
1870 | */ | |
1871 | public final int update(by te[] input , int inpu tOffset, i nt inputLe n, | |
1872 | by te[] outpu t) | |
1873 | throws S hortBuffer Exception { | |
1874 | ch eckCipherS tate(); | |
1875 | ||
1876 | // Input san ity check | |
1877 | if (input == null || i nputOffset < 0 | |
1878 | || input Len > (inp ut.length - inputOff set) || in putLen < 0 ) { | |
1879 | throw ne w IllegalA rgumentExc eption("Ba d argument s"); | |
1880 | } | |
1881 | ||
1882 | ch ooseFirstP rovider(); | |
1883 | if (inputLen == 0) { | |
1884 | return 0 ; | |
1885 | } | |
1886 | re turn spi.e ngineUpdat e(input, i nputOffset , inputLen , | |
1887 | ou tput, 0); | |
1888 | } | |
1889 | ||
1890 | /** | |
1891 | * Con tinues a m ultiple-pa rt encrypt ion or dec ryption op eration | |
1892 | * (de pending on how this cipher was initializ ed), proce ssing anot her data | |
1893 | * par t. | |
1894 | * | |
1895 | * <p> The first <code>inpu tLen</code > bytes in the <code >input</co de> | |
1896 | * buf fer, start ing at <co de>inputOf fset</code > inclusiv e, are pro cessed, | |
1897 | * and the resul t is store d in the < code>outpu t</code> b uffer, sta rting at | |
1898 | * <co de>outputO ffset</cod e> inclusi ve. | |
1899 | * | |
1900 | * <p> If the <co de>output< /code> buf fer is too small to hold the r esult, | |
1901 | * a < code>Short BufferExce ption</cod e> is thro wn. In thi s case, re peat this | |
1902 | * cal l with a l arger outp ut buffer. Use | |
1903 | * {@l ink #getOu tputSize(i nt) getOut putSize} t o determin e how big | |
1904 | * the output bu ffer shoul d be. | |
1905 | * | |
1906 | * <p> If <code>i nputLen</c ode> is ze ro, this m ethod retu rns | |
1907 | * a l ength of z ero. | |
1908 | * | |
1909 | * <p> Note: this method sh ould be co py-safe, w hich means the | |
1910 | * <co de>input</ code> and <code>outp ut</code> buffers ca n referenc e | |
1911 | * the same byte array and no unproc essed inpu t data is overwritte n | |
1912 | * whe n the resu lt is copi ed into th e output b uffer. | |
1913 | * | |
1914 | * @pa ram input the input buffer | |
1915 | * @pa ram inputO ffset the offset in <code>inpu t</code> w here the i nput | |
1916 | * sta rts | |
1917 | * @pa ram inputL en the inp ut length | |
1918 | * @pa ram output the buffe r for the result | |
1919 | * @pa ram output Offset the offset in <code>out put</code> where the result | |
1920 | * is stored | |
1921 | * | |
1922 | * @re turn the n umber of b ytes store d in <code >output</c ode> | |
1923 | * | |
1924 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
1925 | * (e. g., has no t been ini tialized) | |
1926 | * @ex ception Sh ortBufferE xception i f the give n output b uffer is t oo small | |
1927 | * to hold the r esult | |
1928 | */ | |
1929 | public final int update(by te[] input , int inpu tOffset, i nt inputLe n, | |
1930 | by te[] outpu t, int out putOffset) | |
1931 | throws S hortBuffer Exception { | |
1932 | ch eckCipherS tate(); | |
1933 | ||
1934 | // Input san ity check | |
1935 | if (input == null || i nputOffset < 0 | |
1936 | || input Len > (inp ut.length - inputOff set) || in putLen < 0 | |
1937 | || outpu tOffset < 0) { | |
1938 | throw ne w IllegalA rgumentExc eption("Ba d argument s"); | |
1939 | } | |
1940 | ||
1941 | ch ooseFirstP rovider(); | |
1942 | if (inputLen == 0) { | |
1943 | return 0 ; | |
1944 | } | |
1945 | re turn spi.e ngineUpdat e(input, i nputOffset , inputLen , | |
1946 | ou tput, outp utOffset); | |
1947 | } | |
1948 | ||
1949 | /** | |
1950 | * Con tinues a m ultiple-pa rt encrypt ion or dec ryption op eration | |
1951 | * (de pending on how this cipher was initializ ed), proce ssing anot her data | |
1952 | * par t. | |
1953 | * | |
1954 | * <p> All <code> input.rema ining()</c ode> bytes starting at | |
1955 | * <co de>input.p osition()< /code> are processed . The resu lt is stor ed | |
1956 | * in the output buffer. | |
1957 | * Upo n return, the input buffer's p osition wi ll be equa l | |
1958 | * to its limit; its limit will not have chang ed. The ou tput buffe r's | |
1959 | * pos ition will have adva nced by n, where n i s the valu e returned | |
1960 | * by this metho d; the out put buffer 's limit w ill not ha ve changed . | |
1961 | * | |
1962 | * <p> If <code>o utput.rema ining()</c ode> bytes are insuf ficient to | |
1963 | * hol d the resu lt, a <cod e>ShortBuf ferExcepti on</code> is thrown. | |
1964 | * In this case, repeat th is call wi th a large r output b uffer. Use | |
1965 | * {@l ink #getOu tputSize(i nt) getOut putSize} t o determin e how big | |
1966 | * the output bu ffer shoul d be. | |
1967 | * | |
1968 | * <p> Note: this method sh ould be co py-safe, w hich means the | |
1969 | * <co de>input</ code> and <code>outp ut</code> buffers ca n referenc e | |
1970 | * the same bloc k of memor y and no u nprocessed input dat a is overw ritten | |
1971 | * whe n the resu lt is copi ed into th e output b uffer. | |
1972 | * | |
1973 | * @pa ram input the input ByteBuffer | |
1974 | * @pa ram output the outpu t ByteByff er | |
1975 | * | |
1976 | * @re turn the n umber of b ytes store d in <code >output</c ode> | |
1977 | * | |
1978 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
1979 | * (e. g., has no t been ini tialized) | |
1980 | * @ex ception Il legalArgum entExcepti on if inpu t and outp ut are the | |
1981 | * s ame object | |
1982 | * @ex ception Re adOnlyBuff erExceptio n if the o utput buff er is read -only | |
1983 | * @ex ception Sh ortBufferE xception i f there is insuffici ent space in the | |
1984 | * out put buffer | |
1985 | * @si nce 1.5 | |
1986 | */ | |
1987 | public final int update(By teBuffer i nput, Byte Buffer out put) | |
1988 | throws S hortBuffer Exception { | |
1989 | ch eckCipherS tate(); | |
1990 | ||
1991 | if ((input = = null) || (output = = null)) { | |
1992 | throw ne w IllegalA rgumentExc eption("Bu ffers must not be nu ll"); | |
1993 | } | |
1994 | if (input == output) { | |
1995 | throw ne w IllegalA rgumentExc eption("In put and ou tput buffe rs must " | |
1996 | + "n ot be the same objec t, conside r using bu ffer.dupli cate()"); | |
1997 | } | |
1998 | if (output.i sReadOnly( )) { | |
1999 | throw ne w ReadOnly BufferExce ption(); | |
2000 | } | |
2001 | ||
2002 | ch ooseFirstP rovider(); | |
2003 | re turn spi.e ngineUpdat e(input, o utput); | |
2004 | } | |
2005 | ||
2006 | /** | |
2007 | * Fin ishes a mu ltiple-par t encrypti on or decr yption ope ration, de pending | |
2008 | * on how this c ipher was initialize d. | |
2009 | * | |
2010 | * <p> Input data that may have been buffered d uring a pr evious | |
2011 | * <co de>update< /code> ope ration is processed, with padd ing (if re quested) | |
2012 | * bei ng applied . | |
2013 | * If an AEAD mo de such as GCM/CCM i s being us ed, the au thenticati on | |
2014 | * tag is append ed in the case of en cryption, or verifie d in the | |
2015 | * cas e of decry ption. | |
2016 | * The result is stored in a new buf fer. | |
2017 | * | |
2018 | * <p> Upon finis hing, this method re sets this cipher obj ect to the state | |
2019 | * it was in whe n previous ly initial ized via a call to < code>init< /code>. | |
2020 | * Tha t is, the object is reset and available to encrypt or decryp t | |
2021 | * (de pending on the opera tion mode that was s pecified i n the call to | |
2022 | * <co de>init</c ode>) more data. | |
2023 | * | |
2024 | * <p> Note: if a ny excepti on is thro wn, this c ipher obje ct may nee d to | |
2025 | * be reset befo re it can be used ag ain. | |
2026 | * | |
2027 | * @re turn the n ew buffer with the r esult | |
2028 | * | |
2029 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
2030 | * (e. g., has no t been ini tialized) | |
2031 | * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block cipher, | |
2032 | * no padding ha s been req uested (on ly in encr yption mod e), and th e total | |
2033 | * inp ut length of the dat a processe d by this cipher is not a mult iple of | |
2034 | * blo ck size; o r if this encryption algorithm is unable to | |
2035 | * pro cess the i nput data provided. | |
2036 | * @ex ception Ba dPaddingEx ception if this ciph er is in d ecryption mode, | |
2037 | * and (un)paddi ng has bee n requeste d, but the decrypted data is n ot | |
2038 | * bou nded by th e appropri ate paddin g bytes | |
2039 | * @ex ception AE ADBadTagEx ception if this ciph er is decr ypting in an | |
2040 | * AEA D mode (su ch as GCM/ CCM), and the receiv ed authent ication ta g | |
2041 | * doe s not matc h the calc ulated val ue | |
2042 | */ | |
2043 | public final byt e[] doFina l() | |
2044 | throws I llegalBloc kSizeExcep tion, BadP addingExce ption { | |
2045 | ch eckCipherS tate(); | |
2046 | ||
2047 | ch ooseFirstP rovider(); | |
2048 | re turn spi.e ngineDoFin al(null, 0 , 0); | |
2049 | } | |
2050 | ||
2051 | /** | |
2052 | * Fin ishes a mu ltiple-par t encrypti on or decr yption ope ration, de pending | |
2053 | * on how this c ipher was initialize d. | |
2054 | * | |
2055 | * <p> Input data that may have been buffered d uring a pr evious | |
2056 | * <co de>update< /code> ope ration is processed, with padd ing (if re quested) | |
2057 | * bei ng applied . | |
2058 | * If an AEAD mo de such as GCM/CCM i s being us ed, the au thenticati on | |
2059 | * tag is append ed in the case of en cryption, or verifie d in the | |
2060 | * cas e of decry ption. | |
2061 | * The result is stored in the <code >output</c ode> buffe r, startin g at | |
2062 | * <co de>outputO ffset</cod e> inclusi ve. | |
2063 | * | |
2064 | * <p> If the <co de>output< /code> buf fer is too small to hold the r esult, | |
2065 | * a < code>Short BufferExce ption</cod e> is thro wn. In thi s case, re peat this | |
2066 | * cal l with a l arger outp ut buffer. Use | |
2067 | * {@l ink #getOu tputSize(i nt) getOut putSize} t o determin e how big | |
2068 | * the output bu ffer shoul d be. | |
2069 | * | |
2070 | * <p> Upon finis hing, this method re sets this cipher obj ect to the state | |
2071 | * it was in whe n previous ly initial ized via a call to < code>init< /code>. | |
2072 | * Tha t is, the object is reset and available to encrypt or decryp t | |
2073 | * (de pending on the opera tion mode that was s pecified i n the call to | |
2074 | * <co de>init</c ode>) more data. | |
2075 | * | |
2076 | * <p> Note: if a ny excepti on is thro wn, this c ipher obje ct may nee d to | |
2077 | * be reset befo re it can be used ag ain. | |
2078 | * | |
2079 | * @pa ram output the buffe r for the result | |
2080 | * @pa ram output Offset the offset in <code>out put</code> where the result | |
2081 | * is stored | |
2082 | * | |
2083 | * @re turn the n umber of b ytes store d in <code >output</c ode> | |
2084 | * | |
2085 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
2086 | * (e. g., has no t been ini tialized) | |
2087 | * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block cipher, | |
2088 | * no padding ha s been req uested (on ly in encr yption mod e), and th e total | |
2089 | * inp ut length of the dat a processe d by this cipher is not a mult iple of | |
2090 | * blo ck size; o r if this encryption algorithm is unable to | |
2091 | * pro cess the i nput data provided. | |
2092 | * @ex ception Sh ortBufferE xception i f the give n output b uffer is t oo small | |
2093 | * to hold the r esult | |
2094 | * @ex ception Ba dPaddingEx ception if this ciph er is in d ecryption mode, | |
2095 | * and (un)paddi ng has bee n requeste d, but the decrypted data is n ot | |
2096 | * bou nded by th e appropri ate paddin g bytes | |
2097 | * @ex ception AE ADBadTagEx ception if this ciph er is decr ypting in an | |
2098 | * AEA D mode (su ch as GCM/ CCM), and the receiv ed authent ication ta g | |
2099 | * doe s not matc h the calc ulated val ue | |
2100 | */ | |
2101 | public final int doFinal(b yte[] outp ut, int ou tputOffset ) | |
2102 | throws I llegalBloc kSizeExcep tion, Shor tBufferExc eption, | |
2103 | BadPa ddingExcep tion { | |
2104 | ch eckCipherS tate(); | |
2105 | ||
2106 | // Input san ity check | |
2107 | if ((output == null) | | (outputO ffset < 0) ) { | |
2108 | throw ne w IllegalA rgumentExc eption("Ba d argument s"); | |
2109 | } | |
2110 | ||
2111 | ch ooseFirstP rovider(); | |
2112 | re turn spi.e ngineDoFin al(null, 0 , 0, outpu t, outputO ffset); | |
2113 | } | |
2114 | ||
2115 | /** | |
2116 | * Enc rypts or d ecrypts da ta in a si ngle-part operation, or finish es a | |
2117 | * mul tiple-part operation . The data is encryp ted or dec rypted, | |
2118 | * dep ending on how this c ipher was initialize d. | |
2119 | * | |
2120 | * <p> The bytes in the <co de>input</ code> buff er, and an y input by tes that | |
2121 | * may have been buffered during a p revious <c ode>update </code> op eration, | |
2122 | * are processed , with pad ding (if r equested) being appl ied. | |
2123 | * If an AEAD mo de such as GCM/CCM i s being us ed, the au thenticati on | |
2124 | * tag is append ed in the case of en cryption, or verifie d in the | |
2125 | * cas e of decry ption. | |
2126 | * The result is stored in a new buf fer. | |
2127 | * | |
2128 | * <p> Upon finis hing, this method re sets this cipher obj ect to the state | |
2129 | * it was in whe n previous ly initial ized via a call to < code>init< /code>. | |
2130 | * Tha t is, the object is reset and available to encrypt or decryp t | |
2131 | * (de pending on the opera tion mode that was s pecified i n the call to | |
2132 | * <co de>init</c ode>) more data. | |
2133 | * | |
2134 | * <p> Note: if a ny excepti on is thro wn, this c ipher obje ct may nee d to | |
2135 | * be reset befo re it can be used ag ain. | |
2136 | * | |
2137 | * @pa ram input the input buffer | |
2138 | * | |
2139 | * @re turn the n ew buffer with the r esult | |
2140 | * | |
2141 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
2142 | * (e. g., has no t been ini tialized) | |
2143 | * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block cipher, | |
2144 | * no padding ha s been req uested (on ly in encr yption mod e), and th e total | |
2145 | * inp ut length of the dat a processe d by this cipher is not a mult iple of | |
2146 | * blo ck size; o r if this encryption algorithm is unable to | |
2147 | * pro cess the i nput data provided. | |
2148 | * @ex ception Ba dPaddingEx ception if this ciph er is in d ecryption mode, | |
2149 | * and (un)paddi ng has bee n requeste d, but the decrypted data is n ot | |
2150 | * bou nded by th e appropri ate paddin g bytes | |
2151 | * @ex ception AE ADBadTagEx ception if this ciph er is decr ypting in an | |
2152 | * AEA D mode (su ch as GCM/ CCM), and the receiv ed authent ication ta g | |
2153 | * doe s not matc h the calc ulated val ue | |
2154 | */ | |
2155 | public final byt e[] doFina l(byte[] i nput) | |
2156 | throws I llegalBloc kSizeExcep tion, BadP addingExce ption { | |
2157 | ch eckCipherS tate(); | |
2158 | ||
2159 | // Input san ity check | |
2160 | if (input == null) { | |
2161 | throw ne w IllegalA rgumentExc eption("Nu ll input b uffer"); | |
2162 | } | |
2163 | ||
2164 | ch ooseFirstP rovider(); | |
2165 | re turn spi.e ngineDoFin al(input, 0, input.l ength); | |
2166 | } | |
2167 | ||
2168 | /** | |
2169 | * Enc rypts or d ecrypts da ta in a si ngle-part operation, or finish es a | |
2170 | * mul tiple-part operation . The data is encryp ted or dec rypted, | |
2171 | * dep ending on how this c ipher was initialize d. | |
2172 | * | |
2173 | * <p> The first <code>inpu tLen</code > bytes in the <code >input</co de> | |
2174 | * buf fer, start ing at <co de>inputOf fset</code > inclusiv e, and any input | |
2175 | * byt es that ma y have bee n buffered during a previous < code>updat e</code> | |
2176 | * ope ration, ar e processe d, with pa dding (if requested) being app lied. | |
2177 | * If an AEAD mo de such as GCM/CCM i s being us ed, the au thenticati on | |
2178 | * tag is append ed in the case of en cryption, or verifie d in the | |
2179 | * cas e of decry ption. | |
2180 | * The result is stored in a new buf fer. | |
2181 | * | |
2182 | * <p> Upon finis hing, this method re sets this cipher obj ect to the state | |
2183 | * it was in whe n previous ly initial ized via a call to < code>init< /code>. | |
2184 | * Tha t is, the object is reset and available to encrypt or decryp t | |
2185 | * (de pending on the opera tion mode that was s pecified i n the call to | |
2186 | * <co de>init</c ode>) more data. | |
2187 | * | |
2188 | * <p> Note: if a ny excepti on is thro wn, this c ipher obje ct may nee d to | |
2189 | * be reset befo re it can be used ag ain. | |
2190 | * | |
2191 | * @pa ram input the input buffer | |
2192 | * @pa ram inputO ffset the offset in <code>inpu t</code> w here the i nput | |
2193 | * sta rts | |
2194 | * @pa ram inputL en the inp ut length | |
2195 | * | |
2196 | * @re turn the n ew buffer with the r esult | |
2197 | * | |
2198 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
2199 | * (e. g., has no t been ini tialized) | |
2200 | * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block cipher, | |
2201 | * no padding ha s been req uested (on ly in encr yption mod e), and th e total | |
2202 | * inp ut length of the dat a processe d by this cipher is not a mult iple of | |
2203 | * blo ck size; o r if this encryption algorithm is unable to | |
2204 | * pro cess the i nput data provided. | |
2205 | * @ex ception Ba dPaddingEx ception if this ciph er is in d ecryption mode, | |
2206 | * and (un)paddi ng has bee n requeste d, but the decrypted data is n ot | |
2207 | * bou nded by th e appropri ate paddin g bytes | |
2208 | * @ex ception AE ADBadTagEx ception if this ciph er is decr ypting in an | |
2209 | * AEA D mode (su ch as GCM/ CCM), and the receiv ed authent ication ta g | |
2210 | * doe s not matc h the calc ulated val ue | |
2211 | */ | |
2212 | public final byt e[] doFina l(byte[] i nput, int inputOffse t, int inp utLen) | |
2213 | throws I llegalBloc kSizeExcep tion, BadP addingExce ption { | |
2214 | ch eckCipherS tate(); | |
2215 | ||
2216 | // Input san ity check | |
2217 | if (input == null || i nputOffset < 0 | |
2218 | || input Len > (inp ut.length - inputOff set) || in putLen < 0 ) { | |
2219 | throw ne w IllegalA rgumentExc eption("Ba d argument s"); | |
2220 | } | |
2221 | ||
2222 | ch ooseFirstP rovider(); | |
2223 | re turn spi.e ngineDoFin al(input, inputOffse t, inputLe n); | |
2224 | } | |
2225 | ||
2226 | /** | |
2227 | * Enc rypts or d ecrypts da ta in a si ngle-part operation, or finish es a | |
2228 | * mul tiple-part operation . The data is encryp ted or dec rypted, | |
2229 | * dep ending on how this c ipher was initialize d. | |
2230 | * | |
2231 | * <p> The first <code>inpu tLen</code > bytes in the <code >input</co de> | |
2232 | * buf fer, start ing at <co de>inputOf fset</code > inclusiv e, and any input | |
2233 | * byt es that ma y have bee n buffered during a previous < code>updat e</code> | |
2234 | * ope ration, ar e processe d, with pa dding (if requested) being app lied. | |
2235 | * If an AEAD mo de such as GCM/CCM i s being us ed, the au thenticati on | |
2236 | * tag is append ed in the case of en cryption, or verifie d in the | |
2237 | * cas e of decry ption. | |
2238 | * The result is stored in the <code >output</c ode> buffe r. | |
2239 | * | |
2240 | * <p> If the <co de>output< /code> buf fer is too small to hold the r esult, | |
2241 | * a < code>Short BufferExce ption</cod e> is thro wn. In thi s case, re peat this | |
2242 | * cal l with a l arger outp ut buffer. Use | |
2243 | * {@l ink #getOu tputSize(i nt) getOut putSize} t o determin e how big | |
2244 | * the output bu ffer shoul d be. | |
2245 | * | |
2246 | * <p> Upon finis hing, this method re sets this cipher obj ect to the state | |
2247 | * it was in whe n previous ly initial ized via a call to < code>init< /code>. | |
2248 | * Tha t is, the object is reset and available to encrypt or decryp t | |
2249 | * (de pending on the opera tion mode that was s pecified i n the call to | |
2250 | * <co de>init</c ode>) more data. | |
2251 | * | |
2252 | * <p> Note: if a ny excepti on is thro wn, this c ipher obje ct may nee d to | |
2253 | * be reset befo re it can be used ag ain. | |
2254 | * | |
2255 | * <p> Note: this method sh ould be co py-safe, w hich means the | |
2256 | * <co de>input</ code> and <code>outp ut</code> buffers ca n referenc e | |
2257 | * the same byte array and no unproc essed inpu t data is overwritte n | |
2258 | * whe n the resu lt is copi ed into th e output b uffer. | |
2259 | * | |
2260 | * @pa ram input the input buffer | |
2261 | * @pa ram inputO ffset the offset in <code>inpu t</code> w here the i nput | |
2262 | * sta rts | |
2263 | * @pa ram inputL en the inp ut length | |
2264 | * @pa ram output the buffe r for the result | |
2265 | * | |
2266 | * @re turn the n umber of b ytes store d in <code >output</c ode> | |
2267 | * | |
2268 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
2269 | * (e. g., has no t been ini tialized) | |
2270 | * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block cipher, | |
2271 | * no padding ha s been req uested (on ly in encr yption mod e), and th e total | |
2272 | * inp ut length of the dat a processe d by this cipher is not a mult iple of | |
2273 | * blo ck size; o r if this encryption algorithm is unable to | |
2274 | * pro cess the i nput data provided. | |
2275 | * @ex ception Sh ortBufferE xception i f the give n output b uffer is t oo small | |
2276 | * to hold the r esult | |
2277 | * @ex ception Ba dPaddingEx ception if this ciph er is in d ecryption mode, | |
2278 | * and (un)paddi ng has bee n requeste d, but the decrypted data is n ot | |
2279 | * bou nded by th e appropri ate paddin g bytes | |
2280 | * @ex ception AE ADBadTagEx ception if this ciph er is decr ypting in an | |
2281 | * AEA D mode (su ch as GCM/ CCM), and the receiv ed authent ication ta g | |
2282 | * doe s not matc h the calc ulated val ue | |
2283 | */ | |
2284 | public final int doFinal(b yte[] inpu t, int inp utOffset, int inputL en, | |
2285 | b yte[] outp ut) | |
2286 | throws S hortBuffer Exception, IllegalBl ockSizeExc eption, | |
2287 | BadPaddi ngExceptio n { | |
2288 | ch eckCipherS tate(); | |
2289 | ||
2290 | // Input san ity check | |
2291 | if (input == null || i nputOffset < 0 | |
2292 | || input Len > (inp ut.length - inputOff set) || in putLen < 0 ) { | |
2293 | throw ne w IllegalA rgumentExc eption("Ba d argument s"); | |
2294 | } | |
2295 | ||
2296 | ch ooseFirstP rovider(); | |
2297 | re turn spi.e ngineDoFin al(input, inputOffse t, inputLe n, | |
2298 | o utput, 0); | |
2299 | } | |
2300 | ||
2301 | /** | |
2302 | * Enc rypts or d ecrypts da ta in a si ngle-part operation, or finish es a | |
2303 | * mul tiple-part operation . The data is encryp ted or dec rypted, | |
2304 | * dep ending on how this c ipher was initialize d. | |
2305 | * | |
2306 | * <p> The first <code>inpu tLen</code > bytes in the <code >input</co de> | |
2307 | * buf fer, start ing at <co de>inputOf fset</code > inclusiv e, and any input | |
2308 | * byt es that ma y have bee n buffered during a previous | |
2309 | * <co de>update< /code> ope ration, ar e processe d, with pa dding | |
2310 | * (if requested ) being ap plied. | |
2311 | * If an AEAD mo de such as GCM/CCM i s being us ed, the au thenticati on | |
2312 | * tag is append ed in the case of en cryption, or verifie d in the | |
2313 | * cas e of decry ption. | |
2314 | * The result is stored in the <code >output</c ode> buffe r, startin g at | |
2315 | * <co de>outputO ffset</cod e> inclusi ve. | |
2316 | * | |
2317 | * <p> If the <co de>output< /code> buf fer is too small to hold the r esult, | |
2318 | * a < code>Short BufferExce ption</cod e> is thro wn. In thi s case, re peat this | |
2319 | * cal l with a l arger outp ut buffer. Use | |
2320 | * {@l ink #getOu tputSize(i nt) getOut putSize} t o determin e how big | |
2321 | * the output bu ffer shoul d be. | |
2322 | * | |
2323 | * <p> Upon finis hing, this method re sets this cipher obj ect to the state | |
2324 | * it was in whe n previous ly initial ized via a call to < code>init< /code>. | |
2325 | * Tha t is, the object is reset and available to encrypt or decryp t | |
2326 | * (de pending on the opera tion mode that was s pecified i n the call to | |
2327 | * <co de>init</c ode>) more data. | |
2328 | * | |
2329 | * <p> Note: if a ny excepti on is thro wn, this c ipher obje ct may nee d to | |
2330 | * be reset befo re it can be used ag ain. | |
2331 | * | |
2332 | * <p> Note: this method sh ould be co py-safe, w hich means the | |
2333 | * <co de>input</ code> and <code>outp ut</code> buffers ca n referenc e | |
2334 | * the same byte array and no unproc essed inpu t data is overwritte n | |
2335 | * whe n the resu lt is copi ed into th e output b uffer. | |
2336 | * | |
2337 | * @pa ram input the input buffer | |
2338 | * @pa ram inputO ffset the offset in <code>inpu t</code> w here the i nput | |
2339 | * sta rts | |
2340 | * @pa ram inputL en the inp ut length | |
2341 | * @pa ram output the buffe r for the result | |
2342 | * @pa ram output Offset the offset in <code>out put</code> where the result | |
2343 | * is stored | |
2344 | * | |
2345 | * @re turn the n umber of b ytes store d in <code >output</c ode> | |
2346 | * | |
2347 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
2348 | * (e. g., has no t been ini tialized) | |
2349 | * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block cipher, | |
2350 | * no padding ha s been req uested (on ly in encr yption mod e), and th e total | |
2351 | * inp ut length of the dat a processe d by this cipher is not a mult iple of | |
2352 | * blo ck size; o r if this encryption algorithm is unable to | |
2353 | * pro cess the i nput data provided. | |
2354 | * @ex ception Sh ortBufferE xception i f the give n output b uffer is t oo small | |
2355 | * to hold the r esult | |
2356 | * @ex ception Ba dPaddingEx ception if this ciph er is in d ecryption mode, | |
2357 | * and (un)paddi ng has bee n requeste d, but the decrypted data is n ot | |
2358 | * bou nded by th e appropri ate paddin g bytes | |
2359 | * @ex ception AE ADBadTagEx ception if this ciph er is decr ypting in an | |
2360 | * AEA D mode (su ch as GCM/ CCM), and the receiv ed authent ication ta g | |
2361 | * doe s not matc h the calc ulated val ue | |
2362 | */ | |
2363 | public final int doFinal(b yte[] inpu t, int inp utOffset, int inputL en, | |
2364 | b yte[] outp ut, int ou tputOffset ) | |
2365 | throws S hortBuffer Exception, IllegalBl ockSizeExc eption, | |
2366 | BadPaddi ngExceptio n { | |
2367 | ch eckCipherS tate(); | |
2368 | ||
2369 | // Input san ity check | |
2370 | if (input == null || i nputOffset < 0 | |
2371 | || input Len > (inp ut.length - inputOff set) || in putLen < 0 | |
2372 | || outpu tOffset < 0) { | |
2373 | throw ne w IllegalA rgumentExc eption("Ba d argument s"); | |
2374 | } | |
2375 | ||
2376 | ch ooseFirstP rovider(); | |
2377 | re turn spi.e ngineDoFin al(input, inputOffse t, inputLe n, | |
2378 | o utput, out putOffset) ; | |
2379 | } | |
2380 | ||
2381 | /** | |
2382 | * Enc rypts or d ecrypts da ta in a si ngle-part operation, or finish es a | |
2383 | * mul tiple-part operation . The data is encryp ted or dec rypted, | |
2384 | * dep ending on how this c ipher was initialize d. | |
2385 | * | |
2386 | * <p> All <code> input.rema ining()</c ode> bytes starting at | |
2387 | * <co de>input.p osition()< /code> are processed . | |
2388 | * If an AEAD mo de such as GCM/CCM i s being us ed, the au thenticati on | |
2389 | * tag is append ed in the case of en cryption, or verifie d in the | |
2390 | * cas e of decry ption. | |
2391 | * The result is stored in the outpu t buffer. | |
2392 | * Upo n return, the input buffer's p osition wi ll be equa l | |
2393 | * to its limit; its limit will not have chang ed. The ou tput buffe r's | |
2394 | * pos ition will have adva nced by n, where n i s the valu e returned | |
2395 | * by this metho d; the out put buffer 's limit w ill not ha ve changed . | |
2396 | * | |
2397 | * <p> If <code>o utput.rema ining()</c ode> bytes are insuf ficient to | |
2398 | * hol d the resu lt, a <cod e>ShortBuf ferExcepti on</code> is thrown. | |
2399 | * In this case, repeat th is call wi th a large r output b uffer. Use | |
2400 | * {@l ink #getOu tputSize(i nt) getOut putSize} t o determin e how big | |
2401 | * the output bu ffer shoul d be. | |
2402 | * | |
2403 | * <p> Upon finis hing, this method re sets this cipher obj ect to the state | |
2404 | * it was in whe n previous ly initial ized via a call to < code>init< /code>. | |
2405 | * Tha t is, the object is reset and available to encrypt or decryp t | |
2406 | * (de pending on the opera tion mode that was s pecified i n the call to | |
2407 | * <co de>init</c ode>) more data. | |
2408 | * | |
2409 | * <p> Note: if a ny excepti on is thro wn, this c ipher obje ct may nee d to | |
2410 | * be reset befo re it can be used ag ain. | |
2411 | * | |
2412 | * <p> Note: this method sh ould be co py-safe, w hich means the | |
2413 | * <co de>input</ code> and <code>outp ut</code> buffers ca n referenc e | |
2414 | * the same byte array and no unproc essed inpu t data is overwritte n | |
2415 | * whe n the resu lt is copi ed into th e output b uffer. | |
2416 | * | |
2417 | * @pa ram input the input ByteBuffer | |
2418 | * @pa ram output the outpu t ByteBuff er | |
2419 | * | |
2420 | * @re turn the n umber of b ytes store d in <code >output</c ode> | |
2421 | * | |
2422 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
2423 | * (e. g., has no t been ini tialized) | |
2424 | * @ex ception Il legalArgum entExcepti on if inpu t and outp ut are the | |
2425 | * s ame object | |
2426 | * @ex ception Re adOnlyBuff erExceptio n if the o utput buff er is read -only | |
2427 | * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block cipher, | |
2428 | * no padding ha s been req uested (on ly in encr yption mod e), and th e total | |
2429 | * inp ut length of the dat a processe d by this cipher is not a mult iple of | |
2430 | * blo ck size; o r if this encryption algorithm is unable to | |
2431 | * pro cess the i nput data provided. | |
2432 | * @ex ception Sh ortBufferE xception i f there is insuffici ent space in the | |
2433 | * out put buffer | |
2434 | * @ex ception Ba dPaddingEx ception if this ciph er is in d ecryption mode, | |
2435 | * and (un)paddi ng has bee n requeste d, but the decrypted data is n ot | |
2436 | * bou nded by th e appropri ate paddin g bytes | |
2437 | * @ex ception AE ADBadTagEx ception if this ciph er is decr ypting in an | |
2438 | * AEA D mode (su ch as GCM/ CCM), and the receiv ed authent ication ta g | |
2439 | * doe s not matc h the calc ulated val ue | |
2440 | * | |
2441 | * @si nce 1.5 | |
2442 | */ | |
2443 | public final int doFinal(B yteBuffer input, Byt eBuffer ou tput) | |
2444 | throws S hortBuffer Exception, IllegalBl ockSizeExc eption, | |
2445 | BadPaddi ngExceptio n { | |
2446 | ch eckCipherS tate(); | |
2447 | ||
2448 | if ((input = = null) || (output = = null)) { | |
2449 | throw ne w IllegalA rgumentExc eption("Bu ffers must not be nu ll"); | |
2450 | } | |
2451 | if (input == output) { | |
2452 | throw ne w IllegalA rgumentExc eption("In put and ou tput buffe rs must " | |
2453 | + "n ot be the same objec t, conside r using bu ffer.dupli cate()"); | |
2454 | } | |
2455 | if (output.i sReadOnly( )) { | |
2456 | throw ne w ReadOnly BufferExce ption(); | |
2457 | } | |
2458 | ||
2459 | ch ooseFirstP rovider(); | |
2460 | re turn spi.e ngineDoFin al(input, output); | |
2461 | } | |
2462 | ||
2463 | /** | |
2464 | * Wra p a key. | |
2465 | * | |
2466 | * @pa ram key th e key to b e wrapped. | |
2467 | * | |
2468 | * @re turn the w rapped key . | |
2469 | * | |
2470 | * @ex ception Il legalState Exception if this ci pher is in a wrong | |
2471 | * sta te (e.g., has not be en initial ized). | |
2472 | * | |
2473 | * @ex ception Il legalBlock SizeExcept ion if thi s cipher i s a block | |
2474 | * cip her, no pa dding has been reque sted, and the length of the | |
2475 | * enc oding of t he key to be wrapped is not a | |
2476 | * mul tiple of t he block s ize. | |
2477 | * | |
2478 | * @ex ception In validKeyEx ception if it is imp ossible or unsafe to | |
2479 | * wra p the key with this cipher (e. g., a hard ware prote cted key i s | |
2480 | * bei ng passed to a softw are-only c ipher). | |
2481 | * | |
2482 | * @th rows Unsup portedOper ationExcep tion if th e correspo nding meth od in the | |
2483 | * {@c ode Cipher Spi} is no t supporte d. | |
2484 | */ | |
2485 | public final byt e[] wrap(K ey key) | |
2486 | throws I llegalBloc kSizeExcep tion, Inva lidKeyExce ption { | |
2487 | if (!(this i nstanceof NullCipher )) { | |
2488 | if (!ini tialized) { | |
2489 | thro w new Ille galStateEx ception("C ipher not initialize d"); | |
2490 | } | |
2491 | if (opmo de != Ciph er.WRAP_MO DE) { | |
2492 | thro w new Ille galStateEx ception("C ipher not initialize d " + | |
2493 | "f or wrappin g keys"); | |
2494 | } | |
2495 | } | |
2496 | ||
2497 | ch ooseFirstP rovider(); | |
2498 | re turn spi.e ngineWrap( key); | |
2499 | } | |
2500 | ||
2501 | /** | |
2502 | * Unw rap a prev iously wra pped key. | |
2503 | * | |
2504 | * @pa ram wrappe dKey the k ey to be u nwrapped. | |
2505 | * | |
2506 | * @pa ram wrappe dKeyAlgori thm the al gorithm as sociated w ith the wr apped | |
2507 | * key . | |
2508 | * | |
2509 | * @pa ram wrappe dKeyType t he type of the wrapp ed key. Th is must be one of | |
2510 | * <co de>SECRET_ KEY</code> , <code>PR IVATE_KEY< /code>, or | |
2511 | * <co de>PUBLIC_ KEY</code> . | |
2512 | * | |
2513 | * @re turn the u nwrapped k ey. | |
2514 | * | |
2515 | * @ex ception Il legalState Exception if this ci pher is in a wrong s tate | |
2516 | * (e. g., has no t been ini tialized). | |
2517 | * | |
2518 | * @ex ception No SuchAlgori thmExcepti on if no i nstalled p roviders | |
2519 | * can create ke ys of type <code>wra ppedKeyTyp e</code> f or the | |
2520 | * <co de>wrapped KeyAlgorit hm</code>. | |
2521 | * | |
2522 | * @ex ception In validKeyEx ception if <code>wra ppedKey</c ode> does not | |
2523 | * rep resent a w rapped key of type < code>wrapp edKeyType< /code> for | |
2524 | * the <code>wra ppedKeyAlg orithm</co de>. | |
2525 | * | |
2526 | * @th rows Unsup portedOper ationExcep tion if th e correspo nding meth od in the | |
2527 | * {@c ode Cipher Spi} is no t supporte d. | |
2528 | */ | |
2529 | public final Key unwrap(by te[] wrapp edKey, | |
2530 | St ring wrapp edKeyAlgor ithm, | |
2531 | in t wrappedK eyType) | |
2532 | throws I nvalidKeyE xception, NoSuchAlgo rithmExcep tion { | |
2533 | ||
2534 | if (!(this i nstanceof NullCipher )) { | |
2535 | if (!ini tialized) { | |
2536 | thro w new Ille galStateEx ception("C ipher not initialize d"); | |
2537 | } | |
2538 | if (opmo de != Ciph er.UNWRAP_ MODE) { | |
2539 | thro w new Ille galStateEx ception("C ipher not initialize d " + | |
2540 | "f or unwrapp ing keys") ; | |
2541 | } | |
2542 | } | |
2543 | if ((wrapped KeyType != SECRET_KE Y) && | |
2544 | (wrapped KeyType != PRIVATE_K EY) && | |
2545 | (wrapped KeyType != PUBLIC_KE Y)) { | |
2546 | throw ne w InvalidP arameterEx ception("I nvalid key type"); | |
2547 | } | |
2548 | ||
2549 | ch ooseFirstP rovider(); | |
2550 | re turn spi.e ngineUnwra p(wrappedK ey, | |
2551 | wr appedKeyAl gorithm, | |
2552 | wr appedKeyTy pe); | |
2553 | } | |
2554 | ||
2555 | privat e Algorith mParameter Spec getAl gorithmPar ameterSpec ( | |
2556 | Al gorithmPar ameters pa rams) | |
2557 | throws I nvalidPara meterSpecE xception { | |
2558 | if (params = = null) { | |
2559 | return n ull; | |
2560 | } | |
2561 | ||
2562 | St ring alg = params.ge tAlgorithm ().toUpper Case(Local e.ENGLISH) ; | |
2563 | ||
2564 | if (alg.equa lsIgnoreCa se("RC2")) { | |
2565 | return p arams.getP arameterSp ec(RC2Para meterSpec. class); | |
2566 | } | |
2567 | ||
2568 | if (alg.equa lsIgnoreCa se("RC5")) { | |
2569 | return p arams.getP arameterSp ec(RC5Para meterSpec. class); | |
2570 | } | |
2571 | ||
2572 | if (alg.star tsWith("PB E")) { | |
2573 | return p arams.getP arameterSp ec(PBEPara meterSpec. class); | |
2574 | } | |
2575 | ||
2576 | if (alg.star tsWith("DE S")) { | |
2577 | return p arams.getP arameterSp ec(IvParam eterSpec.c lass); | |
2578 | } | |
2579 | re turn null; | |
2580 | } | |
2581 | ||
2582 | privat e static C ryptoPermi ssion getC onfiguredP ermission( | |
2583 | String t ransformat ion) throw s NullPoin terExcepti on, | |
2584 | NoSuchAl gorithmExc eption { | |
2585 | if (transfor mation == null) thro w new Null PointerExc eption(); | |
2586 | St ring[] par ts = token izeTransfo rmation(tr ansformati on); | |
2587 | re turn JceSe curityMana ger.INSTAN CE.getCryp toPermissi on(parts[0 ]); | |
2588 | } | |
2589 | ||
2590 | /** | |
2591 | * Ret urns the m aximum key length fo r the spec ified tran sformation | |
2592 | * acc ording to the instal led JCE ju risdiction policy fi les. If | |
2593 | * JCE unlimited strength jurisdicti on policy files are installed, | |
2594 | * Int eger.MAX_V ALUE will be returne d. | |
2595 | * For more info rmation on default k ey size in JCE juris diction | |
2596 | * pol icy files, please se e Appendix E in the | |
2597 | * <a href= | |
2598 | * " {@docRoot} /../techno tes/guides /security/ crypto/Cry ptoSpec.ht ml#AppC"> | |
2599 | * Jav a Cryptogr aphy Archi tecture Re ference Gu ide</a>. | |
2600 | * | |
2601 | * @pa ram transf ormation t he cipher transforma tion. | |
2602 | * @re turn the m aximum key length in bits or I nteger.MAX _VALUE. | |
2603 | * @ex ception Nu llPointerE xception i f <code>tr ansformati on</code> is null. | |
2604 | * @ex ception No SuchAlgori thmExcepti on if <cod e>transfor mation</co de> | |
2605 | * is not a vali d transfor mation, i. e. in the form of "a lgorithm" or | |
2606 | * "al gorithm/mo de/padding ". | |
2607 | * @si nce 1.5 | |
2608 | */ | |
2609 | public static fi nal int ge tMaxAllowe dKeyLength (String tr ansformati on) | |
2610 | throws N oSuchAlgor ithmExcept ion { | |
2611 | Cr yptoPermis sion cp = getConfigu redPermiss ion(transf ormation); | |
2612 | re turn cp.ge tMaxKeySiz e(); | |
2613 | } | |
2614 | ||
2615 | /** | |
2616 | * Ret urns an Al gorithmPar ameterSpec object wh ich contai ns | |
2617 | * the maximum c ipher para meter valu e accordin g to the | |
2618 | * jur isdiction policy fil e. If JCE unlimited strength j urisdictio n | |
2619 | * pol icy files are instal led or the re is no m aximum lim it on the | |
2620 | * par ameters fo r the spec ified tran sformation in the po licy file, | |
2621 | * nul l will be returned. | |
2622 | * | |
2623 | * @pa ram transf ormation t he cipher transforma tion. | |
2624 | * @re turn an Al gorithmPar ameterSpec which hol ds the max imum | |
2625 | * val ue or null . | |
2626 | * @ex ception Nu llPointerE xception i f <code>tr ansformati on</code> | |
2627 | * is null. | |
2628 | * @ex ception No SuchAlgori thmExcepti on if <cod e>transfor mation</co de> | |
2629 | * is not a vali d transfor mation, i. e. in the form of "a lgorithm" or | |
2630 | * "al gorithm/mo de/padding ". | |
2631 | * @si nce 1.5 | |
2632 | */ | |
2633 | public static fi nal Algori thmParamet erSpec get MaxAllowed ParameterS pec( | |
2634 | String t ransformat ion) throw s NoSuchAl gorithmExc eption { | |
2635 | Cr yptoPermis sion cp = getConfigu redPermiss ion(transf ormation); | |
2636 | re turn cp.ge tAlgorithm ParameterS pec(); | |
2637 | } | |
2638 | ||
2639 | /** | |
2640 | * Con tinues a m ulti-part update of the Additi onal Authe ntication | |
2641 | * Dat a (AAD). | |
2642 | * <p> | |
2643 | * Cal ls to this method pr ovide AAD to the cip her when o perating i n | |
2644 | * mod es such as AEAD (GCM /CCM). If this ciph er is oper ating in | |
2645 | * eit her GCM or CCM mode, all AAD m ust be sup plied befo re beginni ng | |
2646 | * ope rations on the ciphe rtext (via the {@cod e update} and {@code | |
2647 | * doF inal} meth ods). | |
2648 | * | |
2649 | * @pa ram src th e buffer c ontaining the Additi onal Authe ntication Data | |
2650 | * | |
2651 | * @th rows Illeg alArgument Exception if the {@c ode src} | |
2652 | * byt e array is null | |
2653 | * @th rows Illeg alStateExc eption if this ciphe r is in a wrong stat e | |
2654 | * (e. g., has no t been ini tialized), does not accept AAD , or if | |
2655 | * ope rating in either GCM or CCM mo de and one of the {@ code updat e} | |
2656 | * met hods has a lready bee n called f or the act ive | |
2657 | * enc ryption/de cryption o peration | |
2658 | * @th rows Unsup portedOper ationExcep tion if th e correspo nding meth od | |
2659 | * in the {@code CipherSpi } has not been overr idden by a n | |
2660 | * imp lementatio n | |
2661 | * | |
2662 | * @si nce 1.7 | |
2663 | */ | |
2664 | public final voi d updateAA D(byte[] s rc) { | |
2665 | if (src == n ull) { | |
2666 | throw ne w IllegalA rgumentExc eption("sr c buffer i s null"); | |
2667 | } | |
2668 | ||
2669 | up dateAAD(sr c, 0, src. length); | |
2670 | } | |
2671 | ||
2672 | /** | |
2673 | * Con tinues a m ulti-part update of the Additi onal Authe ntication | |
2674 | * Dat a (AAD), u sing a sub set of the provided buffer. | |
2675 | * <p> | |
2676 | * Cal ls to this method pr ovide AAD to the cip her when o perating i n | |
2677 | * mod es such as AEAD (GCM /CCM). If this ciph er is oper ating in | |
2678 | * eit her GCM or CCM mode, all AAD m ust be sup plied befo re beginni ng | |
2679 | * ope rations on the ciphe rtext (via the {@cod e update} and {@code | |
2680 | * doF inal} meth ods). | |
2681 | * | |
2682 | * @pa ram src th e buffer c ontaining the AAD | |
2683 | * @pa ram offset the offse t in {@cod e src} whe re the AAD input sta rts | |
2684 | * @pa ram len th e number o f AAD byte s | |
2685 | * | |
2686 | * @th rows Illeg alArgument Exception if the {@c ode src} | |
2687 | * byt e array is null, or the {@code offset} o r {@code l ength} | |
2688 | * is less than 0, or the sum of the {@code of fset} and | |
2689 | * {@c ode len} i s greater than the l ength of t he | |
2690 | * {@c ode src} b yte array | |
2691 | * @th rows Illeg alStateExc eption if this ciphe r is in a wrong stat e | |
2692 | * (e. g., has no t been ini tialized), does not accept AAD , or if | |
2693 | * ope rating in either GCM or CCM mo de and one of the {@ code updat e} | |
2694 | * met hods has a lready bee n called f or the act ive | |
2695 | * enc ryption/de cryption o peration | |
2696 | * @th rows Unsup portedOper ationExcep tion if th e correspo nding meth od | |
2697 | * in the {@code CipherSpi } has not been overr idden by a n | |
2698 | * imp lementatio n | |
2699 | * | |
2700 | * @si nce 1.7 | |
2701 | */ | |
2702 | public final voi d updateAA D(byte[] s rc, int of fset, int len) { | |
2703 | ch eckCipherS tate(); | |
2704 | ||
2705 | // Input san ity check | |
2706 | if ((src == null) || ( offset < 0 ) || (len < 0) | |
2707 | || ( (len + off set) > src .length)) { | |
2708 | throw ne w IllegalA rgumentExc eption("Ba d argument s"); | |
2709 | } | |
2710 | ||
2711 | ch ooseFirstP rovider(); | |
2712 | if (len == 0 ) { | |
2713 | return; | |
2714 | } | |
2715 | sp i.engineUp dateAAD(sr c, offset, len); | |
2716 | } | |
2717 | ||
2718 | /** | |
2719 | * Con tinues a m ulti-part update of the Additi onal Authe ntication | |
2720 | * Dat a (AAD). | |
2721 | * <p> | |
2722 | * Cal ls to this method pr ovide AAD to the cip her when o perating i n | |
2723 | * mod es such as AEAD (GCM /CCM). If this ciph er is oper ating in | |
2724 | * eit her GCM or CCM mode, all AAD m ust be sup plied befo re beginni ng | |
2725 | * ope rations on the ciphe rtext (via the {@cod e update} and {@code | |
2726 | * doF inal} meth ods). | |
2727 | * <p> | |
2728 | * All {@code sr c.remainin g()} bytes starting at | |
2729 | * {@c ode src.po sition()} are proces sed. | |
2730 | * Upo n return, the input buffer's p osition wi ll be equa l | |
2731 | * to its limit; its limit will not have chang ed. | |
2732 | * | |
2733 | * @pa ram src th e buffer c ontaining the AAD | |
2734 | * | |
2735 | * @th rows Illeg alArgument Exception if the {@c ode src By teBuffer} | |
2736 | * is null | |
2737 | * @th rows Illeg alStateExc eption if this ciphe r is in a wrong stat e | |
2738 | * (e. g., has no t been ini tialized), does not accept AAD , or if | |
2739 | * ope rating in either GCM or CCM mo de and one of the {@ code updat e} | |
2740 | * met hods has a lready bee n called f or the act ive | |
2741 | * enc ryption/de cryption o peration | |
2742 | * @th rows Unsup portedOper ationExcep tion if th e correspo nding meth od | |
2743 | * in the {@code CipherSpi } has not been overr idden by a n | |
2744 | * imp lementatio n | |
2745 | * | |
2746 | * @si nce 1.7 | |
2747 | */ | |
2748 | public final voi d updateAA D(ByteBuff er src) { | |
2749 | ch eckCipherS tate(); | |
2750 | ||
2751 | // Input san ity check | |
2752 | if (src == n ull) { | |
2753 | throw ne w IllegalA rgumentExc eption("sr c ByteBuff er is null "); | |
2754 | } | |
2755 | ||
2756 | ch ooseFirstP rovider(); | |
2757 | if (src.rema ining() == 0) { | |
2758 | return; | |
2759 | } | |
2760 | sp i.engineUp dateAAD(sr c); | |
2761 | } | |
2762 | } |
Araxis Merge (but not the data content of this report) is Copyright © 1993-2016 Araxis Ltd (www.araxis.com). All rights reserved.