< prev index next >
src/share/classes/com/sun/crypto/provider/PKCS5Padding.java
Print this page
rev 12526 : 8171252: Improve exception checking
8158517: Minor optimizations to ISO10126PADDING
Reviewed-by: ascarpino, mschoene
@@ -1,7 +1,7 @@
/*
- * Copyright (c) 1997, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
@@ -24,10 +24,11 @@
*/
package com.sun.crypto.provider;
import javax.crypto.ShortBufferException;
+import java.util.Arrays;
/**
* This class implements padding as specified in the PKCS#5 standard.
*
* @author Gigi Ankeny
@@ -61,18 +62,17 @@
throws ShortBufferException
{
if (in == null)
return;
- if ((off + len) > in.length) {
+ int idx = Math.addExact(off, len);
+ if (idx > in.length) {
throw new ShortBufferException("Buffer too small to hold padding");
}
byte paddingOctet = (byte) (len & 0xff);
- for (int i = 0; i < len; i++) {
- in[i + off] = paddingOctet;
- }
+ Arrays.fill(in, off, idx, paddingOctet);
return;
}
/**
* Returns the index where the padding starts.
@@ -90,29 +90,28 @@
public int unpad(byte[] in, int off, int len) {
if ((in == null) ||
(len == 0)) { // this can happen if input is really a padded buffer
return 0;
}
-
- byte lastByte = in[off + len - 1];
+ int idx = Math.addExact(off, len);
+ byte lastByte = in[idx - 1];
int padValue = (int)lastByte & 0x0ff;
if ((padValue < 0x01)
|| (padValue > blockSize)) {
return -1;
}
- int start = off + len - ((int)lastByte & 0x0ff);
+ int start = idx - padValue;
if (start < off) {
return -1;
}
- for (int i = 0; i < ((int)lastByte & 0x0ff); i++) {
- if (in[start+i] != lastByte) {
+ for (int i = start; i < idx; i++) {
+ if (in[i] != lastByte) {
return -1;
}
}
-
return start;
}
/**
* Determines how long the padding will be for a given input length.
< prev index next >