提交 eada82a3 编写于 作者: R robm

Merge

......@@ -211,47 +211,6 @@ createGlobalRefs(JNIEnv *env, InvokeRequest *request)
return error;
}
/*
* Delete global references from the request which got put there before a
* invoke request was carried out. See fillInvokeRequest() and invoker invoke*()
* impls.
*/
static void
deleteGlobalRefs(JNIEnv *env, InvokeRequest *request)
{
void *cursor;
jint argIndex = 0;
jvalue *argument = request->arguments;
jbyte argumentTag = firstArgumentTypeTag(request->methodSignature, &cursor);
if (request->clazz != NULL) {
tossGlobalRef(env, &(request->clazz));
}
if (request->instance != NULL) {
tossGlobalRef(env, &(request->instance));
}
/* Delete global argument references */
while (argIndex < request->argumentCount) {
if ((argumentTag == JDWP_TAG(OBJECT)) ||
(argumentTag == JDWP_TAG(ARRAY))) {
if (argument->l != NULL) {
tossGlobalRef(env, &(argument->l));
}
}
argument++;
argIndex++;
argumentTag = nextArgumentTypeTag(&cursor);
}
/* Delete potentially saved return values */
if ((request->invokeType == INVOKE_CONSTRUCTOR) ||
(returnTypeTag(request->methodSignature) == JDWP_TAG(OBJECT)) ||
(returnTypeTag(request->methodSignature) == JDWP_TAG(ARRAY))) {
if (request->returnValue.l != NULL) {
tossGlobalRef(env, &(request->returnValue.l));
}
}
}
static jvmtiError
fillInvokeRequest(JNIEnv *env, InvokeRequest *request,
jbyte invokeType, jbyte options, jint id,
......@@ -777,13 +736,6 @@ invoker_completeInvokeRequest(jthread thread)
(void)outStream_writeObjectRef(env, &out, exc);
outStream_sendReply(&out);
}
/*
* At this time, there's no need to retain global references on
* arguments since the reply is processed. No one will deal with
* this request ID anymore, so we must call deleteGlobalRefs().
*/
deleteGlobalRefs(env, request);
}
jboolean
......
......@@ -2975,7 +2975,8 @@ final public class LdapCtx extends ComponentDirContext
r = new LdapReferralException(resolvedName, resolvedObj, remainName,
msg, envprops, fullDN, handleReferrals, reqCtls);
// only one set of URLs is present
r.setReferralInfo(res.referrals.elementAt(0), false);
r.setReferralInfo(res.referrals == null ? null :
res.referrals.elementAt(0), false);
if (hopCount > 1) {
r.setHopCount(hopCount);
......@@ -3044,7 +3045,7 @@ final public class LdapCtx extends ComponentDirContext
* assume name resolution has not yet completed.
*/
if (((res.entries == null) || (res.entries.isEmpty())) &&
(res.referrals.size() == 1)) {
((res.referrals != null) && (res.referrals.size() == 1))) {
r.setReferralInfo(res.referrals, false);
......
......@@ -217,14 +217,16 @@ final public class LdapReferralException extends
System.out.println("LdapReferralException.setReferralInfo");
this.referrals = referrals;
if (referrals != null) {
referralCount = referrals.size();
}
referralCount = (referrals == null) ? 0 : referrals.size();
if (debug) {
if (referrals != null) {
for (int i = 0; i < referralCount; i++) {
System.out.println(" [" + i + "] " + referrals.elementAt(i));
}
} else {
System.out.println("setReferralInfo : referrals == null");
}
}
}
......
/*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2016, 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
......@@ -64,8 +64,7 @@ final class JceSecurity {
private final static Map<Provider, Object> verifyingProviders =
new IdentityHashMap<>();
// Set the default value. May be changed in the static initializer.
private static boolean isRestricted = true;
private static final boolean isRestricted;
/*
* Don't let anyone instantiate this.
......
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2000, 2016, 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
......@@ -47,6 +47,9 @@ public class Util {
// The number of temp buffers in our pool
private static final int TEMP_BUF_POOL_SIZE = IOUtil.IOV_MAX;
// The max size allowed for a cached temp buffer, in bytes
private static final long MAX_CACHED_BUFFER_SIZE = getMaxCachedBufferSize();
// Per-thread cache of temporary direct buffers
private static ThreadLocal<BufferCache> bufferCache =
new ThreadLocal<BufferCache>()
......@@ -57,6 +60,52 @@ public class Util {
}
};
/**
* Returns the max size allowed for a cached temp buffers, in
* bytes. It defaults to Long.MAX_VALUE. It can be set with the
* jdk.nio.maxCachedBufferSize property. Even though
* ByteBuffer.capacity() returns an int, we're using a long here
* for potential future-proofing.
*/
private static long getMaxCachedBufferSize() {
String s = java.security.AccessController.doPrivileged(
new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty("jdk.nio.maxCachedBufferSize");
}
});
if (s != null) {
try {
long m = Long.parseLong(s);
if (m >= 0) {
return m;
} else {
// if it's negative, ignore the system property
}
} catch (NumberFormatException e) {
// if the string is not well formed, ignore the system property
}
}
return Long.MAX_VALUE;
}
/**
* Returns true if a buffer of this size is too large to be
* added to the buffer cache, false otherwise.
*/
private static boolean isBufferTooLarge(int size) {
return size > MAX_CACHED_BUFFER_SIZE;
}
/**
* Returns true if the buffer is too large to be added to the
* buffer cache, false otherwise.
*/
private static boolean isBufferTooLarge(ByteBuffer buf) {
return isBufferTooLarge(buf.capacity());
}
/**
* A simple cache of direct buffers.
*/
......@@ -83,6 +132,9 @@ public class Util {
* size (or null if no suitable buffer is found).
*/
ByteBuffer get(int size) {
// Don't call this if the buffer would be too large.
assert !isBufferTooLarge(size);
if (count == 0)
return null; // cache is empty
......@@ -120,6 +172,9 @@ public class Util {
}
boolean offerFirst(ByteBuffer buf) {
// Don't call this if the buffer is too large.
assert !isBufferTooLarge(buf);
if (count >= TEMP_BUF_POOL_SIZE) {
return false;
} else {
......@@ -131,6 +186,9 @@ public class Util {
}
boolean offerLast(ByteBuffer buf) {
// Don't call this if the buffer is too large.
assert !isBufferTooLarge(buf);
if (count >= TEMP_BUF_POOL_SIZE) {
return false;
} else {
......@@ -159,6 +217,15 @@ public class Util {
* Returns a temporary buffer of at least the given size
*/
public static ByteBuffer getTemporaryDirectBuffer(int size) {
// If a buffer of this size is too large for the cache, there
// should not be a buffer in the cache that is at least as
// large. So we'll just create a new one. Also, we don't have
// to remove the buffer from the cache (as this method does
// below) given that we won't put the new buffer in the cache.
if (isBufferTooLarge(size)) {
return ByteBuffer.allocateDirect(size);
}
BufferCache cache = bufferCache.get();
ByteBuffer buf = cache.get(size);
if (buf != null) {
......@@ -188,6 +255,13 @@ public class Util {
* likely to be returned by a subsequent call to getTemporaryDirectBuffer.
*/
static void offerFirstTemporaryDirectBuffer(ByteBuffer buf) {
// If the buffer is too large for the cache we don't have to
// check the cache. We'll just free it.
if (isBufferTooLarge(buf)) {
free(buf);
return;
}
assert buf != null;
BufferCache cache = bufferCache.get();
if (!cache.offerFirst(buf)) {
......@@ -203,6 +277,13 @@ public class Util {
* cache in same order that they were obtained.
*/
static void offerLastTemporaryDirectBuffer(ByteBuffer buf) {
// If the buffer is too large for the cache we don't have to
// check the cache. We'll just free it.
if (isBufferTooLarge(buf)) {
free(buf);
return;
}
assert buf != null;
BufferCache cache = bufferCache.get();
if (!cache.offerLast(buf)) {
......
......@@ -157,6 +157,9 @@ JNIEXPORT jboolean JNICALL
if (hBitmap != 0) { \
DeleteObject(hBitmap); \
} \
if (tmpBitmap != 0) { \
DeleteObject(tmpBitmap); \
} \
if (dibImage != NULL) { \
free(dibImage); \
} \
......@@ -196,6 +199,7 @@ Java_sun_font_FileFontStrike__1getGlyphImageFromWindows
int bmWidth, bmHeight;
int x, y;
HBITMAP hBitmap = NULL, hOrigBM;
HBITMAP tmpBitmap = NULL;
int gamma, orient;
HWND hWnd = NULL;
......@@ -250,6 +254,12 @@ Java_sun_font_FileFontStrike__1getGlyphImageFromWindows
}
oldFont = SelectObject(hMemoryDC, hFont);
tmpBitmap = CreateCompatibleBitmap(hDesktopDC, 1, 1);
if (tmpBitmap == NULL) {
FREE_AND_RETURN;
}
hOrigBM = (HBITMAP)SelectObject(hMemoryDC, tmpBitmap);
memset(&textMetric, 0, sizeof(TEXTMETRIC));
err = GetTextMetrics(hMemoryDC, &textMetric);
if (err == 0) {
......@@ -334,7 +344,7 @@ Java_sun_font_FileFontStrike__1getGlyphImageFromWindows
if (hBitmap == NULL) {
FREE_AND_RETURN;
}
hOrigBM = (HBITMAP)SelectObject(hMemoryDC, hBitmap);
SelectObject(hMemoryDC, hBitmap);
/* Fill in black */
rect.left = 0;
......@@ -478,6 +488,7 @@ Java_sun_font_FileFontStrike__1getGlyphImageFromWindows
ReleaseDC(hWnd, hDesktopDC);
DeleteObject(hMemoryDC);
DeleteObject(hBitmap);
DeleteObject(tmpBitmap);
return ptr_to_jlong(glyphInfo);
}
......@@ -31,6 +31,8 @@
#include "awt_Object.h"
#include "awt_Component.h"
#include "math.h"
// Important note about VC6 and VC7 (or XP Platform SDK) !
//
// These type definitions have been imported from UxTheme.h
......@@ -68,6 +70,11 @@ typedef struct _MARGINS
#define TMT_TRANSPARENT 2201
#endif // _UXTHEME_H_
#if defined(_MSC_VER) && _MSC_VER >= 1800
# define ROUND_TO_INT(num) ((int) round(num))
#else
# define ROUND_TO_INT(num) ((int) floor((num) + 0.5))
#endif
#define ALPHA_MASK 0xff000000
#define RED_MASK 0xff0000
......@@ -745,6 +752,23 @@ JNIEXPORT jobject JNICALL Java_sun_awt_windows_ThemeReader_getPosition
return NULL;
}
void rescale(SIZE *size) {
HWND hWnd = ::GetDesktopWindow();
HDC hDC = ::GetDC(hWnd);
int dpiX = ::GetDeviceCaps(hDC, LOGPIXELSX);
int dpiY = ::GetDeviceCaps(hDC, LOGPIXELSY);
if (dpiX !=0 && dpiX != 96) {
float invScaleX = 96.0f / dpiX;
size->cx = ROUND_TO_INT(size->cx * invScaleX);
}
if (dpiY != 0 && dpiY != 96) {
float invScaleY = 96.0f / dpiY;
size->cy = ROUND_TO_INT(size->cy * invScaleY);
}
::ReleaseDC(hWnd, hDC);
}
/*
* Class: sun_awt_windows_ThemeReader
* Method: getPartSize
......@@ -770,6 +794,8 @@ JNIEXPORT jobject JNICALL Java_sun_awt_windows_ThemeReader_getPartSize
dimMID = env->GetMethodID(dimClassID, "<init>", "(II)V");
CHECK_NULL_RETURN(dimMID, NULL);
}
rescale(&size);
jobject dimObj = env->NewObject(dimClassID, dimMID, size.cx, size.cy);
if (safe_ExceptionOccurred(env)) {
env->ExceptionDescribe();
......
......@@ -35,6 +35,14 @@
#include <shellapi.h>
#include <shlobj.h>
#include "math.h"
#if defined(_MSC_VER) && _MSC_VER >= 1800
# define ROUND_TO_INT(num) ((int) round(num))
#else
# define ROUND_TO_INT(num) ((int) floor((num) + 0.5))
#endif
// WDesktopProperties fields
jfieldID AwtDesktopProperties::pDataID = 0;
jmethodID AwtDesktopProperties::setBooleanPropertyID = 0;
......@@ -79,18 +87,35 @@ void AwtDesktopProperties::GetWindowsParameters() {
}
}
void getInvScale(float &invScaleX, float &invScaleY) {
HWND hWnd = ::GetDesktopWindow();
HDC hDC = ::GetDC(hWnd);
int dpiX = ::GetDeviceCaps(hDC, LOGPIXELSX);
int dpiY = ::GetDeviceCaps(hDC, LOGPIXELSY);
::ReleaseDC(hWnd, hDC);
invScaleX = (dpiX == 0.0f) ? 1.0f : 96.0f / dpiX;
invScaleY = (dpiY == 0.0f) ? 1.0f : 96.0f / dpiY;
}
int rescale(int value, float invScale){
return invScale == 1.0f ? value : ROUND_TO_INT(value * invScale);
}
void AwtDesktopProperties::GetSystemProperties() {
HDC dc = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
if (dc != NULL) {
try {
SetFontProperty(dc, ANSI_FIXED_FONT, TEXT("win.ansiFixed.font"));
SetFontProperty(dc, ANSI_VAR_FONT, TEXT("win.ansiVar.font"));
SetFontProperty(dc, DEVICE_DEFAULT_FONT, TEXT("win.deviceDefault.font"));
SetFontProperty(dc, DEFAULT_GUI_FONT, TEXT("win.defaultGUI.font"));
SetFontProperty(dc, OEM_FIXED_FONT, TEXT("win.oemFixed.font"));
SetFontProperty(dc, SYSTEM_FONT, TEXT("win.system.font"));
SetFontProperty(dc, SYSTEM_FIXED_FONT, TEXT("win.systemFixed.font"));
float invScaleX;
float invScaleY;
getInvScale(invScaleX, invScaleY);
SetFontProperty(dc, ANSI_FIXED_FONT, TEXT("win.ansiFixed.font"), 1.0f);
SetFontProperty(dc, ANSI_VAR_FONT, TEXT("win.ansiVar.font"), 1.0f);
SetFontProperty(dc, DEVICE_DEFAULT_FONT, TEXT("win.deviceDefault.font"), 1.0f);
SetFontProperty(dc, DEFAULT_GUI_FONT, TEXT("win.defaultGUI.font"), invScaleY);
SetFontProperty(dc, OEM_FIXED_FONT, TEXT("win.oemFixed.font"), 1.0f);
SetFontProperty(dc, SYSTEM_FONT, TEXT("win.system.font"), 1.0f);
SetFontProperty(dc, SYSTEM_FIXED_FONT, TEXT("win.systemFixed.font"), 1.0f);
}
catch (std::bad_alloc&) {
DeleteDC(dc);
......@@ -266,31 +291,35 @@ void AwtDesktopProperties::GetNonClientParameters() {
}
VERIFY( SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ncmetrics.cbSize, &ncmetrics, FALSE) );
SetFontProperty( TEXT("win.frame.captionFont"), ncmetrics.lfCaptionFont );
SetIntegerProperty( TEXT("win.frame.captionHeight"), ncmetrics.iCaptionHeight );
SetIntegerProperty( TEXT("win.frame.captionButtonWidth"), ncmetrics.iCaptionWidth );
SetIntegerProperty( TEXT("win.frame.captionButtonHeight"), ncmetrics.iCaptionHeight );
SetFontProperty( TEXT("win.frame.smallCaptionFont"), ncmetrics.lfSmCaptionFont );
SetIntegerProperty( TEXT("win.frame.smallCaptionHeight"), ncmetrics.iSmCaptionHeight );
SetIntegerProperty( TEXT("win.frame.smallCaptionButtonWidth"), ncmetrics.iSmCaptionWidth );
SetIntegerProperty( TEXT("win.frame.smallCaptionButtonHeight"), ncmetrics.iSmCaptionHeight );
SetIntegerProperty( TEXT("win.frame.sizingBorderWidth"), ncmetrics.iBorderWidth );
float invScaleX;
float invScaleY;
getInvScale(invScaleX, invScaleY);
SetFontProperty(TEXT("win.frame.captionFont"), ncmetrics.lfCaptionFont, invScaleY);
SetIntegerProperty(TEXT("win.frame.captionHeight"), rescale(ncmetrics.iCaptionHeight, invScaleY));
SetIntegerProperty(TEXT("win.frame.captionButtonWidth"), rescale(ncmetrics.iCaptionWidth, invScaleX));
SetIntegerProperty(TEXT("win.frame.captionButtonHeight"), rescale(ncmetrics.iCaptionHeight, invScaleY));
SetFontProperty(TEXT("win.frame.smallCaptionFont"), ncmetrics.lfSmCaptionFont, invScaleY);
SetIntegerProperty(TEXT("win.frame.smallCaptionHeight"), rescale(ncmetrics.iSmCaptionHeight, invScaleY));
SetIntegerProperty(TEXT("win.frame.smallCaptionButtonWidth"), rescale(ncmetrics.iSmCaptionWidth, invScaleX));
SetIntegerProperty(TEXT("win.frame.smallCaptionButtonHeight"), rescale(ncmetrics.iSmCaptionHeight, invScaleY));
SetIntegerProperty(TEXT("win.frame.sizingBorderWidth"), rescale(ncmetrics.iBorderWidth, invScaleX));
// menu properties
SetFontProperty( TEXT("win.menu.font"), ncmetrics.lfMenuFont );
SetIntegerProperty( TEXT("win.menu.height"), ncmetrics.iMenuHeight );
SetIntegerProperty( TEXT("win.menu.buttonWidth"), ncmetrics.iMenuWidth );
SetFontProperty(TEXT("win.menu.font"), ncmetrics.lfMenuFont, invScaleY);
SetIntegerProperty(TEXT("win.menu.height"), rescale(ncmetrics.iMenuHeight, invScaleY));
SetIntegerProperty(TEXT("win.menu.buttonWidth"), rescale(ncmetrics.iMenuWidth, invScaleX));
// scrollbar properties
SetIntegerProperty( TEXT("win.scrollbar.width"), ncmetrics.iScrollWidth );
SetIntegerProperty( TEXT("win.scrollbar.height"), ncmetrics.iScrollHeight );
SetIntegerProperty(TEXT("win.scrollbar.width"), rescale(ncmetrics.iScrollWidth, invScaleX));
SetIntegerProperty(TEXT("win.scrollbar.height"), rescale(ncmetrics.iScrollHeight, invScaleY));
// status bar and tooltip properties
SetFontProperty( TEXT("win.status.font"), ncmetrics.lfStatusFont );
SetFontProperty( TEXT("win.tooltip.font"), ncmetrics.lfStatusFont );
SetFontProperty(TEXT("win.status.font"), ncmetrics.lfStatusFont, invScaleY);
SetFontProperty(TEXT("win.tooltip.font"), ncmetrics.lfStatusFont, invScaleY);
// message box properties
SetFontProperty( TEXT("win.messagebox.font"), ncmetrics.lfMessageFont );
SetFontProperty(TEXT("win.messagebox.font"), ncmetrics.lfMessageFont, invScaleY);
}
void AwtDesktopProperties::GetIconParameters() {
......@@ -302,10 +331,13 @@ void AwtDesktopProperties::GetIconParameters() {
iconmetrics.cbSize = sizeof(iconmetrics);
VERIFY( SystemParametersInfo(SPI_GETICONMETRICS, iconmetrics.cbSize, &iconmetrics, FALSE) );
SetIntegerProperty(TEXT("win.icon.hspacing"), iconmetrics.iHorzSpacing);
SetIntegerProperty(TEXT("win.icon.vspacing"), iconmetrics.iVertSpacing);
float invScaleX;
float invScaleY;
getInvScale(invScaleX, invScaleY);
SetIntegerProperty(TEXT("win.icon.hspacing"), rescale(iconmetrics.iHorzSpacing, invScaleX));
SetIntegerProperty(TEXT("win.icon.vspacing"), rescale(iconmetrics.iVertSpacing, invScaleY));
SetBooleanProperty(TEXT("win.icon.titleWrappingOn"), iconmetrics.iTitleWrap != 0);
SetFontProperty(TEXT("win.icon.font"), iconmetrics.lfFont);
SetFontProperty(TEXT("win.icon.font"), iconmetrics.lfFont, invScaleY);
}
/*
Windows settings for these are also in the registry
......@@ -718,6 +750,7 @@ void AwtDesktopProperties::SetStringProperty(LPCTSTR propName, LPTSTR value) {
}
void AwtDesktopProperties::SetIntegerProperty(LPCTSTR propName, int value) {
jstring key = JNU_NewStringPlatform(GetEnv(), propName);
if (key == NULL) {
throw std::bad_alloc();
......@@ -752,7 +785,7 @@ void AwtDesktopProperties::SetColorProperty(LPCTSTR propName, DWORD value) {
}
void AwtDesktopProperties::SetFontProperty(HDC dc, int fontID,
LPCTSTR propName) {
LPCTSTR propName, float invScale) {
HGDIOBJ font = GetStockObject(fontID);
if (font != NULL && SelectObject(dc, font) != NULL) {
int length = GetTextFace(dc, 0, NULL);
......@@ -789,8 +822,8 @@ void AwtDesktopProperties::SetFontProperty(HDC dc, int fontID,
throw std::bad_alloc();
}
jint pointSize = metrics.tmHeight -
metrics.tmInternalLeading;
jint pointSize = rescale(metrics.tmHeight -
metrics.tmInternalLeading, invScale);
jint style = java_awt_Font_PLAIN;
if (metrics.tmWeight >= FW_BOLD) {
......@@ -818,7 +851,8 @@ void AwtDesktopProperties::SetFontProperty(HDC dc, int fontID,
}
}
void AwtDesktopProperties::SetFontProperty(LPCTSTR propName, const LOGFONT & font) {
void AwtDesktopProperties::SetFontProperty(LPCTSTR propName, const LOGFONT & font,
float invScale) {
jstring fontName;
jint pointSize;
jint style;
......@@ -836,7 +870,7 @@ void AwtDesktopProperties::SetFontProperty(LPCTSTR propName, const LOGFONT & fon
ReleaseDC(NULL, hdc);
#endif
// Java uses point sizes, but assumes 1 pixel = 1 point
pointSize = -font.lfHeight;
pointSize = rescale(-font.lfHeight, invScale);
// convert Windows font style to Java style
style = java_awt_Font_PLAIN;
......
......@@ -73,8 +73,8 @@ class AwtDesktopProperties {
void SetIntegerProperty(LPCTSTR, int);
void SetStringProperty(LPCTSTR, LPTSTR);
void SetColorProperty(LPCTSTR, DWORD);
void SetFontProperty(HDC, int, LPCTSTR);
void SetFontProperty(LPCTSTR, const LOGFONT &);
void SetFontProperty(HDC, int, LPCTSTR, float invScale);
void SetFontProperty(LPCTSTR, const LOGFONT &, float invScale);
void SetSoundProperty(LPCTSTR, LPCTSTR);
JNIEnv * GetEnv() {
......
......@@ -17,5 +17,8 @@ othervm.dirs=java/awt java/beans java/rmi javax/accessibility javax/imageio java
# Tests that cannot run concurrently
exclusiveAccess.dirs=java/rmi/Naming java/util/Currency java/util/prefs sun/management/jmxremote sun/tools/jstatd sun/security/mscapi javax/rmi
# Allow querying of sun.arch.data.model in @requires clauses
requires.properties=sun.arch.data.model
# Group definitions
groups=TEST.groups [closed/TEST.groups]
/*
* Copyright (c) 2014, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
/**
* @test
* @bug 8043836
* @summary Test AES ciphers with different modes and padding schemes (ECB mode
* doesn't use IV). The test tries 3 different read methods of
* CipherInputStream.
*/
public class CICO {
private static final String ALGORITHM = "aEs";
private static final String[] MODES = { "PCBC", "ECb", "cbC", "cFB",
"cFB24", "cFB32", "Cfb40", "CFB72", "OfB", "OfB20", "OfB48",
"OfB56", "OFB64", "OFB112", "CFB112", "pCbC" };
private static final String[] PADDING = { "noPadding", "pkcs5padding" };
private static final String PROVIDER = "SunJCE";
private static final int NREADS = 3;
private static final int KEY_LENGTH = 128;
private final byte[] plainText = new byte[1600000];
public static void main(String argv[]) throws Exception {
CICO test = new CICO();
for (String mode : MODES) {
for (String pad : PADDING) {
for (int m = 0; m < NREADS; m++) {
test.runTest(ALGORITHM, mode, pad, m);
}
}
}
}
public void runTest(String algo, String mo, String pad, int whichRead) throws Exception {
Cipher ci1 = null;
Cipher ci2 = null;
byte[] iv = null;
AlgorithmParameterSpec aps = null;
SecretKey key = null;
try {
// Do initialization
Random rdm = new Random();
rdm.nextBytes(plainText);
KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
if (!kg.getAlgorithm().equals(algo)) {
throw new RuntimeException("Unexpected algorithm <"
+ kg.getAlgorithm() + ">, expected value is <" + algo
+ ">");
}
kg.init(KEY_LENGTH);
key = kg.generateKey();
ci1 = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
if (mo.equalsIgnoreCase("ECB")) {
ci1.init(Cipher.ENCRYPT_MODE, key);
} else {
ci1.init(Cipher.ENCRYPT_MODE, key, aps);
}
if (!mo.equalsIgnoreCase("ECB")) {
iv = ci1.getIV();
aps = new IvParameterSpec(iv);
} else {
aps = null;
}
ci2 = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
if (mo.equalsIgnoreCase("ECB")) {
ci2.init(Cipher.DECRYPT_MODE, key);
} else {
ci2.init(Cipher.DECRYPT_MODE, key, aps);
}
ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
try (CipherInputStream ciInput = new CipherInputStream(baInput, ci1);
CipherOutputStream ciOutput = new CipherOutputStream(
baOutput, ci2)) {
// According to specification, CipherInputStream does not support the
// mark and reset methods
if (ciInput.markSupported()) {
throw new RuntimeException(
"CipherInputStream unexpectedly supports the mark and reset methods");
}
// Read from the input and write to the output using 2 types
// of buffering : byte[] and int
switch (whichRead) {
case 0:
int buffer0 = ciInput.read();
while (buffer0 != -1) {
ciOutput.write(buffer0);
buffer0 = ciInput.read();
}
break;
case 1:
byte[] buffer1 = new byte[20];
int len1 = ciInput.read(buffer1);
while (len1 != -1) {
ciOutput.write(buffer1, 0, len1);
len1 = ciInput.read(buffer1);
}
break;
case NREADS - 1:
byte[] buffer2 = new byte[ci1
.getOutputSize(plainText.length)];
int offset2 = 0;
int len2 = 0;
while (len2 != -1) {
len2 = ciInput.read(buffer2, offset2, buffer2.length
- offset2);
offset2 += len2;
}
ciOutput.write(buffer2, 0, buffer2.length);
break;
}
}
// Get the output
byte[] recoveredText = new byte[baOutput.size()];
recoveredText = baOutput.toByteArray();
if (!java.util.Arrays.equals(plainText, recoveredText)) {
throw new RuntimeException(
"Original text is not equal with recovered text, with "
+ algo + "/" + mo + "/" + pad + "/" + whichRead);
}
// Compare input and output
} catch (NoSuchAlgorithmException e) {
//OFB20 is for negative testing
if (!mo.equalsIgnoreCase("OFB20")) {
System.out.println("Unexpected NoSuchAlgorithmException with "
+ algo + "/" + mo + "/" + pad + "/" + whichRead);
throw new RuntimeException("Test failed!");
}
} catch (IOException | NoSuchProviderException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException e) {
System.out.println("Unexpected Exception with "
+ algo + "/" + mo + "/" + pad + "/" + whichRead);
System.out.println("Test failed!");
throw e;
}
}
}
/*
* Copyright (c) 2014, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
/**
* @test
* @bug 8043836
* @summary Test AES ciphers with 4 different modes with NoPadding. Check if
* data before encryption and after decryption is the same.
*/
public class CTR {
private static final String ALGORITHM = "AES";
private static final String PROVIDER = "SunJCE";
private static final String[] MODES = {"CTR","CFB24","OFB32","GCM"};
private static final String PADDING = "NoPadding";
private static final int KEY_LENGTH = 128;
public static void main(String argv[]) throws Exception {
CTR test = new CTR();
for (String mode : MODES) {
test.runTest(ALGORITHM, mode, PADDING);
}
}
public void runTest(String algo, String mo, String pad) throws Exception {
Cipher ci = null;
byte[] iv = null;
AlgorithmParameterSpec aps = null;
SecretKey key = null;
try {
Random rdm = new Random();
byte[] plainText;
ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
kg.init(KEY_LENGTH);
key = kg.generateKey();
for (int i = 0; i < 15; i++) {
plainText = new byte[1600 + i + 1];
rdm.nextBytes(plainText);
if (!mo.equalsIgnoreCase("GCM")) {
ci.init(Cipher.ENCRYPT_MODE, key, aps);
} else {
ci.init(Cipher.ENCRYPT_MODE, key);
}
byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
int offset = ci.update(plainText, 0, plainText.length,
cipherText, 0);
ci.doFinal(cipherText, offset);
if (!mo.equalsIgnoreCase("ECB")) {
iv = ci.getIV();
aps = new IvParameterSpec(iv);
} else {
aps = null;
}
if (!mo.equalsIgnoreCase("GCM")) {
ci.init(Cipher.DECRYPT_MODE, key, aps);
} else {
ci.init(Cipher.DECRYPT_MODE, key, ci.getParameters());
}
byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
int len = ci.doFinal(cipherText, 0, cipherText.length,
recoveredText);
byte[] tmp = new byte[len];
for (int j = 0; j < len; j++) {
tmp[j] = recoveredText[j];
}
Arrays.toString(plainText);
if (!java.util.Arrays.equals(plainText, tmp)) {
System.out.println("Original: ");
dumpBytes(plainText);
System.out.println("Recovered: ");
dumpBytes(tmp);
throw new RuntimeException("Original text is not equal with recovered text, with mode:" + mo);
}
}
} catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| ShortBufferException | IllegalBlockSizeException
| BadPaddingException e) {
System.out.println("Test failed!");
throw e;
}
}
private void dumpBytes(byte[] bytes){
for (byte b : bytes){
System.out.print(Integer.toHexString(b));
}
System.out.println();
}
}
/*
* Copyright (c) 2014, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
/**
* @test
* @bug 8043836
* @summary Test AES ciphers with different modes and padding schemes (ECB mode
* doesn't use IV). The test tries 3 different read methods of
* CipherInputStream.
*/
public class Padding {
private static final String ALGORITHM = "AES";
private static final String PROVIDER = "SunJCE";
private static final String[] MODES = { "ECb", "CbC", "PCBC", "OFB",
"OFB150", "cFB", "CFB7", "cFB8", "cFB16", "cFB24", "cFB32",
"Cfb40", "cfB48", "cfB56", "cfB64", "cfB72", "cfB80", "cfB88",
"cfB96", "cfb104", "cfB112", "cfB120", "OFB8", "OFB16", "OFB24",
"OFB32", "OFB40", "OFB48", "OFB56", "OFB64", "OFB72", "OFB80",
"OFB88", "OFB96", "OFB104", "OFB112", "OFB120", "GCM" };
private static final String PADDING = "PKCS5Padding";
private static final int KEY_LENGTH = 128;
public static void main(String argv[]) throws Exception {
Padding test = new Padding();
for (String mode : MODES) {
test.runTest(ALGORITHM, mode, PADDING);
}
}
public void runTest(String algo, String mo, String pad) throws Exception {
Cipher ci = null;
byte[] iv = null;
AlgorithmParameterSpec aps = null;
SecretKey key = null;
try {
Random rdm = new Random();
byte[] plainText;
ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
kg.init(KEY_LENGTH);
key = kg.generateKey();
for (int i = 0; i < 15; i++) {
plainText = new byte[1600 + i + 1];
rdm.nextBytes(plainText);
if (!mo.equalsIgnoreCase("GCM")) {
ci.init(Cipher.ENCRYPT_MODE, key, aps);
} else {
ci.init(Cipher.ENCRYPT_MODE, key);
}
byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
int offset = ci.update(plainText, 0, plainText.length,
cipherText, 0);
ci.doFinal(cipherText, offset);
if (!mo.equalsIgnoreCase("ECB")) {
iv = ci.getIV();
aps = new IvParameterSpec(iv);
} else {
aps = null;
}
if (!mo.equalsIgnoreCase("GCM")) {
ci.init(Cipher.DECRYPT_MODE, key, aps);
} else {
ci.init(Cipher.DECRYPT_MODE, key, ci.getParameters());
}
byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
int len = ci.doFinal(cipherText, 0, cipherText.length,
recoveredText);
byte[] tmp = new byte[len];
for (int j = 0; j < len; j++) {
tmp[j] = recoveredText[j];
}
if (!java.util.Arrays.equals(plainText, tmp)) {
System.out.println("Original: ");
dumpBytes(plainText);
System.out.println("Recovered: ");
dumpBytes(tmp);
throw new RuntimeException(
"Original text is not equal with recovered text, with mode:"
+ mo);
}
}
} catch (NoSuchAlgorithmException e) {
//CFB7 and OFB150 are for negative testing
if (!mo.equalsIgnoreCase("CFB7") && !mo.equalsIgnoreCase("OFB150")) {
System.out
.println("Unexpected NoSuchAlgorithmException with mode: "
+ mo);
throw new RuntimeException("Test failed!");
}
} catch ( NoSuchProviderException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| ShortBufferException | IllegalBlockSizeException
| BadPaddingException e) {
System.out.println("Test failed!");
throw e;
}
}
private void dumpBytes(byte[] bytes) {
for (byte b : bytes) {
System.out.print(Integer.toHexString(b));
}
System.out.println();
}
}
/*
* Copyright (c) 2014, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
/**
* @test
* @bug 8043836
* @summary Test AES ciphers with different modes and padding schemes (ECB mode
* doesn't use IV).
* @author Liwen Wang
* @author Parag Salvi
*/
public class TestAESCipher {
private static final String ALGORITHM = "AES";
private static final String PROVIDER = "SunJCE";
private static final String[] MODES = { "ECb", "CbC", "CTR", "PCBC", "OFB",
"OFB150", "cFB", "CFB7", "cFB8", "cFB16", "cFB24", "cFB32",
"Cfb40", "cfB48", "cfB56", "cfB64", "cfB72", "cfB80", "cfB88",
"cfB96", "cfb104", "cfB112", "cfB120", "OFB8", "OFB16", "OFB24",
"OFB32", "OFB40", "OFB48", "OFB56", "OFB64", "OFB72", "OFB80",
"OFB88", "OFB96", "OFB104", "OFB112", "OFB120", "GCM" };
private static final String[] PADDING = { "NoPadding", "PKCS5Padding" };
private static final int KEY_LENGTH = 128;
public static void main(String argv[]) throws Exception {
TestAESCipher test = new TestAESCipher();
for (String mode : MODES) {
int padKinds = 1;
if (mode.equalsIgnoreCase("ECB") || mode.equalsIgnoreCase("PCBC")
|| mode.equalsIgnoreCase("CBC")) {
padKinds = PADDING.length;
}
for (int k = 0; k < padKinds; k++) {
test.runTest(ALGORITHM, mode, PADDING[k]);
}
}
}
public void runTest(String algo, String mo, String pad) throws Exception {
Cipher ci = null;
byte[] iv = null;
AlgorithmParameterSpec aps = null;
SecretKey key = null;
try {
// Initialization
Random rdm = new Random();
byte[] plainText = new byte[128];
rdm.nextBytes(plainText);
ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
kg.init(KEY_LENGTH);
key = kg.generateKey();
// encrypt
if (!mo.equalsIgnoreCase("GCM")) {
ci.init(Cipher.ENCRYPT_MODE, key, aps);
} else {
ci.init(Cipher.ENCRYPT_MODE, key);
}
byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
int offset = ci.update(plainText, 0, plainText.length, cipherText,
0);
ci.doFinal(cipherText, offset);
if (!mo.equalsIgnoreCase("ECB")) {
iv = ci.getIV();
aps = new IvParameterSpec(iv);
} else {
aps = null;
}
if (!mo.equalsIgnoreCase("GCM")) {
ci.init(Cipher.DECRYPT_MODE, key, aps);
} else {
ci.init(Cipher.DECRYPT_MODE, key, ci.getParameters());
}
byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)];
int len = ci.doFinal(cipherText, 0, cipherText.length,
recoveredText);
byte[] tmp = new byte[len];
System.arraycopy(recoveredText, 0, tmp, 0, len);
// Comparison
if (!java.util.Arrays.equals(plainText, tmp)) {
System.out.println("Original: ");
dumpBytes(plainText);
System.out.println("Recovered: ");
dumpBytes(tmp);
throw new RuntimeException(
"Original text is not equal with recovered text, with mode:"
+ mo);
}
} catch (NoSuchAlgorithmException e) {
//CFB7 and OFB150 are for negative testing
if (!mo.equalsIgnoreCase("CFB7") && !mo.equalsIgnoreCase("OFB150")) {
System.out.println("Unexpected NoSuchAlgorithmException with mode: "
+ mo);
throw new RuntimeException("Test failed!");
}
} catch ( NoSuchProviderException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| ShortBufferException | IllegalBlockSizeException
| BadPaddingException e) {
System.out.println("Test failed!");
throw e;
}
}
private void dumpBytes(byte[] bytes) {
for (byte b : bytes) {
System.out.print(Integer.toHexString(b));
}
System.out.println();
}
}
/*
* Copyright (c) 2014, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.InvalidParameterSpecException;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.GCMParameterSpec;
/**
* @test
* @bug 8043836
* @summary Test AES encryption with no padding. Expect the original data length
* is the same as the encrypted data.
*/
public class TestNonexpanding {
private static final String ALGORITHM = "AES";
private static final String PROVIDER = "SunJCE";
private static final String[] MODES = { "ECb", "CbC", "OFB", "OFB150",
"cFB", "CFB7", "cFB8", "cFB16", "cFB24", "cFB32", "Cfb40", "cfB48",
"cfB56", "cfB64", "cfB72", "cfB80", "cfB88", "cfB96", "cfb104",
"cfB112", "cfB120", "GCM" };
private static final String PADDING = "NoPadding";
private static final int KEY_LENGTH = 128;
public static void main(String argv[]) throws Exception {
TestNonexpanding test = new TestNonexpanding();
for (String mode : MODES) {
test.runTest(ALGORITHM, mode, PADDING);
}
}
public void runTest(String algo, String mo, String pad) throws Exception {
Cipher ci = null;
SecretKey key = null;
try {
// Initialization
Random rdm = new Random();
byte[] plainText = new byte[128];
rdm.nextBytes(plainText);
ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
kg.init(KEY_LENGTH);
key = kg.generateKey();
// encrypt
ci.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
int offset = ci.update(plainText, 0, plainText.length, cipherText,
0);
ci.doFinal(cipherText, offset);
// Comparison
if (!(plainText.length == cipherText.length)) {
// The result of encryption in GCM is a combination of an
// authentication tag and cipher text.
if (mo.equalsIgnoreCase("GCM")) {
GCMParameterSpec spec = ci.getParameters().getParameterSpec(GCMParameterSpec.class);
int cipherTextLength = cipherText.length - spec.getTLen()
/ 8;
if (plainText.length == cipherTextLength) {
return;
}
}
System.out.println("Original length: " + plainText.length);
System.out.println("Cipher text length: " + cipherText.length);
throw new RuntimeException("Test failed!");
}
} catch (NoSuchAlgorithmException e) {
//CFB7 and OFB150 are for negative testing
if (!mo.equalsIgnoreCase("CFB7") && !mo.equalsIgnoreCase("OFB150")) {
System.out.println("Unexpected NoSuchAlgorithmException with mode: "
+ mo);
throw new RuntimeException("Test failed!");
}
} catch ( NoSuchProviderException | NoSuchPaddingException
| InvalidKeyException | InvalidParameterSpecException
| ShortBufferException | IllegalBlockSizeException
| BadPaddingException e) {
System.out.println("Test failed!");
throw e;
}
}
}
/*
* Copyright (c) 2014, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Random;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
/**
* @test
* @bug 8043836
* @summary Test AES ciphers with different modes and padding schemes (ECB mode
* doesn't use IV). The test tries 3 different read methods of
* CipherInputStream.
*/
public class TestSameBuffer {
private static final String ALGORITHM = "Rijndael";
private static final String PROVIDER = "SunJCE";
private static final String[] MODES = { "ECb", "CbC", "OFB", "CFB150",
"cFB", "CFB7", " cFB8", "cFB16", "cFB24", "cFB32", "Cfb40",
"cfB48", " cfB56", "cfB64", "cfB72", "cfB80", "cfB88", "cfB96",
"cfb104", "cfB112", "cfB120" };
private static final String PADDING = "NoPadding";
private static final int KEY_LENGTH = 128;
public static void main(String argv[]) throws Exception {
TestSameBuffer test = new TestSameBuffer();
for (String mode : MODES) {
test.runTest(ALGORITHM, mode, PADDING);
}
}
public void runTest(String algo, String mo, String pad) throws Exception {
Cipher ci = null;
byte[] iv = null;
AlgorithmParameterSpec aps = null;
SecretKey key = null;
try {
// Initialization
Random rdm = new Random();
byte[] plainText = new byte[128];
rdm.nextBytes(plainText);
// keep the plain text
byte[] tmpText = new byte[plainText.length];
for (int i = 0; i < plainText.length; i++) {
tmpText[i] = plainText[i];
}
ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
kg.init(KEY_LENGTH);
key = kg.generateKey();
// encrypt
ci.init(Cipher.ENCRYPT_MODE, key);
int offset = ci
.update(plainText, 0, plainText.length, plainText, 0);
ci.doFinal(plainText, offset);
if (!mo.equalsIgnoreCase("ECB")) {
iv = ci.getIV();
aps = new IvParameterSpec(iv);
} else {
aps = null;
}
ci.init(Cipher.DECRYPT_MODE, key, aps);
byte[] recoveredText = new byte[ci.getOutputSize(plainText.length)];
ci.doFinal(plainText, 0, plainText.length, recoveredText);
// Comparison
if (!java.util.Arrays.equals(tmpText, recoveredText)) {
System.out.println("Original: ");
dumpBytes(plainText);
System.out.println("Recovered: ");
dumpBytes(recoveredText);
throw new RuntimeException(
"Original text is not equal with recovered text, with mode:"
+ mo);
}
} catch (NoSuchAlgorithmException e) {
//CFB7 and CFB150 are for negative testing
if (!mo.equalsIgnoreCase("CFB7") && !mo.equalsIgnoreCase("CFB150")) {
System.out.println("Unexpected NoSuchAlgorithmException with mode: "
+ mo);
throw new RuntimeException("Test failed!");
}
} catch (NoSuchProviderException | NoSuchPaddingException
| InvalidKeyException | InvalidAlgorithmParameterException
| ShortBufferException | IllegalBlockSizeException
| BadPaddingException e) {
System.out.println("Test failed!");
throw e;
}
}
private void dumpBytes(byte[] bytes) {
for (byte b : bytes) {
System.out.print(Integer.toHexString(b));
}
System.out.println();
}
}
/*
* Copyright (c) 2016 Red Hat Inc.
*
* 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4858370
* @summary JDWP: Memory Leak (global references not deleted after invokeMethod).
*
* @author Severin Gehwolf <sgehwolf@redhat.com>
*
* @library ..
* @run build TestScaffold VMConnection TargetListener TargetAdapter
* @run compile -g OomDebugTest.java
* @run shell OomDebugTestSetup.sh
* @run main OomDebugTest OomDebugTestTarget test1
* @run main OomDebugTest OomDebugTestTarget test2
* @run main OomDebugTest OomDebugTestTarget test3
* @run main OomDebugTest OomDebugTestTarget test4
* @run main OomDebugTest OomDebugTestTarget test5
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.sun.jdi.ArrayReference;
import com.sun.jdi.ArrayType;
import com.sun.jdi.ClassType;
import com.sun.jdi.Field;
import com.sun.jdi.InvocationException;
import com.sun.jdi.Method;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.StackFrame;
import com.sun.jdi.VMOutOfMemoryException;
import com.sun.jdi.Value;
import com.sun.jdi.event.BreakpointEvent;
/***************** Target program **********************/
class OomDebugTestTarget {
OomDebugTestTarget() {
System.out.println("DEBUG: invoked constructor");
}
static class FooCls {
@SuppressWarnings("unused")
private byte[] bytes = new byte[3000000];
};
FooCls fooCls = new FooCls();
byte[] byteArray = new byte[0];
void testMethod(FooCls foo) {
System.out.println("DEBUG: invoked 'void testMethod(FooCls)', foo == " + foo);
}
void testPrimitive(byte[] foo) {
System.out.println("DEBUG: invoked 'void testPrimitive(byte[])', foo == " + foo);
}
byte[] testPrimitiveArrRetval() {
System.out.println("DEBUG: invoked 'byte[] testPrimitiveArrRetval()'");
return new byte[3000000];
}
FooCls testFooClsRetval() {
System.out.println("DEBUG: invoked 'FooCls testFooClsRetval()'");
return new FooCls();
}
public void entry() {}
public static void main(String[] args){
System.out.println("DEBUG: OomDebugTestTarget.main");
new OomDebugTestTarget().entry();
}
}
/***************** Test program ************************/
public class OomDebugTest extends TestScaffold {
private static final int TOTAL_TESTS = 1;
private ReferenceType targetClass;
private ObjectReference thisObject;
private int failedTests;
private final String testMethodName;
public OomDebugTest(String[] args) {
super(args);
if (args.length != 2) {
throw new RuntimeException("Test failed unexpectedly.");
}
testMethodName = args[1];
}
@Override
protected void runTests() throws Exception {
try {
/*
* Get to the top of entry()
* to determine targetClass and mainThread
*/
BreakpointEvent bpe = startTo("OomDebugTestTarget", "entry", "()V");
targetClass = bpe.location().declaringType();
mainThread = bpe.thread();
StackFrame frame = mainThread.frame(0);
thisObject = frame.thisObject();
java.lang.reflect.Method m = findTestMethod();
m.invoke(this);
} catch (NoSuchMethodException e) {
e.printStackTrace();
failure();
} catch (SecurityException e) {
e.printStackTrace();
failure();
}
}
private java.lang.reflect.Method findTestMethod()
throws NoSuchMethodException, SecurityException {
return OomDebugTest.class.getDeclaredMethod(testMethodName);
}
private void failure() {
failedTests++;
}
/*
* Test case: Object reference as method parameter.
*/
@SuppressWarnings("unused") // called via reflection
private void test1() throws Exception {
System.out.println("DEBUG: ------------> Running " + testMethodName);
try {
Field field = targetClass.fieldByName("fooCls");
ClassType clsType = (ClassType)field.type();
Method constructor = getConstructorForClass(clsType);
for (int i = 0; i < 15; i++) {
@SuppressWarnings({ "rawtypes", "unchecked" })
ObjectReference objRef = clsType.newInstance(mainThread,
constructor,
new ArrayList(0),
ObjectReference.INVOKE_NONVIRTUAL);
invoke("testMethod", "(LOomDebugTestTarget$FooCls;)V", objRef);
}
} catch (InvocationException e) {
handleFailure(e);
}
}
/*
* Test case: Array reference as method parameter.
*/
@SuppressWarnings("unused") // called via reflection
private void test2() throws Exception {
System.out.println("DEBUG: ------------> Running " + testMethodName);
try {
Field field = targetClass.fieldByName("byteArray");
ArrayType arrType = (ArrayType)field.type();
for (int i = 0; i < 15; i++) {
ArrayReference byteArrayVal = arrType.newInstance(3000000);
invoke("testPrimitive", "([B)V", byteArrayVal);
}
} catch (VMOutOfMemoryException e) {
defaultHandleOOMFailure(e);
}
}
/*
* Test case: Array reference as return value.
*/
@SuppressWarnings("unused") // called via reflection
private void test3() throws Exception {
System.out.println("DEBUG: ------------> Running " + testMethodName);
try {
for (int i = 0; i < 15; i++) {
invoke("testPrimitiveArrRetval",
"()[B",
Collections.EMPTY_LIST,
vm().mirrorOfVoid());
}
} catch (InvocationException e) {
handleFailure(e);
}
}
/*
* Test case: Object reference as return value.
*/
@SuppressWarnings("unused") // called via reflection
private void test4() throws Exception {
System.out.println("DEBUG: ------------> Running " + testMethodName);
try {
for (int i = 0; i < 15; i++) {
invoke("testFooClsRetval",
"()LOomDebugTestTarget$FooCls;",
Collections.EMPTY_LIST,
vm().mirrorOfVoid());
}
} catch (InvocationException e) {
handleFailure(e);
}
}
/*
* Test case: Constructor
*/
@SuppressWarnings({ "unused", "unchecked", "rawtypes" }) // called via reflection
private void test5() throws Exception {
System.out.println("DEBUG: ------------> Running " + testMethodName);
try {
ClassType type = (ClassType)thisObject.type();
for (int i = 0; i < 15; i++) {
type.newInstance(mainThread,
findMethod(targetClass, "<init>", "()V"),
new ArrayList(0),
ObjectReference.INVOKE_NONVIRTUAL);
}
} catch (InvocationException e) {
handleFailure(e);
}
}
private Method getConstructorForClass(ClassType clsType) {
List<Method> methods = clsType.methodsByName("<init>");
if (methods.size() != 1) {
throw new RuntimeException("FAIL. Expected only one, the default, constructor");
}
return methods.get(0);
}
private void handleFailure(InvocationException e) {
// There is no good way to see the OOME diagnostic message in the target since the
// TestScaffold might throw an exception while trying to print the stack trace. I.e
// it might get a a VMDisconnectedException before the stack trace printing finishes.
System.err.println("FAILURE: InvocationException caused by OOM");
defaultHandleOOMFailure(e);
}
private void defaultHandleOOMFailure(Exception e) {
e.printStackTrace();
failure();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
void invoke(String methodName, String methodSig, Value value)
throws Exception {
List args = new ArrayList(1);
args.add(value);
invoke(methodName, methodSig, args, value);
}
void invoke(String methodName,
String methodSig,
@SuppressWarnings("rawtypes") List args,
Value value) throws Exception {
Method method = findMethod(targetClass, methodName, methodSig);
if ( method == null) {
failure("FAILED: Can't find method: "
+ methodName + " for class = " + targetClass);
return;
}
invoke(method, args, value);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
void invoke(Method method, List args, Value value) throws Exception {
thisObject.invokeMethod(mainThread, method, args, 0);
System.out.println("DEBUG: Done invoking method via debugger.");
}
Value fieldValue(String fieldName) {
Field field = targetClass.fieldByName(fieldName);
return thisObject.getValue(field);
}
public static void main(String[] args) throws Exception {
OomDebugTest oomTest = new OomDebugTest(args);
oomTest.startTests();
if (oomTest.failedTests > 0) {
throw new RuntimeException(oomTest.failedTests
+ " of " + TOTAL_TESTS + " test(s) failed.");
}
System.out.println("All " + TOTAL_TESTS + " tests passed.");
}
}
#!/bin/sh
#
# Copyright (c) 2016 Red Hat Inc.
# 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.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
if [ "${TESTSRC}" = "" ]
then
echo "TESTSRC not set. Test cannot execute. Failed."
exit 1
fi
echo "TESTSRC=${TESTSRC}"
if [ "${TESTJAVA}" = "" ]
then
echo "TESTJAVA not set. Test cannot execute. Failed."
exit 1
fi
echo "TESTJAVA=${TESTJAVA}"
if [ "${TESTCLASSES}" = "" ]
then
echo "TESTCLASSES not set. Test cannot execute. Failed."
exit 1
fi
cp ${TESTSRC}/@debuggeeVMOptions ${TESTCLASSES}/
/*
* Copyright (c) 2016, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
/*
* @test
* @bug 8076545
* @summary Text size is twice bigger under Windows L&F on Win 8.1 with
* HiDPI display
*/
public class FontScalingTest {
public static void main(String[] args) throws Exception {
int metalFontSize = getFontSize(MetalLookAndFeel.class.getName());
int systemFontSize = getFontSize(UIManager.getSystemLookAndFeelClassName());
if (Math.abs(systemFontSize - metalFontSize) > 8) {
throw new RuntimeException("System L&F is too big!");
}
}
private static int getFontSize(String laf) throws Exception {
UIManager.setLookAndFeel(laf);
final int[] sizes = new int[1];
SwingUtilities.invokeAndWait(() -> {
JButton button = new JButton("Test");
sizes[0] = button.getFont().getSize();
});
return sizes[0];
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import jdk.testlibrary.RandomFactory;
/*
* @test
* @bug 8050374
* @key randomness
* @summary This test validates signature verification
* Signature.verify(byte[], int, int). The test uses RandomFactory to
* get random set of clear text data to sign. After the signature
* generation, the test tries to verify signature with the above API
* and passing in different signature offset (0, 33, 66, 99).
* @library /lib/testlibrary
* @run main Offsets SUN NONEwithDSA
* @run main Offsets SUN SHA1withDSA
* @run main Offsets SUN SHA224withDSA
* @run main Offsets SUN SHA256withDSA
*/
public class Offsets {
private final int size;
private final byte[] cleartext;
private final PublicKey pubkey;
private final Signature signature;
private final byte[] signed;
private Offsets(Signature signature, PublicKey pubkey, PrivateKey privkey,
int size, byte[] cleartext) throws InvalidKeyException,
SignatureException {
this.pubkey = pubkey;
this.signature = signature;
this.size = size;
this.cleartext = cleartext;
signature.initSign(privkey);
signature.update(cleartext, 0, size);
signed = signature.sign();
}
int getDataSize() {
return size;
}
int getSignatureLength() {
return signed.length;
}
byte[] shiftSignData(int offset) {
byte[] testSignData = new byte[offset + signed.length];
System.arraycopy(signed, 0, testSignData, offset,
signed.length);
return testSignData;
}
boolean verifySignature(byte[] sigData, int sigOffset, int sigLength,
int updateOffset, int updateLength)
throws InvalidKeyException, SignatureException {
signature.initVerify(pubkey);
signature.update(cleartext, updateOffset, updateLength);
return signature.verify(sigData, sigOffset, sigLength);
}
static Offsets init(String provider, String algorithm)
throws NoSuchAlgorithmException, NoSuchProviderException,
InvalidKeyException, SignatureException {
// fill the cleartext data with random bytes
byte[] cleartext = new byte[100];
RandomFactory.getRandom().nextBytes(cleartext);
// NONEwith requires input to be of 20 bytes
int size = algorithm.contains("NONEwith") ? 20 : 100;
// create signature instance
Signature signature = Signature.getInstance(algorithm, provider);
String keyAlgo;
if (algorithm.contains("RSA")) {
keyAlgo = "RSA";
} else if (algorithm.contains("ECDSA")) {
keyAlgo = "EC";
} else if (algorithm.contains("DSA")) {
keyAlgo = "DSA";
} else {
throw new RuntimeException("Test doesn't support this signature "
+ "algorithm: " + algorithm);
}
KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo, provider);
KeyPair kp = kpg.generateKeyPair();
PublicKey pubkey = kp.getPublic();
PrivateKey privkey = kp.getPrivate();
return new Offsets(signature, pubkey, privkey, size, cleartext);
}
public static void main(String[] args) throws NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
if (args.length < 2) {
throw new RuntimeException("Wrong parameters");
}
boolean result = true;
try {
Offsets test = init(args[0], args[1]);
// We are trying 3 different offsets, data size has nothing to do
// with signature length
for (int chunk = 3; chunk > 0; chunk--) {
int signOffset = test.getDataSize() / chunk;
System.out.println("Running test with offset " + signOffset);
byte[] signData = test.shiftSignData(signOffset);
boolean success = test.verifySignature(signData, signOffset,
test.getSignatureLength(), 0, test.getDataSize());
if (success) {
System.out.println("Successfully verified with offset "
+ signOffset);
} else {
System.out.println("Verification failed with offset "
+ signOffset);
result = false;
}
}
// save signature to offset 0
byte[] signData = test.shiftSignData(0);
// Negative tests
// Test signature offset 0.
// Wrong test data will be passed to update,
// so signature verification should fail.
for (int chunk = 3; chunk > 0; chunk--) {
int dataOffset = (test.getDataSize() - 1) / chunk;
boolean success;
try {
success = test.verifySignature(signData, 0,
test.getSignatureLength(), dataOffset,
(test.getDataSize() - dataOffset));
} catch (SignatureException e) {
// Since we are trying different data size, it can throw
// SignatureException
success = false;
}
if (!success) {
System.out.println("Signature verification failed "
+ "as expected, with data offset " + dataOffset
+ " and length "
+ (test.getDataSize() - dataOffset));
} else {
System.out.println("Signature verification "
+ "should not succeed, with data offset "
+ dataOffset + " and length "
+ (test.getDataSize() - dataOffset));
result = false;
}
}
// Tests with manipulating offset and length
result &= Offsets.checkFailure(test, signData, -1,
test.getSignatureLength());
result &= Offsets.checkFailure(test, signData, 0,
test.getSignatureLength() - 1);
result &= Offsets.checkFailure(test, signData,
test.getSignatureLength() + 1, test.getSignatureLength());
result &= Offsets.checkFailure(test, signData, 0,
test.getSignatureLength() + 1);
result &= Offsets.checkFailure(test, signData, 0, 0);
result &= Offsets.checkFailure(test, signData, 0, -1);
result &= Offsets.checkFailure(test, signData,
2147483646, test.getSignatureLength());
result &= Offsets.checkFailure(test, null, 0,
test.getSignatureLength());
} catch (NoSuchProviderException nspe) {
System.out.println("No such provider: " + nspe);
}
if (!result) {
throw new RuntimeException("Some test cases failed");
}
}
static boolean checkFailure(Offsets test, byte[] signData, int offset,
int length) {
boolean success;
try {
success = test.verifySignature(signData, offset, length, 0,
test.getDataSize());
} catch (IllegalArgumentException | SignatureException e) {
System.out.println("Expected exception: " + e);
success = false;
} catch (InvalidKeyException e) {
System.out.println("Unexpected exception: " + e);
return false;
}
if (!success) {
System.out.println("Signature verification failed as expected, "
+ "with signature offset " + offset + " and length "
+ length);
return true;
} else {
System.out.println("Signature verification should not succeed, "
+ "with signature offset " + offset + " and length "
+ length);
return false;
}
}
}
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.Signature;
import java.security.SignedObject;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;
/*
* @test
* @bug 8050374
* @summary Verify a chain of signed objects
*/
public class Chain {
static enum KeyAlg {
RSA("RSA"),
DSA("DSA"),
EC("EC");
final String name;
KeyAlg(String alg) {
this.name = alg;
}
}
static enum Provider {
Default("default"),
SunRsaSign("SunRsaSign"),
Sun("SUN"),
SunEC("SunEC"),
SunJSSE("SunJSSE"),
SunMSCAPI("SunMSCAPI");
final String name;
Provider(String name) {
this.name = name;
}
}
static enum SigAlg {
MD2withRSA("MD2withRSA"),
MD5withRSA("md5withRSA"),
SHA1withDSA("SHA1withDSA"),
SHA224withDSA("SHA224withDSA"),
SHA256withDSA("SHA256withDSA"),
SHA1withRSA("Sha1withrSA"),
SHA224withRSA("SHA224withRSA"),
SHA256withRSA("SHA256withRSA"),
SHA384withRSA("SHA384withRSA"),
SHA512withRSA("SHA512withRSA"),
SHA1withECDSA("SHA1withECDSA"),
SHA256withECDSA("SHA256withECDSA"),
SHA224withECDSA("SHA224withECDSA"),
SHA384withECDSA("SHA384withECDSA"),
SHA512withECDSA("SHA512withECDSA"),
MD5andSHA1withRSA("MD5andSHA1withRSA");
final String name;
SigAlg(String name) {
this.name = name;
}
}
static class Test {
final Provider provider;
final KeyAlg keyAlg;
final SigAlg sigAlg;
Test(SigAlg sigAlg, KeyAlg keyAlg, Provider privider) {
this.provider = privider;
this.keyAlg = keyAlg;
this.sigAlg = sigAlg;
}
}
private static final Test[] tests = {
new Test(SigAlg.SHA1withDSA, KeyAlg.DSA, Provider.Default),
new Test(SigAlg.MD2withRSA, KeyAlg.RSA, Provider.Default),
new Test(SigAlg.MD5withRSA, KeyAlg.RSA, Provider.Default),
new Test(SigAlg.SHA1withRSA, KeyAlg.RSA, Provider.Default),
new Test(SigAlg.SHA1withDSA, KeyAlg.DSA, Provider.Sun),
new Test(SigAlg.SHA224withDSA, KeyAlg.DSA, Provider.Sun),
new Test(SigAlg.SHA256withDSA, KeyAlg.DSA, Provider.Sun),
};
private static final String str = "to-be-signed";
private static final int N = 3;
public static void main(String argv[]) {
boolean result = Arrays.stream(tests).allMatch((test) -> runTest(test));
if(result) {
System.out.println("All tests passed");
} else {
throw new RuntimeException("Some tests failed");
}
}
static boolean runTest(Test test) {
System.out.format("Test: provider = %s, signature algorithm = %s, "
+ "key algorithm = %s\n",
test.provider, test.sigAlg, test.keyAlg);
try {
// Generate all private/public key pairs
PrivateKey[] privKeys = new PrivateKey[N];
PublicKey[] pubKeys = new PublicKey[N];
PublicKey[] anotherPubKeys = new PublicKey[N];
KeyPairGenerator kpg = KeyPairGenerator.getInstance(
test.keyAlg.name);
for (int j=0; j < N; j++) {
KeyPair kp = kpg.genKeyPair();
KeyPair anotherKp = kpg.genKeyPair();
privKeys[j] = kp.getPrivate();
pubKeys[j] = kp.getPublic();
anotherPubKeys[j] = anotherKp.getPublic();
if (Arrays.equals(pubKeys[j].getEncoded(),
anotherPubKeys[j].getEncoded())) {
System.out.println("Failed: it should not get "
+ "the same pair of public key");
return false;
}
}
Signature signature;
if (test.provider != Provider.Default) {
signature = Signature.getInstance(test.sigAlg.name,
test.provider.name);
} else {
signature = Signature.getInstance(test.sigAlg.name);
}
// Create a chain of signed objects
SignedObject[] objects = new SignedObject[N];
objects[0] = new SignedObject(str, privKeys[0], signature);
for (int j = 1; j < N; j++) {
objects[j] = new SignedObject(objects[j - 1], privKeys[j],
signature);
}
// Verify the chain
int n = objects.length - 1;
SignedObject object = objects[n];
do {
if (!object.verify(pubKeys[n], signature)) {
System.out.println("Failed: verification failed, n = " + n);
return false;
}
if (object.verify(anotherPubKeys[n], signature)) {
System.out.println("Failed: verification should not "
+ "succeed with wrong public key, n = " + n);
return false;
}
object = (SignedObject) object.getObject();
n--;
} while (n > 0);
System.out.println("signed data: " + object.getObject());
if (!str.equals(object.getObject())) {
System.out.println("Failed: signed data is not equal to "
+ "original one");
return false;
}
System.out.println("Test passed");
return true;
} catch (NoSuchProviderException nspe) {
if (test.provider == Provider.SunMSCAPI
&& !System.getProperty("os.name").startsWith("Windows")) {
System.out.println("SunMSCAPI is available only on Windows: "
+ nspe);
return true;
}
System.out.println("Unexpected exception: " + nspe);
return false;
} catch (Exception e) {
System.out.println("Unexpected exception: " + e);
e.printStackTrace(System.out);
return false;
}
}
}
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.Serializable;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import java.security.SignedObject;
/*
* @test
* @bug 8050374
* @summary Checks if a signed object is a copy of an original object
*/
public class Copy {
private static final String DSA = "DSA";
private static final int KEY_SIZE = 512;
private static final int MAGIC = 123;
public static void main(String args[]) throws Exception {
KeyPairGenerator kg = KeyPairGenerator.getInstance(DSA);
kg.initialize(KEY_SIZE);
KeyPair kp = kg.genKeyPair();
Signature signature = Signature.getInstance(DSA);
Test original = new Test();
SignedObject so = new SignedObject(original, kp.getPrivate(),
signature);
System.out.println("Signature algorithm: " + so.getAlgorithm());
signature = Signature.getInstance(DSA, "SUN");
if (!so.verify(kp.getPublic(), signature)) {
throw new RuntimeException("Verification failed");
}
kg = KeyPairGenerator.getInstance(DSA);
kg.initialize(KEY_SIZE);
kp = kg.genKeyPair();
if (so.verify(kp.getPublic(), signature)) {
throw new RuntimeException("Unexpected success");
}
Object copy = so.getObject();
if (!original.equals(copy)) {
throw new RuntimeException("Signed object is not equal "
+ "to original one: " + copy);
}
/*
* The signed object is a copy of an original one.
* Once the copy is made, further manipulation
* of the original object shouldn't has any effect on the copy.
*/
original.set(MAGIC - 1);
copy = so.getObject();
if (original.equals(copy)) {
throw new RuntimeException("Signed object is not a copy "
+ "of original one: " + copy);
}
System.out.println("Test passed");
}
private static class Test implements Serializable {
private int number = MAGIC;
public int get() {
return number;
}
public void set(int magic) {
this.number = magic;
}
@Override
public int hashCode() {
return number;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Test)) {
return false;
}
Test other = (Test) obj;
return number == other.number;
}
@Override
public String toString() {
return "" + number;
}
}
}
/*
* Copyright (c) 1998, 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.security.cert.CertPath;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
/*
* @test
* @bug 8074931
* @summary CertPathEncodingTest tests the ability of the CertPath and
* CertificateFactory to encode and decode CertPaths.
*/
public final class CertPathEncodingTest {
/*
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 935438132 (0x37c1a734)
Signature Algorithm: dsaWithSHA1
Issuer: C=us, O=sun, OU=east, OU=bcn, CN=yassir
Validity
Not Before: Aug 23 19:55:32 1999 GMT
Not After : Aug 22 19:55:32 2000 GMT
Subject: C=us, O=sun, OU=east, OU=bcn
Subject Public Key Info:
Public Key Algorithm: dsaEncryption
pub:
63:47:4f:f6:29:e5:98:a2:21:fd:da:97:9e:3f:ca:
b0:17:49:8d:8a:a7:06:0d:a6:78:97:39:59:33:72:
a2:a5:74:d5:3a:ef:e6:7c:07:d7:8e:8e:d1:66:73:
99:14:04:96:f5:31:d6:72:ee:d2:53:f8:90:b5:f3:
c3:f1:64:ba:1a:9e:c0:0a:da:92:48:c5:d3:84:7e:
48:09:66:d9:51:ba:74:56:5a:77:8a:8c:9a:9c:f6:
84:12:61:12:51:dc:c6:4f:84:94:ec:cb:78:51:83:
8c:20:8a:53:7b:d2:b6:36:df:50:35:95:1f:cb:50:
55:8b:3f:fb:e2:77:cb
P:
00:fd:7f:53:81:1d:75:12:29:52:df:4a:9c:2e:ec:
e4:e7:f6:11:b7:52:3c:ef:44:00:c3:1e:3f:80:b6:
51:26:69:45:5d:40:22:51:fb:59:3d:8d:58:fa:bf:
c5:f5:ba:30:f6:cb:9b:55:6c:d7:81:3b:80:1d:34:
6f:f2:66:60:b7:6b:99:50:a5:a4:9f:9f:e8:04:7b:
10:22:c2:4f:bb:a9:d7:fe:b7:c6:1b:f8:3b:57:e7:
c6:a8:a6:15:0f:04:fb:83:f6:d3:c5:1e:c3:02:35:
54:13:5a:16:91:32:f6:75:f3:ae:2b:61:d7:2a:ef:
f2:22:03:19:9d:d1:48:01:c7
Q:
00:97:60:50:8f:15:23:0b:cc:b2:92:b9:82:a2:eb:
84:0b:f0:58:1c:f5
G:
00:f7:e1:a0:85:d6:9b:3d:de:cb:bc:ab:5c:36:b8:
57:b9:79:94:af:bb:fa:3a:ea:82:f9:57:4c:0b:3d:
07:82:67:51:59:57:8e:ba:d4:59:4f:e6:71:07:10:
81:80:b4:49:16:71:23:e8:4c:28:16:13:b7:cf:09:
32:8c:c8:a6:e1:3c:16:7a:8b:54:7c:8d:28:e0:a3:
ae:1e:2b:b3:a6:75:91:6e:a3:7f:0b:fa:21:35:62:
f1:fb:62:7a:01:24:3b:cc:a4:f1:be:a8:51:90:89:
a8:83:df:e1:5a:e5:9f:06:92:8b:66:5e:80:7b:55:
25:64:01:4c:3b:fe:cf:49:2a
X509v3 extensions:
X509v3 Key Usage: critical
Digital Signature, Key Encipherment, Certificate Sign
Signature Algorithm: dsaWithSHA1
r:
52:80:52:2b:2c:3d:02:66:58:b4:dc:ef:52:26:70:
1b:53:ca:b3:7d
s:
62:03:b2:ab:3e:18:2a:66:09:b6:ce:d4:05:a5:8e:
a5:7a:0d:55:67
*/
private static final String cert1 =
"-----BEGIN CERTIFICATE-----\n" +
"MIICzTCCAougAwIBAgIEN8GnNDALBgcqhkjOOAQDBQAwSTELMAkGA1UEBhMCdXMx\n" +
"DDAKBgNVBAoTA3N1bjENMAsGA1UECxMEZWFzdDEMMAoGA1UECxMDYmNuMQ8wDQYD\n" +
"VQQDEwZ5YXNzaXIwHhcNOTkwODIzMTk1NTMyWhcNMDAwODIyMTk1NTMyWjA4MQsw\n" +
"CQYDVQQGEwJ1czEMMAoGA1UEChMDc3VuMQ0wCwYDVQQLEwRlYXN0MQwwCgYDVQQL\n" +
"EwNiY24wggG1MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YR\n" +
"t1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZ\n" +
"UKWkn5/oBHsQIsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOu\n" +
"K2HXKu/yIgMZndFIAccCFQCXYFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps9\n" +
"3su8q1w2uFe5eZSvu/o66oL5V0wLPQeCZ1FZV4661FlP5nEHEIGAtEkWcSPoTCgW\n" +
"E7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoBJDvMpPG+qFGQ\n" +
"iaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBggACf2NHT/Yp5ZiiIf3al54/yrAX\n" +
"SY2KpwYNpniXOVkzcqKldNU67+Z8B9eOjtFmc5kUBJb1MdZy7tJT+JC188PxZLoa\n" +
"nsAK2pJIxdOEfkgJZtlRunRWWneKjJqc9oQSYRJR3MZPhJTsy3hRg4wgilN70rY2\n" +
"31A1lR/LUFWLP/vid8ujEzARMA8GA1UdDwEB/wQFAwMHpAAwCwYHKoZIzjgEAwUA\n" +
"Ay8AMCwCFFKAUissPQJmWLTc71ImcBtTyrN9AhRiA7KrPhgqZgm2ztQFpY6leg1V\n" +
"Zw==\n" +
"-----END CERTIFICATE-----\n" +
"";
/*
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 935095671 (0x37bc6d77)
Signature Algorithm: dsaWithSHA1
Issuer: C=us, O=sun, OU=east, OU=bcn, CN=yassir
Validity
Not Before: Aug 19 20:47:51 1999 GMT
Not After : Aug 18 20:47:51 2000 GMT
Subject: C=us, O=sun, OU=east, OU=bcn, CN=yassir
Subject Public Key Info:
Public Key Algorithm: dsaEncryption
pub:
0a:cc:a4:ec:d6:88:45:c2:24:6b:0d:78:f1:82:f3:
5e:3e:31:5d:fb:64:d5:06:5e:39:16:f1:0a:85:d1:
ff:d1:a4:74:c5:e6:b0:ba:93:1c:ee:69:51:be:3b:
a6:66:44:50:b4:f0:5e:0e:dd:9f:08:71:fe:a1:91:
2e:d4:9e:6b:b2:c0:82:3c:91:6c:18:b0:d9:bc:a3:
48:91:3f:8b:59:01:61:00:02:ab:22:31:bc:7c:6c:
0d:9f:ed:be:33:e6:5c:44:9e:62:30:95:f8:6d:22:
d7:e5:85:4c:b0:98:6e:ad:cc:ca:3b:ad:cb:fa:f7:
9f:37:13:f7:ca:e2:22:ba
P:
00:fd:7f:53:81:1d:75:12:29:52:df:4a:9c:2e:ec:
e4:e7:f6:11:b7:52:3c:ef:44:00:c3:1e:3f:80:b6:
51:26:69:45:5d:40:22:51:fb:59:3d:8d:58:fa:bf:
c5:f5:ba:30:f6:cb:9b:55:6c:d7:81:3b:80:1d:34:
6f:f2:66:60:b7:6b:99:50:a5:a4:9f:9f:e8:04:7b:
10:22:c2:4f:bb:a9:d7:fe:b7:c6:1b:f8:3b:57:e7:
c6:a8:a6:15:0f:04:fb:83:f6:d3:c5:1e:c3:02:35:
54:13:5a:16:91:32:f6:75:f3:ae:2b:61:d7:2a:ef:
f2:22:03:19:9d:d1:48:01:c7
Q:
00:97:60:50:8f:15:23:0b:cc:b2:92:b9:82:a2:eb:
84:0b:f0:58:1c:f5
G:
00:f7:e1:a0:85:d6:9b:3d:de:cb:bc:ab:5c:36:b8:
57:b9:79:94:af:bb:fa:3a:ea:82:f9:57:4c:0b:3d:
07:82:67:51:59:57:8e:ba:d4:59:4f:e6:71:07:10:
81:80:b4:49:16:71:23:e8:4c:28:16:13:b7:cf:09:
32:8c:c8:a6:e1:3c:16:7a:8b:54:7c:8d:28:e0:a3:
ae:1e:2b:b3:a6:75:91:6e:a3:7f:0b:fa:21:35:62:
f1:fb:62:7a:01:24:3b:cc:a4:f1:be:a8:51:90:89:
a8:83:df:e1:5a:e5:9f:06:92:8b:66:5e:80:7b:55:
25:64:01:4c:3b:fe:cf:49:2a
X509v3 extensions:
X509v3 Key Usage: critical
Digital Signature, Key Encipherment, Certificate Sign
X509v3 Basic Constraints: critical
CA:TRUE, pathlen:5
Signature Algorithm: dsaWithSHA1
r:
2f:88:46:37:94:92:b2:02:07:5b:8d:76:e5:81:23:
85:7f:bc:8d:b9
s:
00:8b:d7:41:fa:11:c7:ab:27:92:5d:0a:03:98:56:
36:42:5f:f5:1f:9d
*/
private static final String cert2 =
"-----BEGIN CERTIFICATE-----\n" +
"MIIC9TCCArKgAwIBAgIEN7xtdzALBgcqhkjOOAQDBQAwSTELMAkGA1UEBhMCdXMx\n" +
"DDAKBgNVBAoTA3N1bjENMAsGA1UECxMEZWFzdDEMMAoGA1UECxMDYmNuMQ8wDQYD\n" +
"VQQDEwZ5YXNzaXIwHhcNOTkwODE5MjA0NzUxWhcNMDAwODE4MjA0NzUxWjBJMQsw\n" +
"CQYDVQQGEwJ1czEMMAoGA1UEChMDc3VuMQ0wCwYDVQQLEwRlYXN0MQwwCgYDVQQL\n" +
"EwNiY24xDzANBgNVBAMTBnlhc3NpcjCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQD9\n" +
"f1OBHXUSKVLfSpwu7OTn9hG3UjzvRADDHj+AtlEmaUVdQCJR+1k9jVj6v8X1ujD2\n" +
"y5tVbNeBO4AdNG/yZmC3a5lQpaSfn+gEexAiwk+7qdf+t8Yb+DtX58aophUPBPuD\n" +
"9tPFHsMCNVQTWhaRMvZ1864rYdcq7/IiAxmd0UgBxwIVAJdgUI8VIwvMspK5gqLr\n" +
"hAvwWBz1AoGBAPfhoIXWmz3ey7yrXDa4V7l5lK+7+jrqgvlXTAs9B4JnUVlXjrrU\n" +
"WU/mcQcQgYC0SRZxI+hMKBYTt88JMozIpuE8FnqLVHyNKOCjrh4rs6Z1kW6jfwv6\n" +
"ITVi8ftiegEkO8yk8b6oUZCJqIPf4VrlnwaSi2ZegHtVJWQBTDv+z0kqA4GEAAKB\n" +
"gArMpOzWiEXCJGsNePGC814+MV37ZNUGXjkW8QqF0f/RpHTF5rC6kxzuaVG+O6Zm\n" +
"RFC08F4O3Z8Icf6hkS7UnmuywII8kWwYsNm8o0iRP4tZAWEAAqsiMbx8bA2f7b4z\n" +
"5lxEnmIwlfhtItflhUywmG6tzMo7rcv69583E/fK4iK6oycwJTAPBgNVHQ8BAf8E\n" +
"BQMDB6QAMBIGA1UdEwEB/wQIMAYBAf8CAQUwCwYHKoZIzjgEAwUAAzAAMC0CFC+I\n" +
"RjeUkrICB1uNduWBI4V/vI25AhUAi9dB+hHHqyeSXQoDmFY2Ql/1H50=\n" +
"-----END CERTIFICATE-----\n" +
"";
private static final String pkcs7path =
"MIIF9QYJKoZIhvcNAQcCoIIF5jCCBeICAQExADALBgkqhkiG9w0BBwGgggXKMIICzTCCAougAwIB\n" +
"AgIEN8GnNDALBgcqhkjOOAQDBQAwSTELMAkGA1UEBhMCdXMxDDAKBgNVBAoTA3N1bjENMAsGA1UE\n" +
"CxMEZWFzdDEMMAoGA1UECxMDYmNuMQ8wDQYDVQQDEwZ5YXNzaXIwHhcNOTkwODIzMTk1NTMyWhcN\n" +
"MDAwODIyMTk1NTMyWjA4MQswCQYDVQQGEwJ1czEMMAoGA1UEChMDc3VuMQ0wCwYDVQQLEwRlYXN0\n" +
"MQwwCgYDVQQLEwNiY24wggG1MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YR\n" +
"t1I870QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQ\n" +
"IsJPu6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCFQCX\n" +
"YFCPFSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5eZSvu/o66oL5V0wLPQeCZ1FZ\n" +
"V4661FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7\n" +
"YnoBJDvMpPG+qFGQiaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBggACf2NHT/Yp5ZiiIf3al54/\n" +
"yrAXSY2KpwYNpniXOVkzcqKldNU67+Z8B9eOjtFmc5kUBJb1MdZy7tJT+JC188PxZLoansAK2pJI\n" +
"xdOEfkgJZtlRunRWWneKjJqc9oQSYRJR3MZPhJTsy3hRg4wgilN70rY231A1lR/LUFWLP/vid8uj\n" +
"EzARMA8GA1UdDwEB/wQFAwMHpAAwCwYHKoZIzjgEAwUAAy8AMCwCFFKAUissPQJmWLTc71ImcBtT\n" +
"yrN9AhRiA7KrPhgqZgm2ztQFpY6leg1VZzCCAvUwggKyoAMCAQICBDe8bXcwCwYHKoZIzjgEAwUA\n" +
"MEkxCzAJBgNVBAYTAnVzMQwwCgYDVQQKEwNzdW4xDTALBgNVBAsTBGVhc3QxDDAKBgNVBAsTA2Jj\n" +
"bjEPMA0GA1UEAxMGeWFzc2lyMB4XDTk5MDgxOTIwNDc1MVoXDTAwMDgxODIwNDc1MVowSTELMAkG\n" +
"A1UEBhMCdXMxDDAKBgNVBAoTA3N1bjENMAsGA1UECxMEZWFzdDEMMAoGA1UECxMDYmNuMQ8wDQYD\n" +
"VQQDEwZ5YXNzaXIwggG3MIIBLAYHKoZIzjgEATCCAR8CgYEA/X9TgR11EilS30qcLuzk5/YRt1I8\n" +
"70QAwx4/gLZRJmlFXUAiUftZPY1Y+r/F9bow9subVWzXgTuAHTRv8mZgt2uZUKWkn5/oBHsQIsJP\n" +
"u6nX/rfGG/g7V+fGqKYVDwT7g/bTxR7DAjVUE1oWkTL2dfOuK2HXKu/yIgMZndFIAccCFQCXYFCP\n" +
"FSMLzLKSuYKi64QL8Fgc9QKBgQD34aCF1ps93su8q1w2uFe5eZSvu/o66oL5V0wLPQeCZ1FZV466\n" +
"1FlP5nEHEIGAtEkWcSPoTCgWE7fPCTKMyKbhPBZ6i1R8jSjgo64eK7OmdZFuo38L+iE1YvH7YnoB\n" +
"JDvMpPG+qFGQiaiD3+Fa5Z8GkotmXoB7VSVkAUw7/s9JKgOBhAACgYAKzKTs1ohFwiRrDXjxgvNe\n" +
"PjFd+2TVBl45FvEKhdH/0aR0xeawupMc7mlRvjumZkRQtPBeDt2fCHH+oZEu1J5rssCCPJFsGLDZ\n" +
"vKNIkT+LWQFhAAKrIjG8fGwNn+2+M+ZcRJ5iMJX4bSLX5YVMsJhurczKO63L+vefNxP3yuIiuqMn\n" +
"MCUwDwYDVR0PAQH/BAUDAwekADASBgNVHRMBAf8ECDAGAQH/AgEFMAsGByqGSM44BAMFAAMwADAt\n" +
"AhQviEY3lJKyAgdbjXblgSOFf7yNuQIVAIvXQfoRx6snkl0KA5hWNkJf9R+dMQA=\n" +
"";
// Runs test of CertPath encoding and decoding.
public static void main(String[] args) throws Exception {
// Make the CertPath whose encoded form has already been stored
CertificateFactory certFac = CertificateFactory.getInstance("X509");
final List<Certificate> certs = new ArrayList<>();
certs.add(certFac.generateCertificate(new ByteArrayInputStream(cert1.getBytes())));
certs.add(certFac.generateCertificate(new ByteArrayInputStream(cert2.getBytes())));
CertPath cp = certFac.generateCertPath(certs);
// Get the encoded form of the CertPath we made
byte[] encoded = cp.getEncoded("PKCS7");
// check if it matches the encoded value
if (!Arrays.equals(encoded, Base64.getMimeDecoder().decode(pkcs7path.getBytes()))) {
throw new RuntimeException("PKCS#7 encoding doesn't match stored value");
}
// Generate a CertPath from the encoded value and check if it equals
// the CertPath generated from the certificates
CertPath decodedCP = certFac.generateCertPath(new ByteArrayInputStream(encoded), "PKCS7");
if (!decodedCP.equals(cp)) {
throw new RuntimeException("CertPath decoded from PKCS#7 isn't equal to original");
}
}
}
此差异已折叠。
/*
* Copyright (c) 2016, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8149417
* @summary Use final restricted flag
*/
import java.security.*;
import java.lang.reflect.*;
public class FinalRestricted {
public static void main(String[] args) throws Exception {
int modifiers = Class.forName("javax.crypto.JceSecurity")
.getDeclaredField("isRestricted").getModifiers();
if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers) &&
Modifier.isPrivate(modifiers))) {
throw new Exception("JceSecurity.isRestricted is not " +
"a private static final field!");
}
}
}
/*
* Copyright (c) 2001, 2016, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import jdk.testlibrary.ProcessTools;
import javax.security.auth.Subject;
import javax.security.auth.x500.X500Principal;
import java.io.*;
import java.security.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
/**
* @test
* @bug 8048147
* @summary Check if proper AccessControlException is thrown
* in case of nested Subject.doAs() invocations
* when one of protection domains doesn't have permissions
*
* @library /lib/testlibrary
*
* @run main NestedActions jar NestedActionsACE.jar
* NestedActionsACE.class Utils.class
* @run main NestedActions jar NestedActionsPAE.jar
* NestedActionsPAE.class Utils.class
* @run main NestedActions jar NestedActionsOnePrincipal.jar
* NestedActionsOnePrincipal.class Utils.class
* @run main NestedActions jar NestedActionsTwoPrincipals.jar
* NestedActionsTwoPrincipals.class Utils.class
* @run main NestedActions jar WriteToFileAction.jar
* WriteToFileAction.class
* @run main NestedActions jar WriteToFileNegativeAction.jar
* WriteToFileNegativeAction.class
* @run main NestedActions jar WriteToFileExceptionAction.jar
* WriteToFileExceptionAction.class
* @run main NestedActions jar ReadFromFileAction.jar
* ReadFromFileAction.class
* @run main NestedActions jar ReadFromFileNegativeAction.jar
* ReadFromFileNegativeAction.class
* @run main NestedActions jar ReadFromFileExceptionAction.jar
* ReadFromFileExceptionAction.class
* @run main NestedActions jar ReadPropertyAction.jar
* ReadPropertyAction.class
* @run main NestedActions jar ReadPropertyNegativeAction.jar
* ReadPropertyNegativeAction.class
* @run main NestedActions jar ReadPropertyExceptionAction.jar
* ReadPropertyExceptionAction.class ReadPropertyException.class
*
* @run main NestedActions NestedActionsACE policy.expect.ace
* NestedActionsACE.jar WriteToFileNegativeAction.jar
* ReadFromFileNegativeAction.jar ReadPropertyNegativeAction.jar
* @run main NestedActions NestedActionsPAE policy.expect.pae
* NestedActionsPAE.jar WriteToFileExceptionAction.jar
* ReadFromFileExceptionAction.jar ReadPropertyExceptionAction.jar
* @run main NestedActions NestedActionsOnePrincipal policy.one.principal
* NestedActionsOnePrincipal.jar WriteToFileAction.jar
* ReadFromFileAction.jar ReadPropertyAction.jar
* @run main NestedActions NestedActionsTwoPrincipals policy.two.principals
* NestedActionsTwoPrincipals.jar WriteToFileAction.jar
* ReadFromFileAction.jar ReadPropertyAction.jar
*/
public class NestedActions {
static final String file = "NestedActions.tmp";
static final String PS = System.getProperty("path.separator");
static final String FS = System.getProperty("file.separator");
static final String TEST_CLASSES = System.getProperty("test.classes");
static final String TEST_SOURCES = System.getProperty("test.src");
static final String JAVA_OPTS = System.getProperty("test.java.opts");
static final String JAVA = System.getProperty("java.home")
+ FS + "bin" + FS + "java";
public static void main(String[] args) throws IOException {
if (args.length > 0) {
if ("jar".equals(args[0]) && args.length > 2) {
createJar(args[1],
Arrays.copyOfRange(args, 2, args.length));
} else {
runJava(args);
}
} else {
throw new RuntimeException("Wrong parameters");
}
}
static void createJar(String dest, String... files) throws IOException {
System.out.println("Create " + dest + " with the following content:");
try (JarOutputStream jos = new JarOutputStream(
new FileOutputStream(dest), new Manifest())) {
for (String file : files) {
System.out.println(" " + file);
jos.putNextEntry(new JarEntry(file));
try (FileInputStream fis = new FileInputStream(
TEST_CLASSES + FS + file)) {
byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer, 0, buffer.length)) > 0) {
jos.write(buffer, 0, read);
}
}
}
}
}
static void runJava(String[] args) {
if (args == null || args.length < 3) {
throw new IllegalArgumentException("wrong parameters");
}
List<String> cmds = new ArrayList<>();
cmds.add(JAVA);
StringBuilder sb = new StringBuilder();
cmds.add("-classpath");
for (int i=2; i<args.length; i++) {
sb.append(args[i]).append(PS);
}
cmds.add(sb.toString());
if (JAVA_OPTS != null && !JAVA_OPTS.isEmpty()) {
Collections.addAll(cmds, JAVA_OPTS.trim().split("\\s+"));
}
cmds.add("-Djava.security.manager");
cmds.add("-Djava.security.policy=" + TEST_SOURCES + FS + args[1]);
cmds.add(args[0]);
try {
ProcessTools.executeCommand(cmds.toArray(new String[cmds.size()]))
.shouldHaveExitValue(0);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
/**
* Test for nested Subject.doAs() invocation:
*
* WriteToFileAction (CN=Duke principal) ->
* ReadFromFileAction (CN=Duke principal) ->
* ReadPropertyAction (CN=Duke principal)
*
* The test expects AccessControllException.
*/
class NestedActionsACE {
public static void main(String args[]) {
Subject subject = new Subject();
subject.getPrincipals().add(new X500Principal("CN=Duke"));
WriteToFileNegativeAction writeToFile
= new WriteToFileNegativeAction(NestedActions.file);
Subject.doAs(subject, writeToFile);
}
}
/**
* Test for nested Subject.doAs() invocation:
*
* WriteToFileAction (CN=Duke principal) ->
* ReadFromFileAction (CN=Duke principal) ->
* ReadPropertyAction (CN=Duke principal)
*
* The test expects PrivilegedActionException
* that caused by AccessControlEception.
*/
class NestedActionsPAE {
public static void main(String args[]) {
Subject subject = new Subject();
subject.getPrincipals().add(new X500Principal("CN=Duke"));
try {
WriteToFileExceptionAction writeToFile =
new WriteToFileExceptionAction(NestedActions.file);
Subject.doAs(subject, writeToFile);
throw new RuntimeException(
"Test failed: no PrivilegedActionException thrown");
} catch (PrivilegedActionException pae) {
System.out.println(
"PrivilegedActionException thrown as expected: "
+ pae);
// check if AccessControlException caused PrivilegedActionException
Throwable exception = pae.getException();
do {
if (!(exception instanceof PrivilegedActionException)) {
break;
}
exception = ((PrivilegedActionException) exception).
getException();
} while (true);
if (!(exception instanceof ReadPropertyException)) {
throw new RuntimeException(
"Test failed: PrivilegedActionException "
+ "was not caused by ReadPropertyException");
}
exception = exception.getCause();
if (!(exception instanceof AccessControlException)) {
throw new RuntimeException(
"Test failed: PrivilegedActionException "
+ "was not caused by ReadPropertyException");
}
System.out.println(
"Test passed: PrivilegedActionException "
+ "was caused by AccessControlException");
}
}
}
/**
* Test for nested Subject.doAs() invocation:
*
* WriteToFileAction (CN=Duke principal) ->
* ReadFromFileAction (CN=Duke principal) ->
* ReadPropertyAction (CN=Duke principal)
*/
class NestedActionsOnePrincipal {
public static void main(String args[]) {
Subject subject = new Subject();
subject.getPrincipals().add(new X500Principal("CN=Duke"));
WriteToFileAction writeToFile =
new WriteToFileAction(NestedActions.file);
Subject.doAs(subject, writeToFile);
}
}
/**
* Test for nested Subject.doAs() invocation:
*
* WriteToFileAction (CN=Duke principal) ->
* ReadFromFileAction (CN=Duke principal) ->
* ReadPropertyAction (CN=Java principal)
*/
class NestedActionsTwoPrincipals {
public static void main(String args[]) {
Subject subject = new Subject();
subject.getPrincipals().add(new X500Principal("CN=Duke"));
Subject anotherSubject = new Subject();
anotherSubject.getPrincipals().add(new X500Principal("CN=Java"));
ReadFromFileAction readFromFile
= new ReadFromFileAction(NestedActions.file, anotherSubject);
WriteToFileAction writeToFile
= new WriteToFileAction(NestedActions.file, readFromFile);
Subject.doAs(subject, writeToFile);
}
}
/**
* Helper class.
*/
class Utils {
static void readFile(String filename) {
System.out.println("ReadFromFileAction: try to read " + filename);
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
System.out.println("principals = " + subject.getPrincipals());
try (FileInputStream fis = new FileInputStream(filename)) {
// do nothing
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException", e);
}
}
static void writeFile(String filename) {
System.out.println("WriteToFileAction: try to write to " + filename);
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
System.out.println("principals = " + subject.getPrincipals());
try (BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(filename))) {
bos.write(0);
bos.flush();
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException", e);
}
}
}
class WriteToFileAction implements PrivilegedAction {
private final String filename;
private final PrivilegedAction nextAction;
WriteToFileAction(String filename, PrivilegedAction nextAction) {
this.filename = filename;
this.nextAction = nextAction;
}
WriteToFileAction(String filename) {
this(filename, new ReadFromFileAction(filename));
}
@Override
public Object run() {
Utils.writeFile(filename);
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
return Subject.doAs(subject, nextAction);
}
}
class ReadFromFileAction implements PrivilegedAction {
private final String filename;
private final Subject anotherSubject;
ReadFromFileAction(String filename) {
this(filename, null);
}
ReadFromFileAction(String filename, Subject anotherSubject) {
this.filename = filename;
this.anotherSubject = anotherSubject;
}
@Override
public Object run() {
Utils.readFile(filename);
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
ReadPropertyAction readProperty = new ReadPropertyAction();
if (anotherSubject != null) {
return Subject.doAs(anotherSubject, readProperty);
} else {
return Subject.doAs(subject, readProperty);
}
}
}
class ReadPropertyAction implements PrivilegedAction {
@Override
public java.lang.Object run() {
System.out.println("ReadPropertyAction: "
+ "try to read 'java.class.path' property");
AccessControlContext acc = AccessController.getContext();
Subject s = Subject.getSubject(acc);
System.out.println("principals = " + s.getPrincipals());
System.out.println("java.class.path = "
+ System.getProperty("java.class.path"));
return null;
}
}
class WriteToFileNegativeAction implements PrivilegedAction {
private final String filename;
public WriteToFileNegativeAction(String filename) {
this.filename = filename;
}
@Override
public Object run() {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
System.out.println("principals = " + subject.getPrincipals());
try {
Utils.writeFile(filename);
new File(filename).delete();
throw new RuntimeException(
"Test failed: no AccessControlException thrown");
} catch (AccessControlException ace) {
System.out.println(
"AccessControlException thrown as expected: "
+ ace.getMessage());
}
ReadFromFileNegativeAction readFromFile
= new ReadFromFileNegativeAction(filename);
return Subject.doAs(subject, readFromFile);
}
}
class ReadFromFileNegativeAction implements PrivilegedAction {
private final String filename;
public ReadFromFileNegativeAction(String filename) {
this.filename = filename;
}
@Override
public Object run() {
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
System.out.println("principals = " + subject.getPrincipals());
try {
Utils.readFile(filename);
throw new RuntimeException(
"Test failed: no AccessControlException thrown");
} catch (AccessControlException ace) {
System.out.println(
"AccessControlException thrown as expected: "
+ ace.getMessage());
}
ReadPropertyNegativeAction readProperty =
new ReadPropertyNegativeAction();
return Subject.doAs(subject, readProperty);
}
}
class ReadPropertyNegativeAction implements PrivilegedAction {
@Override
public java.lang.Object run() {
System.out.println("Try to read 'java.class.path' property");
AccessControlContext acc = AccessController.getContext();
Subject s = Subject.getSubject(acc);
System.out.println("principals = " + s.getPrincipals());
try {
System.out.println("java.class.path = "
+ System.getProperty("java.class.path"));
throw new RuntimeException(
"Test failed: no AccessControlException thrown");
} catch (AccessControlException ace) {
System.out.println(
"AccessControlException thrown as expected: "
+ ace.getMessage());
}
return null;
}
}
class WriteToFileExceptionAction implements PrivilegedExceptionAction {
private final String filename;
WriteToFileExceptionAction(String filename) {
this.filename = filename;
}
@Override
public Object run() throws Exception {
Utils.writeFile(filename);
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
ReadFromFileExceptionAction readFromFile =
new ReadFromFileExceptionAction(filename);
return Subject.doAs(subject, readFromFile);
}
}
class ReadFromFileExceptionAction implements PrivilegedExceptionAction {
private final String filename;
ReadFromFileExceptionAction(String filename) {
this.filename = filename;
}
@Override
public Object run() throws Exception {
Utils.readFile(filename);
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
ReadPropertyExceptionAction readProperty =
new ReadPropertyExceptionAction();
return Subject.doAs(subject, readProperty);
}
}
class ReadPropertyExceptionAction implements PrivilegedExceptionAction {
@Override
public java.lang.Object run() throws Exception {
System.out.println("Try to read 'java.class.path' property");
AccessControlContext acc = AccessController.getContext();
Subject s = Subject.getSubject(acc);
System.out.println("principals = " + s.getPrincipals());
try {
System.out.println("java.class.path = "
+ System.getProperty("java.class.path"));
throw new RuntimeException(
"Test failed: no AccessControlException thrown");
} catch (AccessControlException ace) {
System.out.println(
"AccessControlException thrown as expected: "
+ ace.getMessage());
throw new ReadPropertyException(ace);
}
}
}
class ReadPropertyException extends Exception {
ReadPropertyException(Throwable cause) {
super(cause);
}
}
// this code has limited permissions that should cause ACE
grant codeBase "file:NestedActionsACE.jar" {
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "modifyPrincipals";
permission javax.security.auth.AuthPermission "doAs";
permission java.util.PropertyPermission "path.separator", "read";
permission java.util.PropertyPermission "file.separator", "read";
permission java.util.PropertyPermission "test.classes", "read";
permission java.util.PropertyPermission "test.src", "read";
permission java.util.PropertyPermission "test.java.opts", "read";
permission java.util.PropertyPermission "java.home", "read";
};
grant codeBase "file:WriteToFileNegativeAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission java.security.AllPermission;
};
grant codeBase "file:ReadFromFileNegativeAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission java.security.AllPermission;
};
grant codeBase "file:ReadPropertyNegativeAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission java.security.AllPermission;
};
\ No newline at end of file
grant codeBase "file:NestedActionsPAE.jar" {
permission java.security.AllPermission;
};
grant codeBase "file:WriteToFileExceptionAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission java.security.AllPermission;
};
grant codeBase "file:ReadFromFileExceptionAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission java.security.AllPermission;
};
// this code has limited permissions that should cause ACE
grant codeBase "file:ReadPropertyExceptionAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission javax.security.auth.AuthPermission "getSubject";
};
grant codeBase "file:NestedActionsOnePrincipal.jar" {
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "modifyPrincipals";
permission javax.security.auth.AuthPermission "doAs";
permission java.util.PropertyPermission "path.separator", "read";
permission java.util.PropertyPermission "file.separator", "read";
permission java.util.PropertyPermission "test.classes", "read";
permission java.util.PropertyPermission "test.src", "read";
permission java.util.PropertyPermission "test.java.opts", "read";
permission java.util.PropertyPermission "java.home", "read";
permission java.util.PropertyPermission "java.class.path", "read";
permission java.io.FilePermission "NestedActions.tmp", "read,write";
};
grant codeBase "file:WriteToFileAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "doAs";
permission java.util.PropertyPermission "java.class.path", "read";
permission java.io.FilePermission "NestedActions.tmp", "read,write";
};
grant codeBase "file:ReadFromFileAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "doAs";
permission java.util.PropertyPermission "java.class.path", "read";
permission java.io.FilePermission "NestedActions.tmp", "read";
};
grant codeBase "file:ReadPropertyAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "doAs";
permission java.util.PropertyPermission "java.class.path", "read";
};
\ No newline at end of file
grant codeBase "file:NestedActionsTwoPrincipals.jar" {
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "modifyPrincipals";
permission javax.security.auth.AuthPermission "doAs";
permission java.util.PropertyPermission "path.separator", "read";
permission java.util.PropertyPermission "file.separator", "read";
permission java.util.PropertyPermission "test.classes", "read";
permission java.util.PropertyPermission "test.src", "read";
permission java.util.PropertyPermission "test.java.opts", "read";
permission java.util.PropertyPermission "java.home", "read";
permission java.util.PropertyPermission "java.class.path", "read";
permission java.io.FilePermission "NestedActions.tmp", "read,write,delete";
};
grant codeBase "file:WriteToFileAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke" {
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "doAs";
permission javax.security.auth.AuthPermission "modifyPrincipals";
permission java.util.PropertyPermission "java.class.path", "read";
permission java.io.FilePermission "NestedActions.tmp", "read,write";
};
grant codeBase "file:ReadFromFileAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Duke"{
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "doAs";
permission java.util.PropertyPermission "java.class.path", "read";
permission java.io.FilePermission "NestedActions.tmp", "read";
};
grant codeBase "file:ReadPropertyAction.jar"
Principal javax.security.auth.x500.X500Principal "cn=Java" {
permission javax.security.auth.AuthPermission "getSubject";
permission javax.security.auth.AuthPermission "doAs";
permission java.util.PropertyPermission "java.class.path", "read";
};
\ No newline at end of file
......@@ -35,6 +35,7 @@ import java.io.FileInputStream;
import java.security.*;
import javax.xml.crypto.Data;
import javax.xml.crypto.KeySelector;
import javax.xml.crypto.MarshalException;
import javax.xml.crypto.OctetStreamData;
import javax.xml.crypto.URIDereferencer;
import javax.xml.crypto.URIReference;
......@@ -60,9 +61,17 @@ public class ValidationTests {
static class Test {
String file;
KeySelector ks;
Test(String file, KeySelector ks) {
Class exception;
Test(String file, KeySelector ks, Class exception) {
this.file = file;
this.ks = ks;
this.exception = exception;
}
// XMLSignatureException is expected by default
Test(String file, KeySelector ks) {
this(file, ks, XMLSignatureException.class);
}
}
......@@ -109,7 +118,17 @@ public class ValidationTests {
private final static Test[] INVALID_TESTS = {
new Test("signature-enveloping-hmac-sha1-40.xml", SKKS),
new Test("signature-enveloping-hmac-sha1-trunclen-0-attack.xml", SKKS),
new Test("signature-enveloping-hmac-sha1-trunclen-8-attack.xml", SKKS)
new Test("signature-enveloping-hmac-sha1-trunclen-8-attack.xml", SKKS),
new Test("signature-extra-text-in-signed-info.xml", SKKS,
MarshalException.class),
new Test("signature-wrong-canonicalization-method-algorithm.xml", SKKS,
MarshalException.class),
new Test("signature-wrong-transform-algorithm.xml", SKKS,
MarshalException.class),
new Test("signature-no-reference-uri.xml", SKKS),
new Test("signature-wrong-signature-method-algorithm.xml", SKKS,
MarshalException.class),
new Test("signature-wrong-tag-names.xml", SKKS, MarshalException.class)
};
public static void main(String args[]) throws Exception {
......@@ -142,11 +161,16 @@ public class ValidationTests {
test_signature(test);
System.out.println("FAILED");
atLeastOneFailed = true;
} catch (XMLSignatureException xse) {
System.out.println(xse.getMessage());
} catch (Exception e) {
System.out.println("Exception: " + e);
if (e.getClass() != test.exception) {
System.out.println("FAILED: unexpected exception");
atLeastOneFailed = true;
} else {
System.out.println("PASSED");
}
}
}
if (atLeastOneFailed) {
throw new Exception
......
<test xmlns="http://example.org/envelope">test<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod><DigestValue>1Bq8FsjajUBYPD7stQeJSc66GlM=</DigestValue><test>extra text</test></Reference></SignedInfo><SignatureValue>iTrgJERmYeD5hFwY8/MwJpkF+nd++AAOgf/Kxt9SwdE6BIYq2Vyxq4CQPhD+t2971BGTgvF6ejZd
+/Ko4Zs5Dqf4Lt65Vck0q43rM0PdP1e8gJov0IPYnZ1zeqFpah+N/OjmqTbshaZWRIjf3eqS6en5
ZKjn+TkCQ1kOX/YUNDc=</SignatureValue></Signature></test>
\ No newline at end of file
<test xmlns="http://example.org/envelope">test<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod><Reference><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod><DigestValue>1Bq8FsjajUBYPD7stQeJSc66GlM=</DigestValue></Reference></SignedInfo><SignatureValue>BNPSYlNcyXcO/Tc1tr9mQ/KAZ40eFybLTDyB/HH1EHHMpc972A+nOX2EWBaLsVgG8apl0Isp1ZqV
gmoDHNF6xrcJJQVydVJzU08GVV4GiXHMqRYQbted7STQLhlhssvNNdMEoVApsX5ByL66wxKZQXrT
z1kZtOHAi88DOrmIJu0=</SignatureValue></Signature></test>
\ No newline at end of file
<test xmlns="http://example.org/envelope">test<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><CanonicalizationMethod Algorithm="http://oracle.com"></CanonicalizationMethod><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod><DigestValue>1Bq8FsjajUBYPD7stQeJSc66GlM=</DigestValue></Reference></SignedInfo><SignatureValue>EBbyEV7e+1CTUsyCTyxiN8p+U3/za1oTjK7q+kF8Q87r8e/7C1z4ndGWbk6zyI3w6leT+I2suW9U
KkdvkrDXX2OyLw0GfgJfLkNn+1pGK6kyWpL95NoWJZhHkUAKKBZ0ikfZ4j33gYxrYK+IYCLeZYzr
hlZjdXXXCiSH0Sq+weQ=</SignatureValue></Signature></test>
\ No newline at end of file
<test xmlns="http://example.org/envelope">test<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod><SignatureMethod Algorithm="bogus://bogus"></SignatureMethod><Reference URI=""><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod><DigestValue>1Bq8FsjajUBYPD7stQeJSc66GlM=</DigestValue></Reference></SignedInfo><SignatureValue>RjL9nfQg9u6+KEFfAlBBH7E7ilFgB7YEQ5MxOIJN/fOdQmc5iDD+YuhiHzNGXGi/UOyo6t8LxTxl
X4oFE1RNlPVkSAZK4LcTWhVa757WwgW1/EZo8PQYWp5NScLq6PumYaujoovSYBKW2N6+jQpnD/L6
4cuEVNnwEFqvOLrjogY=</SignatureValue></Signature></test>
\ No newline at end of file
<test xmlns="http://example.org/envelope">test<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><aSignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><aCanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></aCanonicalizationMethod><aSignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></aSignatureMethod><aReference URI=""><Transforms><aTransform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></aTransform></Transforms><aDigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></aDigestMethod><aDigestValue>1Bq8FsjajUBYPD7stQeJSc66GlM=</aDigestValue></aReference></aSignedInfo><aSignatureValue>cbNpPGavhM0BGUtrvLxvy2SCIt+I27BPpVEt0Q9mXrdPYurMqWF/67AdY9m5RqS7+ZZlwUtem083
MczRYbKoOIq7sMbCqKKdzbSE/U6rfmky/ACQ5wgemZl8jtipwu5LhAUzjhzT8hhTjVqOYpHdkVJz
l9dnd9eWbLmEr3BI0VA=</aSignatureValue></Signature></test>
\ No newline at end of file
<!-- This XML signature contains a Transform with wrong algorithm -->
<test xmlns="http://example.org/envelope">test<Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#"><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod><Reference URI=""><Transforms><Transform Algorithm="bogus://bogus"></Transform></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod><DigestValue>1Bq8FsjajUBYPD7stQeJSc66GlM=</DigestValue></Reference></SignedInfo><SignatureValue>Wzyx3jgEKGwY+pBXBmqWLWhASHQYCCGZVii5sKKKeZUBKxNBthjiSVfzKANuLgX6zAt16XRycrSL
zFKTPuvGeWVPDvd+KTNKCJxN9ccrG7v23EM7RY2eMJGu2r5DLfKwV7H6YuJPsOuWifVkKAhvq7gd
6akJshxyAj9Ud+mjo48=</SignatureValue></Signature></test>
\ No newline at end of file
......@@ -269,16 +269,46 @@ public final class ProcessTools {
}
/**
* Create ProcessBuilder using the java launcher from the jdk to be tested
* and with any platform specific arguments prepended
* Create ProcessBuilder using the java launcher from the jdk to be tested,
* and with any platform specific arguments prepended.
*
* @param command Arguments to pass to the java command.
* @return The ProcessBuilder instance representing the java command.
*/
public static ProcessBuilder createJavaProcessBuilder(String... command)
throws Exception {
return createJavaProcessBuilder(false, command);
}
/**
* Create ProcessBuilder using the java launcher from the jdk to be tested,
* and with any platform specific arguments prepended.
*
* @param addTestVmAndJavaOptions If true, adds test.vm.opts and test.java.opts
* to the java arguments.
* @param command Arguments to pass to the java command.
* @return The ProcessBuilder instance representing the java command.
*/
public static ProcessBuilder createJavaProcessBuilder(boolean addTestVmAndJavaOptions, String... command) throws Exception {
String javapath = JDKToolFinder.getJDKTool("java");
ArrayList<String> args = new ArrayList<>();
args.add(javapath);
Collections.addAll(args, getPlatformSpecificVMArgs());
if (addTestVmAndJavaOptions) {
// -cp is needed to make sure the same classpath is used whether the test is
// run in AgentVM mode or OtherVM mode. It was added to the hotspot version
// of this API as part of 8077608. However, for the jdk version it is only
// added when addTestVmAndJavaOptions is true in order to minimize
// disruption to existing JDK tests, which have yet to be tested with -cp
// being added. At some point -cp should always be added to be consistent
// with what the hotspot version does.
args.add("-cp");
args.add(System.getProperty("java.class.path"));
Collections.addAll(args, Utils.getTestJavaOpts());
}
Collections.addAll(args, command);
// Reporting
......
/*
* Copyright (c) 2016, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.IOException;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static java.nio.file.StandardOpenOption.WRITE;
import java.util.List;
import java.util.Random;
/*
* @test
* @requires sun.arch.data.model == "64"
* @build TestMaxCachedBufferSize
* @run main/othervm TestMaxCachedBufferSize
* @run main/othervm -Djdk.nio.maxCachedBufferSize=0 TestMaxCachedBufferSize
* @run main/othervm -Djdk.nio.maxCachedBufferSize=2000 TestMaxCachedBufferSize
* @run main/othervm -Djdk.nio.maxCachedBufferSize=100000 TestMaxCachedBufferSize
* @run main/othervm -Djdk.nio.maxCachedBufferSize=10000000 TestMaxCachedBufferSize
* @summary Test the implementation of the jdk.nio.maxCachedBufferSize property.
*/
public class TestMaxCachedBufferSize {
private static final int DEFAULT_ITERS = 10 * 1000;
private static final int DEFAULT_THREAD_NUM = 4;
private static final int SMALL_BUFFER_MIN_SIZE = 4 * 1024;
private static final int SMALL_BUFFER_MAX_SIZE = 64 * 1024;
private static final int SMALL_BUFFER_DIFF_SIZE =
SMALL_BUFFER_MAX_SIZE - SMALL_BUFFER_MIN_SIZE;
private static final int LARGE_BUFFER_MIN_SIZE = 512 * 1024;
private static final int LARGE_BUFFER_MAX_SIZE = 4 * 1024 * 1024;
private static final int LARGE_BUFFER_DIFF_SIZE =
LARGE_BUFFER_MAX_SIZE - LARGE_BUFFER_MIN_SIZE;
private static final int LARGE_BUFFER_FREQUENCY = 100;
private static final String FILE_NAME_PREFIX = "nio-out-file-";
private static final int VERBOSE_PERIOD = 5 * 1000;
private static int iters = DEFAULT_ITERS;
private static int threadNum = DEFAULT_THREAD_NUM;
private static BufferPoolMXBean getDirectPool() {
final List<BufferPoolMXBean> pools =
ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class);
for (BufferPoolMXBean pool : pools) {
if (pool.getName().equals("direct")) {
return pool;
}
}
throw new Error("could not find direct pool");
}
private static final BufferPoolMXBean directPool = getDirectPool();
// Each worker will do write operations on a file channel using
// buffers of various sizes. The buffer size is randomly chosen to
// be within a small or a large range. This way we can control
// which buffers can be cached (all, only the small ones, or none)
// by setting the jdk.nio.maxCachedBufferSize property.
private static class Worker implements Runnable {
private final int id;
private final Random random = new Random();
private long smallBufferCount = 0;
private long largeBufferCount = 0;
private int getWriteSize() {
int minSize = 0;
int diff = 0;
if (random.nextInt() % LARGE_BUFFER_FREQUENCY != 0) {
// small buffer
minSize = SMALL_BUFFER_MIN_SIZE;
diff = SMALL_BUFFER_DIFF_SIZE;
smallBufferCount += 1;
} else {
// large buffer
minSize = LARGE_BUFFER_MIN_SIZE;
diff = LARGE_BUFFER_DIFF_SIZE;
largeBufferCount += 1;
}
return minSize + random.nextInt(diff);
}
private void loop() {
final String fileName = String.format("%s%d", FILE_NAME_PREFIX, id);
try {
for (int i = 0; i < iters; i += 1) {
final int writeSize = getWriteSize();
// This will allocate a HeapByteBuffer. It should not
// be a direct buffer, otherwise the write() method on
// the channel below will not create a temporary
// direct buffer for the write.
final ByteBuffer buffer = ByteBuffer.allocate(writeSize);
// Put some random data on it.
while (buffer.hasRemaining()) {
buffer.put((byte) random.nextInt());
}
buffer.rewind();
final Path file = Paths.get(fileName);
try (FileChannel outChannel = FileChannel.open(file, CREATE, TRUNCATE_EXISTING, WRITE)) {
// The write() method will create a temporary
// direct buffer for the write and attempt to cache
// it. It's important that buffer is not a
// direct buffer, otherwise the temporary buffer
// will not be created.
long res = outChannel.write(buffer);
}
if ((i + 1) % VERBOSE_PERIOD == 0) {
System.out.printf(
" Worker %3d | %8d Iters | Small %8d Large %8d | Direct %4d / %7dK\n",
id, i + 1, smallBufferCount, largeBufferCount,
directPool.getCount(), directPool.getTotalCapacity() / 1024);
}
}
} catch (IOException e) {
throw new Error("I/O error", e);
}
}
@Override
public void run() {
loop();
}
public Worker(int id) {
this.id = id;
}
}
public static void checkDirectBuffers(long expectedCount, long expectedMax) {
final long directCount = directPool.getCount();
final long directTotalCapacity = directPool.getTotalCapacity();
System.out.printf("Direct %d / %dK\n",
directCount, directTotalCapacity / 1024);
// Note that directCount could be < expectedCount. This can
// happen if a GC occurs after one of the worker threads exits
// since its thread-local DirectByteBuffer could be cleaned up
// before we reach here.
if (directCount > expectedCount) {
throw new Error(String.format(
"inconsistent direct buffer total count, expected = %d, found = %d",
expectedCount, directCount));
}
if (directTotalCapacity > expectedMax) {
throw new Error(String.format(
"inconsistent direct buffer total capacity, expectex max = %d, found = %d",
expectedMax, directTotalCapacity));
}
}
public static void main(String[] args) {
final String maxBufferSizeStr = System.getProperty("jdk.nio.maxCachedBufferSize");
final long maxBufferSize =
(maxBufferSizeStr != null) ? Long.valueOf(maxBufferSizeStr) : Long.MAX_VALUE;
// We assume that the max cannot be equal to a size of a
// buffer that can be allocated (makes sanity checking at the
// end easier).
if ((SMALL_BUFFER_MIN_SIZE <= maxBufferSize &&
maxBufferSize <= SMALL_BUFFER_MAX_SIZE) ||
(LARGE_BUFFER_MIN_SIZE <= maxBufferSize &&
maxBufferSize <= LARGE_BUFFER_MAX_SIZE)) {
throw new Error(String.format("max buffer size = %d not allowed",
maxBufferSize));
}
System.out.printf("Threads %d | Iterations %d | MaxBufferSize %d\n",
threadNum, iters, maxBufferSize);
System.out.println();
final Thread[] threads = new Thread[threadNum];
for (int i = 0; i < threadNum; i += 1) {
threads[i] = new Thread(new Worker(i));
threads[i].start();
}
try {
for (int i = 0; i < threadNum; i += 1) {
threads[i].join();
}
} catch (InterruptedException e) {
throw new Error("join() interrupted!", e);
}
// There is an assumption here that, at this point, only the
// cached DirectByteBuffers should be active. Given we
// haven't used any other DirectByteBuffers in this test, this
// should hold.
//
// Also note that we can only do the sanity checking at the
// end and not during the run given that, at any time, there
// could be buffers currently in use by some of the workers
// that will not be cached.
System.out.println();
if (maxBufferSize < SMALL_BUFFER_MAX_SIZE) {
// The max buffer size is smaller than all buffers that
// were allocated. No buffers should have been cached.
checkDirectBuffers(0, 0);
} else if (maxBufferSize < LARGE_BUFFER_MIN_SIZE) {
// The max buffer size is larger than all small buffers
// but smaller than all large buffers that were
// allocated. Only small buffers could have been cached.
checkDirectBuffers(threadNum,
(long) threadNum * (long) SMALL_BUFFER_MAX_SIZE);
} else {
// The max buffer size is larger than all buffers that
// were allocated. All buffers could have been cached.
checkDirectBuffers(threadNum,
(long) threadNum * (long) LARGE_BUFFER_MAX_SIZE);
}
}
}
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
/*
* @test
* @bug 8050374
* @key randomness
* @summary This test validates signature verification
* Signature.verify(byte[], int, int). The test uses RandomFactory to
* get random set of clear text data to sign. After the signature
* generation, the test tries to verify signature with the above API
* and passing in different signature offset (0, 33, 66, 99).
* @library /lib/testlibrary
* @compile ../../../java/security/Signature/Offsets.java
* @run main SignatureOffsets SunEC NONEwithECDSA
* @run main SignatureOffsets SunEC SHA1withECDSA
* @run main SignatureOffsets SunEC SHA256withECDSA
* @run main SignatureOffsets SunEC SHA224withECDSA
* @run main SignatureOffsets SunEC SHA384withECDSA
* @run main SignatureOffsets SunEC SHA512withECDSA
*/
public class SignatureOffsets {
public static void main(String[] args) throws NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
Offsets.main(args);
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8050374
* @compile ../../../java/security/SignedObject/Chain.java
* @summary Verify a chain of signed objects
*/
public class SignedObjectChain {
private static class Test extends Chain.Test {
public Test(Chain.SigAlg sigAlg) {
super(sigAlg, Chain.KeyAlg.EC, Chain.Provider.SunEC);
}
}
private static final Test[] tests = {
new Test(Chain.SigAlg.SHA1withECDSA),
new Test(Chain.SigAlg.SHA256withECDSA),
new Test(Chain.SigAlg.SHA224withECDSA),
new Test(Chain.SigAlg.SHA384withECDSA),
new Test(Chain.SigAlg.SHA512withECDSA),
};
public static void main(String argv[]) {
boolean resutl = java.util.Arrays.stream(tests).allMatch(
(test) -> Chain.runTest(test));
if(resutl) {
System.out.println("All tests passed");
} else {
throw new RuntimeException("Some tests failed");
}
}
}
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
/*
* @test
* @bug 8050374
* @key randomness
* @summary This test validates signature verification
* Signature.verify(byte[], int, int). The test uses RandomFactory to
* get random set of clear text data to sign. After the signature
* generation, the test tries to verify signature with the above API
* and passing in different signature offset (0, 33, 66, 99).
* @library /lib/testlibrary
* @compile ../../../java/security/Signature/Offsets.java
* @run main SignatureOffsets SunMSCAPI NONEwithRSA
* @run main SignatureOffsets SunMSCAPI MD2withRSA
* @run main SignatureOffsets SunMSCAPI MD5withRSA
* @run main SignatureOffsets SunMSCAPI SHA1withRSA
* @run main SignatureOffsets SunMSCAPI SHA256withRSA
* @run main SignatureOffsets SunMSCAPI SHA384withRSA
* @run main SignatureOffsets SunMSCAPI SHA512withRSA
*/
public class SignatureOffsets {
public static void main(String[] args) throws NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
Offsets.main(args);
}
}
\ No newline at end of file
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8050374
* @compile ../../../java/security/SignedObject/Chain.java
* @summary Verify a chain of signed objects
*/
public class SignedObjectChain {
private static class Test extends Chain.Test {
public Test(Chain.SigAlg sigAlg) {
super(sigAlg, Chain.KeyAlg.RSA, Chain.Provider.SunMSCAPI);
}
}
private static final Test[] tests = {
new Test(Chain.SigAlg.MD2withRSA),
new Test(Chain.SigAlg.MD5withRSA),
new Test(Chain.SigAlg.SHA1withRSA),
new Test(Chain.SigAlg.SHA256withRSA),
new Test(Chain.SigAlg.SHA384withRSA),
new Test(Chain.SigAlg.SHA512withRSA),
};
public static void main(String argv[]) {
boolean resutl = java.util.Arrays.stream(tests).allMatch(
(test) -> Chain.runTest(test));
if(resutl) {
System.out.println("All tests passed");
} else {
throw new RuntimeException("Some tests failed");
}
}
}
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
/**
* @test
* @bug 8044199
* @summary test if the private and public key size are the same as what is set
* through KeyPairGenerator.
* @run main KeySizeTest 512 10
* @run main KeySizeTest 768 10
* @run main KeySizeTest 1024 10
* @run main KeySizeTest 2048 5
* @run main KeySizeTest 4096 1
*/
public class KeySizeTest {
/**
* ALGORITHM name, fixed as RSA.
*/
private static final String KEYALG = "RSA";
/**
* JDK default RSA Provider.
*/
private static final String PROVIDER_NAME = "SunRsaSign";
public static void main(String[] args) throws Exception {
int iKeyPairSize = Integer.parseInt(args[0]);
int maxLoopCnt = Integer.parseInt(args[1]);
int failCount = 0;
KeyPairGenerator keyPairGen
= KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
keyPairGen.initialize(iKeyPairSize);
// Generate RSA keypair
KeyPair keyPair = keyPairGen.generateKeyPair();
// Get priavte and public keys
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
try {
if (!sizeTest(keyPair)) {
failCount++;
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
failCount++;
}
for (int iCnt = 0; iCnt < maxLoopCnt; iCnt++) {
// Get keysize (modulus) of keys
KeyFactory keyFact = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
// Comparing binary length.
RSAPrivateKeySpec privateKeySpec
= (RSAPrivateKeySpec) keyFact.getKeySpec(privateKey,
RSAPrivateKeySpec.class);
int iPrivateKeySize = privateKeySpec.getModulus().bitLength();
RSAPublicKeySpec publicKeySpec
= (RSAPublicKeySpec) keyFact.getKeySpec(publicKey,
RSAPublicKeySpec.class);
int iPublicKeySize = publicKeySpec.getModulus().bitLength();
if ((iKeyPairSize != iPublicKeySize) || (iKeyPairSize != iPrivateKeySize)) {
System.err.println("iKeyPairSize : " + iKeyPairSize);
System.err.println("Generated a " + iPrivateKeySize
+ " bit RSA private key");
System.err.println("Generated a " + iPublicKeySize
+ " bit RSA public key");
failCount++;
}
}
if (failCount > 0) {
throw new RuntimeException("There are " + failCount + " tests failed.");
}
}
/**
* @param kpair test key pair.
* @return true if test passed. false if test failed.
*/
private static boolean sizeTest(KeyPair kpair) {
RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();
// test the getModulus method
if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
if (!priv.getModulus().equals(pub.getModulus())) {
System.err.println("priv.getModulus() = " + priv.getModulus());
System.err.println("pub.getModulus() = " + pub.getModulus());
return false;
}
}
return true;
}
}
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
/**
* @test
* @bug 8044199 4666485
* @summary Equality checking for RSAPrivateKey by SunRsaSign provider.
*/
public class PrivateKeyEqualityTest {
/**
* ALGORITHM name, fixed as RSA.
*/
private static final String KEYALG = "RSA";
/**
* JDK default RSA Provider.
*/
private static final String PROVIDER_NAME = "SunRsaSign";
public static void main(String[] args) throws NoSuchAlgorithmException,
NoSuchProviderException, InvalidKeySpecException {
// Generate the first key.
KeyPairGenerator generator
= KeyPairGenerator.getInstance(KEYALG, PROVIDER_NAME);
KeyPair keyPair = generator.generateKeyPair();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
if (!(rsaPrivateKey instanceof RSAPrivateCrtKey)) {
System.err.println("rsaPrivateKey class : " + rsaPrivateKey.getClass().getName());
throw new RuntimeException("rsaPrivateKey is not a RSAPrivateCrtKey instance");
}
// Generate the second key.
KeyFactory factory = KeyFactory.getInstance(KEYALG, PROVIDER_NAME);
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent());
RSAPrivateKey rsaPrivateKey2 = (RSAPrivateKey) factory.generatePrivate(
rsaPrivateKeySpec);
// Generate the third key.
PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(
rsaPrivateKey.getEncoded());
RSAPrivateKey rsaPrivateKey3 = (RSAPrivateKey) factory.generatePrivate(
encodedKeySpec);
// Check for equality.
if (rsaPrivateKey.equals(rsaPrivateKey2)) {
throw new RuntimeException("rsaPrivateKey should not equal to rsaPrivateKey2");
}
if (!rsaPrivateKey3.equals(rsaPrivateKey)) {
throw new RuntimeException("rsaPrivateKey3 should equal to rsaPrivateKey");
}
if (rsaPrivateKey3.equals(rsaPrivateKey2)) {
throw new RuntimeException("rsaPrivateKey3 should not equal to rsaPrivateKey2");
}
if (rsaPrivateKey2.equals(rsaPrivateKey3)) {
throw new RuntimeException("rsaPrivateKey2 should not equal to rsaPrivateKey3");
}
// Generate the fourth key.
RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey)rsaPrivateKey;
RSAPrivateCrtKeySpec rsaPrivateCrtKeySpec = new RSAPrivateCrtKeySpec(
rsaPrivateCrtKey.getModulus(),
rsaPrivateCrtKey.getPublicExponent(),
rsaPrivateCrtKey.getPrivateExponent(),
rsaPrivateCrtKey.getPrimeP(),
rsaPrivateCrtKey.getPrimeQ(),
rsaPrivateCrtKey.getPrimeExponentP(),
rsaPrivateCrtKey.getPrimeExponentQ(),
rsaPrivateCrtKey.getCrtCoefficient()
);
RSAPrivateCrtKey rsaPrivateKey4 = (RSAPrivateCrtKey) factory.generatePrivate(
rsaPrivateCrtKeySpec);
if (!rsaPrivateKey.equals(rsaPrivateKey4)) {
throw new RuntimeException("rsaPrivateKey should equal to rsaPrivateKey4");
}
}
}
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
/*
* @test
* @bug 8050374
* @key randomness
* @summary This test validates signature verification
* Signature.verify(byte[], int, int). The test uses RandomFactory to
* get random set of clear text data to sign. After the signature
* generation, the test tries to verify signature with the above API
* and passing in different signature offset (0, 33, 66, 99).
* @library /lib/testlibrary
* @compile ../../../java/security/Signature/Offsets.java
* @run main SignatureOffsets SunRsaSign MD2withRSA
* @run main SignatureOffsets SunRsaSign MD5withRSA
* @run main SignatureOffsets SunRsaSign SHA1withRSA
* @run main SignatureOffsets SunRsaSign SHA224withRSA
* @run main SignatureOffsets SunRsaSign SHA256withRSA
* @run main SignatureOffsets SunRsaSign SHA384withRSA
* @run main SignatureOffsets SunRsaSign SHA512withRSA
*/
public class SignatureOffsets {
public static void main(String[] args) throws NoSuchAlgorithmException,
InvalidKeyException, SignatureException {
Offsets.main(args);
}
}
\ No newline at end of file
此差异已折叠。
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8050374
* @compile ../../../java/security/SignedObject/Chain.java
* @summary Verify a chain of signed objects
*/
public class SignedObjectChain {
private static class Test extends Chain.Test {
public Test(Chain.SigAlg sigAlg) {
super(sigAlg, Chain.KeyAlg.RSA, Chain.Provider.SunRsaSign);
}
}
private static final Test[] tests = {
new Test(Chain.SigAlg.MD2withRSA),
new Test(Chain.SigAlg.MD5withRSA),
new Test(Chain.SigAlg.SHA1withRSA),
new Test(Chain.SigAlg.SHA224withRSA),
new Test(Chain.SigAlg.SHA256withRSA),
new Test(Chain.SigAlg.SHA384withRSA),
new Test(Chain.SigAlg.SHA512withRSA),
};
public static void main(String argv[]) {
boolean resutl = java.util.Arrays.stream(tests).allMatch(
(test) -> Chain.runTest(test));
if(resutl) {
System.out.println("All tests passed");
} else {
throw new RuntimeException("Some tests failed");
}
}
}
/*
* Copyright (c) 2015, 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.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.interfaces.RSAKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAKeyGenParameterSpec;
/**
* @test
* @bug 8044199
* @summary Check same KeyPair's private key and public key have same modulus.
* also check public key's public exponent equals to given spec's public
* exponent.
* @run main SpecTest 512
* @run main SpecTest 768
* @run main SpecTest 1024
* @run main SpecTest 2048
* @run main/timeout=240 SpecTest 4096
* @run main/timeout=240 SpecTest 5120
*/
public class SpecTest {
/**
* ALGORITHM name, fixed as RSA.
*/
private static final String KEYALG = "RSA";
/**
* JDK default RSA Provider.
*/
private static final String PROVIDER = "SunRsaSign";
/**
*
* @param kpair test key pair
* @param pubExponent expected public exponent.
* @return true if test passed. false if test failed.
*/
private static boolean specTest(KeyPair kpair, BigInteger pubExponent) {
boolean passed = true;
RSAPrivateKey priv = (RSAPrivateKey) kpair.getPrivate();
RSAPublicKey pub = (RSAPublicKey) kpair.getPublic();
// test the getModulus method
if ((priv instanceof RSAKey) && (pub instanceof RSAKey)) {
if (!priv.getModulus().equals(pub.getModulus())) {
System.err.println("priv.getModulus() = " + priv.getModulus());
System.err.println("pub.getModulus() = " + pub.getModulus());
passed = false;
}
if (!pubExponent.equals(pub.getPublicExponent())) {
System.err.println("pubExponent = " + pubExponent);
System.err.println("pub.getPublicExponent() = "
+ pub.getPublicExponent());
passed = false;
}
}
return passed;
}
public static void main(String[] args) {
int failCount = 0;
// Test key size.
int size = Integer.parseInt(args[0]);
try {
KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
kpg1.initialize(new RSAKeyGenParameterSpec(size,
RSAKeyGenParameterSpec.F4));
if (!specTest(kpg1.generateKeyPair(),
RSAKeyGenParameterSpec.F4)) {
failCount++;
}
KeyPairGenerator kpg2 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
kpg2.initialize(new RSAKeyGenParameterSpec(size,
RSAKeyGenParameterSpec.F0));
if (!specTest(kpg2.generateKeyPair(), RSAKeyGenParameterSpec.F0)) {
failCount++;
}
} catch (NoSuchAlgorithmException | NoSuchProviderException
| InvalidAlgorithmParameterException ex) {
ex.printStackTrace(System.err);
failCount++;
}
if (failCount != 0) {
throw new RuntimeException("There are " + failCount
+ " tests failed.");
}
}
}
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册