/* * Copyright (c) 1997, 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * 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. */ package java.security; import java.util.ArrayList; import java.util.List; import sun.security.util.Debug; import sun.security.util.SecurityConstants; /** * An AccessControlContext is used to make system resource access decisions * based on the context it encapsulates. * *
More specifically, it encapsulates a context and * has a single method, {@code checkPermission}, * that is equivalent to the {@code checkPermission} method * in the AccessController class, with one difference: The AccessControlContext * {@code checkPermission} method makes access decisions based on the * context it encapsulates, * rather than that of the current execution thread. * *
Thus, the purpose of AccessControlContext is for those situations where * a security check that should be made within a given context * actually needs to be done from within a * different context (for example, from within a worker thread). * *
An AccessControlContext is created by calling the * {@code AccessController.getContext} method. * The {@code getContext} method takes a "snapshot" * of the current calling context, and places * it in an AccessControlContext object, which it returns. A sample call is * the following: * *
* AccessControlContext acc = AccessController.getContext() ** *
* Code within a different context can subsequently call the * {@code checkPermission} method on the * previously-saved AccessControlContext object. A sample call is the * following: * *
* acc.checkPermission(permission) ** * @see AccessController * * @author Roland Schemers */ public final class AccessControlContext { private ProtectionDomain context[]; // isPrivileged and isAuthorized are referenced by the VM - do not remove // or change their names private boolean isPrivileged; private boolean isAuthorized = false; // Note: This field is directly used by the virtual machine // native codes. Don't touch it. private AccessControlContext privilegedContext; private DomainCombiner combiner = null; // limited privilege scope private Permission permissions[]; private AccessControlContext parent; private boolean isWrapped; // is constrained by limited privilege scope? private boolean isLimited; private ProtectionDomain limitedContext[]; private static boolean debugInit = false; private static Debug debug = null; static Debug getDebug() { if (debugInit) return debug; else { if (Policy.isSet()) { debug = Debug.getInstance("access"); debugInit = true; } return debug; } } /** * Create an AccessControlContext with the given array of ProtectionDomains. * Context must not be null. Duplicate domains will be removed from the * context. * * @param context the ProtectionDomains associated with this context. * The non-duplicate domains are copied from the array. Subsequent * changes to the array will not affect this AccessControlContext. * @throws NullPointerException if {@code context} is {@code null} */ public AccessControlContext(ProtectionDomain context[]) { if (context.length == 0) { this.context = null; } else if (context.length == 1) { if (context[0] != null) { this.context = context.clone(); } else { this.context = null; } } else { List
* * @param acc the {@code AccessControlContext} associated * with the provided {@code DomainCombiner}. * * @param combiner the {@code DomainCombiner} to be associated * with the provided {@code AccessControlContext}. * * @exception NullPointerException if the provided * {@code context} is {@code null}. * * @exception SecurityException if a security manager is installed and the * caller does not have the "createAccessControlContext" * {@link SecurityPermission} * @since 1.3 */ public AccessControlContext(AccessControlContext acc, DomainCombiner combiner) { this(acc, combiner, false); } /** * package private to allow calls from ProtectionDomain without performing * the security check for {@linkplain SecurityConstants.CREATE_ACC_PERMISSION} * permission */ AccessControlContext(AccessControlContext acc, DomainCombiner combiner, boolean preauthorized) { if (!preauthorized) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(SecurityConstants.CREATE_ACC_PERMISSION); this.isAuthorized = true; } } else { this.isAuthorized = true; } this.context = acc.context; // we do not need to run the combine method on the // provided ACC. it was already "combined" when the // context was originally retrieved. // // at this point in time, we simply throw away the old // combiner and use the newly provided one. this.combiner = combiner; } /** * package private for AccessController * * This "argument wrapper" context will be passed as the actual context * parameter on an internal doPrivileged() call used in the implementation. */ AccessControlContext(ProtectionDomain caller, DomainCombiner combiner, AccessControlContext parent, AccessControlContext context, Permission[] perms) { /* * Combine the domains from the doPrivileged() context into our * wrapper context, if necessary. */ ProtectionDomain[] callerPDs = null; if (caller != null) { callerPDs = new ProtectionDomain[] { caller }; } if (context != null) { if (combiner != null) { this.context = combiner.combine(callerPDs, context.context); } else { this.context = combine(callerPDs, context.context); } } else { /* * Call combiner even if there is seemingly nothing to combine. */ if (combiner != null) { this.context = combiner.combine(callerPDs, null); } else { this.context = combine(callerPDs, null); } } this.combiner = combiner; Permission[] tmp = null; if (perms != null) { tmp = new Permission[perms.length]; for (int i=0; i < perms.length; i++) { if (perms[i] == null) { throw new NullPointerException("permission can't be null"); } /* * An AllPermission argument is equivalent to calling * doPrivileged() without any limit permissions. */ if (perms[i].getClass() == AllPermission.class) { parent = null; } tmp[i] = perms[i]; } } /* * For a doPrivileged() with limited privilege scope, initialize * the relevant fields. * * The limitedContext field contains the union of all domains which * are enclosed by this limited privilege scope. In other words, * it contains all of the domains which could potentially be checked * if none of the limiting permissions implied a requested permission. */ if (parent != null) { this.limitedContext = combine(parent.context, parent.limitedContext); this.isLimited = true; this.isWrapped = true; this.permissions = tmp; this.parent = parent; this.privilegedContext = context; // used in checkPermission2() } this.isAuthorized = true; } /** * package private constructor for AccessController.getContext() */ AccessControlContext(ProtectionDomain context[], boolean isPrivileged) { this.context = context; this.isPrivileged = isPrivileged; this.isAuthorized = true; } /** * Constructor for JavaSecurityAccess.doIntersectionPrivilege() */ AccessControlContext(ProtectionDomain[] context, AccessControlContext privilegedContext) { this.context = context; this.privilegedContext = privilegedContext; this.isPrivileged = true; } /** * Returns this context's context. */ ProtectionDomain[] getContext() { return context; } /** * Returns true if this context is privileged. */ boolean isPrivileged() { return isPrivileged; } /** * get the assigned combiner from the privileged or inherited context */ DomainCombiner getAssignedCombiner() { AccessControlContext acc; if (isPrivileged) { acc = privilegedContext; } else { acc = AccessController.getInheritedAccessControlContext(); } if (acc != null) { return acc.combiner; } return null; } /** * Get the {@code DomainCombiner} associated with this * {@code AccessControlContext}. * *
* * @return the {@code DomainCombiner} associated with this * {@code AccessControlContext}, or {@code null} * if there is none. * * @exception SecurityException if a security manager is installed and * the caller does not have the "getDomainCombiner" * {@link SecurityPermission} * @since 1.3 */ public DomainCombiner getDomainCombiner() { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(SecurityConstants.GET_COMBINER_PERMISSION); } return getCombiner(); } /** * package private for AccessController */ DomainCombiner getCombiner() { return combiner; } boolean isAuthorized() { return isAuthorized; } /** * Determines whether the access request indicated by the * specified permission should be allowed or denied, based on * the security policy currently in effect, and the context in * this object. The request is allowed only if every ProtectionDomain * in the context implies the permission. Otherwise the request is * denied. * *
* This method quietly returns if the access request
* is permitted, or throws a suitable AccessControlException otherwise.
*
* @param perm the requested permission.
*
* @exception AccessControlException if the specified permission
* is not permitted, based on the current security policy and the
* context encapsulated by this object.
* @exception NullPointerException if the permission to check for is null.
*/
public void checkPermission(Permission perm)
throws AccessControlException
{
boolean dumpDebug = false;
if (perm == null) {
throw new NullPointerException("permission can't be null");
}
if (getDebug() != null) {
// If "codebase" is not specified, we dump the info by default.
dumpDebug = !Debug.isOn("codebase=");
if (!dumpDebug) {
// If "codebase" is specified, only dump if the specified code
// value is in the stack.
for (int i = 0; context != null && i < context.length; i++) {
if (context[i].getCodeSource() != null &&
context[i].getCodeSource().getLocation() != null &&
Debug.isOn("codebase=" + context[i].getCodeSource().getLocation().toString())) {
dumpDebug = true;
break;
}
}
}
dumpDebug &= !Debug.isOn("permission=") ||
Debug.isOn("permission=" + perm.getClass().getCanonicalName());
if (dumpDebug && Debug.isOn("stack")) {
Thread.dumpStack();
}
if (dumpDebug && Debug.isOn("domain")) {
if (context == null) {
debug.println("domain (context is null)");
} else {
for (int i=0; i< context.length; i++) {
debug.println("domain "+i+" "+context[i]);
}
}
}
}
/*
* iterate through the ProtectionDomains in the context.
* Stop at the first one that doesn't allow the
* requested permission (throwing an exception).
*
*/
/* if ctxt is null, all we had on the stack were system domains,
or the first domain was a Privileged system domain. This
is to make the common case for system code very fast */
if (context == null) {
checkPermission2(perm);
return;
}
for (int i=0; i< context.length; i++) {
if (context[i] != null && !context[i].implies(perm)) {
if (dumpDebug) {
debug.println("access denied " + perm);
}
if (Debug.isOn("failure") && debug != null) {
// Want to make sure this is always displayed for failure,
// but do not want to display again if already displayed
// above.
if (!dumpDebug) {
debug.println("access denied " + perm);
}
Thread.dumpStack();
final ProtectionDomain pd = context[i];
final Debug db = debug;
AccessController.doPrivileged (new PrivilegedAction
* @param obj the object we are testing for equality with this object.
* @return true if obj is an AccessControlContext, and has the
* same set of ProtectionDomains as this context, false otherwise.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if (! (obj instanceof AccessControlContext))
return false;
AccessControlContext that = (AccessControlContext) obj;
if (!equalContext(that))
return false;
if (!equalLimitedContext(that))
return false;
return true;
}
/*
* Compare for equality based on state that is free of limited
* privilege complications.
*/
private boolean equalContext(AccessControlContext that) {
if (!equalPDs(this.context, that.context))
return false;
if (this.combiner == null && that.combiner != null)
return false;
if (this.combiner != null && !this.combiner.equals(that.combiner))
return false;
return true;
}
private boolean equalPDs(ProtectionDomain[] a, ProtectionDomain[] b) {
if (a == null) {
return (b == null);
}
if (b == null)
return false;
if (!(containsAllPDs(a, b) && containsAllPDs(b, a)))
return false;
return true;
}
/*
* Compare for equality based on state that is captured during a
* call to AccessController.getContext() when a limited privilege
* scope is in effect.
*/
private boolean equalLimitedContext(AccessControlContext that) {
if (that == null)
return false;
/*
* If neither instance has limited privilege scope then we're done.
*/
if (!this.isLimited && !that.isLimited)
return true;
/*
* If only one instance has limited privilege scope then we're done.
*/
if (!(this.isLimited && that.isLimited))
return false;
/*
* Wrapped instances should never escape outside the implementation
* this class and AccessController so this will probably never happen
* but it only makes any sense to compare if they both have the same
* isWrapped state.
*/
if ((this.isWrapped && !that.isWrapped) ||
(!this.isWrapped && that.isWrapped)) {
return false;
}
if (this.permissions == null && that.permissions != null)
return false;
if (this.permissions != null && that.permissions == null)
return false;
if (!(this.containsAllLimits(that) && that.containsAllLimits(this)))
return false;
/*
* Skip through any wrapped contexts.
*/
AccessControlContext thisNextPC = getNextPC(this);
AccessControlContext thatNextPC = getNextPC(that);
/*
* The protection domains and combiner of a privilegedContext are
* not relevant because they have already been included in the context
* of this instance by optimize() so we only care about any limited
* privilege state they may have.
*/
if (thisNextPC == null && thatNextPC != null && thatNextPC.isLimited)
return false;
if (thisNextPC != null && !thisNextPC.equalLimitedContext(thatNextPC))
return false;
if (this.parent == null && that.parent != null)
return false;
if (this.parent != null && !this.parent.equals(that.parent))
return false;
return true;
}
/*
* Follow the privilegedContext link making our best effort to skip
* through any wrapper contexts.
*/
private static AccessControlContext getNextPC(AccessControlContext acc) {
while (acc != null && acc.privilegedContext != null) {
acc = acc.privilegedContext;
if (!acc.isWrapped)
return acc;
}
return null;
}
private static boolean containsAllPDs(ProtectionDomain[] thisContext,
ProtectionDomain[] thatContext) {
boolean match = false;
//
// ProtectionDomains within an ACC currently cannot be null
// and this is enforced by the constructor and the various
// optimize methods. However, historically this logic made attempts
// to support the notion of a null PD and therefore this logic continues
// to support that notion.
ProtectionDomain thisPd;
for (int i = 0; i < thisContext.length; i++) {
match = false;
if ((thisPd = thisContext[i]) == null) {
for (int j = 0; (j < thatContext.length) && !match; j++) {
match = (thatContext[j] == null);
}
} else {
Class> thisPdClass = thisPd.getClass();
ProtectionDomain thatPd;
for (int j = 0; (j < thatContext.length) && !match; j++) {
thatPd = thatContext[j];
// Class check required to avoid PD exposure (4285406)
match = (thatPd != null &&
thisPdClass == thatPd.getClass() && thisPd.equals(thatPd));
}
}
if (!match) return false;
}
return match;
}
private boolean containsAllLimits(AccessControlContext that) {
boolean match = false;
Permission thisPerm;
if (this.permissions == null && that.permissions == null)
return true;
for (int i = 0; i < this.permissions.length; i++) {
Permission limit = this.permissions[i];
Class > limitClass = limit.getClass();
match = false;
for (int j = 0; (j < that.permissions.length) && !match; j++) {
Permission perm = that.permissions[j];
match = (limitClass.equals(perm.getClass()) &&
limit.equals(perm));
}
if (!match) return false;
}
return match;
}
/**
* Returns the hash code value for this context. The hash code
* is computed by exclusive or-ing the hash code of all the protection
* domains in the context together.
*
* @return a hash code value for this context.
*/
public int hashCode() {
int hashCode = 0;
if (context == null)
return hashCode;
for (int i =0; i < context.length; i++) {
if (context[i] != null)
hashCode ^= context[i].hashCode();
}
return hashCode;
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 2900
Content-Disposition: inline; filename="AccessControlException.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "a4f2a7803adbbc264355da9c017cf13f05f4969d"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* This exception is thrown by the AccessController to indicate
* that a requested access (to a critical system resource such as the
* file system or the network) is denied.
*
* The reason to deny access can vary. For example, the requested
* permission might be of an incorrect type, contain an invalid
* value, or request access that is not allowed according to the
* security policy. Such information should be given whenever
* possible at the time the exception is thrown.
*
* @author Li Gong
* @author Roland Schemers
*/
public class AccessControlException extends SecurityException {
private static final long serialVersionUID = 5138225684096988535L;
// the permission that caused the exception to be thrown.
private Permission perm;
/**
* Constructs an {@code AccessControlException} with the
* specified, detailed message.
*
* @param s the detail message.
*/
public AccessControlException(String s) {
super(s);
}
/**
* Constructs an {@code AccessControlException} with the
* specified, detailed message, and the requested permission that caused
* the exception.
*
* @param s the detail message.
* @param p the permission that caused the exception.
*/
public AccessControlException(String s, Permission p) {
super(s);
perm = p;
}
/**
* Gets the Permission object associated with this exception, or
* null if there was no corresponding Permission object.
*
* @return the Permission object.
*/
public Permission getPermission() {
return perm;
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 37103
Content-Disposition: inline; filename="AccessController.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "00e084ca96b8821a6e4cf6bccf6cd1672dd89150"
/*
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import sun.security.util.Debug;
import sun.reflect.CallerSensitive;
import sun.reflect.Reflection;
/**
* The AccessController class is used for access control operations
* and decisions.
*
* More specifically, the AccessController class is used for
* three purposes:
*
* The {@link #checkPermission(Permission) checkPermission} method
* determines whether the access request indicated by a specified
* permission should be granted or denied. A sample call appears
* below. In this example, {@code checkPermission} will determine
* whether or not to grant "read" access to the file named "testFile" in
* the "/temp" directory.
*
* If a requested access is allowed,
* {@code checkPermission} returns quietly. If denied, an
* AccessControlException is
* thrown. AccessControlException can also be thrown if the requested
* permission is of an incorrect type or contains an invalid value.
* Such information is given whenever possible.
*
* Suppose the current thread traversed m callers, in the order of caller 1
* to caller 2 to caller m. Then caller m invoked the
* {@code checkPermission} method.
* The {@code checkPermission} method determines whether access
* is granted or denied based on the following algorithm:
*
* A caller can be marked as being "privileged"
* (see {@link #doPrivileged(PrivilegedAction) doPrivileged} and below).
* When making access control decisions, the {@code checkPermission}
* method stops checking if it reaches a caller that
* was marked as "privileged" via a {@code doPrivileged}
* call without a context argument (see below for information about a
* context argument). If that caller's domain has the
* specified permission and at least one limiting permission argument (if any)
* implies the requested permission, no further checking is done and
* {@code checkPermission}
* returns quietly, indicating that the requested access is allowed.
* If that domain does not have the specified permission, an exception
* is thrown, as usual. If the caller's domain had the specified permission
* but it was not implied by any limiting permission arguments given in the call
* to {@code doPrivileged} then the permission checking continues
* until there are no more callers or another {@code doPrivileged}
* call matches the requested permission and returns normally.
*
* The normal use of the "privileged" feature is as follows. If you
* don't need to return a value from within the "privileged" block, do
* the following:
*
*
* PrivilegedAction is an interface with a single method, named
* {@code run}.
* The above example shows creation of an implementation
* of that interface; a concrete implementation of the
* {@code run} method is supplied.
* When the call to {@code doPrivileged} is made, an
* instance of the PrivilegedAction implementation is passed
* to it. The {@code doPrivileged} method calls the
* {@code run} method from the PrivilegedAction
* implementation after enabling privileges, and returns the
* {@code run} method's return value as the
* {@code doPrivileged} return value (which is
* ignored in this example).
*
* If you need to return a value, you can do something like the following:
*
* If the action performed in your {@code run} method could
* throw a "checked" exception (those listed in the {@code throws} clause
* of a method), then you need to use the
* {@code PrivilegedExceptionAction} interface instead of the
* {@code PrivilegedAction} interface:
*
* Be *very* careful in your use of the "privileged" construct, and
* always remember to make the privileged code section as small as possible.
* You can pass {@code Permission} arguments to further limit the
* scope of the "privilege" (see below).
*
*
* Note that {@code checkPermission} always performs security checks
* within the context of the currently executing thread.
* Sometimes a security check that should be made within a given context
* will actually need to be done from within a
* different context (for example, from within a worker thread).
* The {@link #getContext() getContext} method and
* AccessControlContext class are provided
* for this situation. The {@code getContext} method takes a "snapshot"
* of the current calling context, and places
* it in an AccessControlContext object, which it returns. A sample call is
* the following:
*
*
* AccessControlContext itself has a {@code checkPermission} method
* that makes access decisions based on the context it encapsulates,
* rather than that of the current execution thread.
* Code within a different context can thus call that method on the
* previously-saved AccessControlContext object. A sample call is the
* following:
*
* There are also times where you don't know a priori which permissions
* to check the context against. In these cases you can use the
* doPrivileged method that takes a context. You can also limit the scope
* of the privileged code by passing additional {@code Permission}
* parameters.
*
* Passing a limiting {@code Permission} argument of an instance of
* {@code AllPermission} is equivalent to calling the equivalent
* {@code doPrivileged} method without limiting {@code Permission}
* arguments. Passing a zero length array of {@code Permission} disables
* the code privileges so that checking always continues beyond the caller of
* that {@code doPrivileged} method.
*
* @see AccessControlContext
*
* @author Li Gong
* @author Roland Schemers
*/
public final class AccessController {
/**
* Don't allow anyone to instantiate an AccessController
*/
private AccessController() { }
/**
* Performs the specified {@code PrivilegedAction} with privileges
* enabled. The action is performed with all of the permissions
* possessed by the caller's protection domain.
*
* If the action's {@code run} method throws an (unchecked)
* exception, it will propagate through this method.
*
* Note that any DomainCombiner associated with the current
* AccessControlContext will be ignored while the action is performed.
*
* @param If the action's {@code run} method throws an (unchecked)
* exception, it will propagate through this method.
*
* This method preserves the current AccessControlContext's
* DomainCombiner (which may be null) while the action is performed.
*
* @param
* If the action's {@code run} method throws an (unchecked) exception,
* it will propagate through this method.
*
* If a security manager is installed and the specified
* {@code AccessControlContext} was not created by system code and the
* caller's {@code ProtectionDomain} has not been granted the
* {@literal "createAccessControlContext"}
* {@link java.security.SecurityPermission}, then the action is performed
* with no permissions.
*
* @param
* If the action's {@code run} method throws an (unchecked) exception,
* it will propagate through this method.
*
* If a security manager is installed and the specified
* {@code AccessControlContext} was not created by system code and the
* caller's {@code ProtectionDomain} has not been granted the
* {@literal "createAccessControlContext"}
* {@link java.security.SecurityPermission}, then the action is performed
* with no permissions.
*
* @param
* If the action's {@code run} method throws an (unchecked) exception,
* it will propagate through this method.
*
* This method preserves the current AccessControlContext's
* DomainCombiner (which may be null) while the action is performed.
*
* If a security manager is installed and the specified
* {@code AccessControlContext} was not created by system code and the
* caller's {@code ProtectionDomain} has not been granted the
* {@literal "createAccessControlContext"}
* {@link java.security.SecurityPermission}, then the action is performed
* with no permissions.
*
* @param If the action's {@code run} method throws an unchecked
* exception, it will propagate through this method.
*
* Note that any DomainCombiner associated with the current
* AccessControlContext will be ignored while the action is performed.
*
* @param If the action's {@code run} method throws an unchecked
* exception, it will propagate through this method.
*
* This method preserves the current AccessControlContext's
* DomainCombiner (which may be null) while the action is performed.
*
* @param
* If the action's {@code run} method throws an unchecked
* exception, it will propagate through this method.
*
* If a security manager is installed and the specified
* {@code AccessControlContext} was not created by system code and the
* caller's {@code ProtectionDomain} has not been granted the
* {@literal "createAccessControlContext"}
* {@link java.security.SecurityPermission}, then the action is performed
* with no permissions.
*
* @param
* If the action's {@code run} method throws an (unchecked) exception,
* it will propagate through this method.
*
* If a security manager is installed and the specified
* {@code AccessControlContext} was not created by system code and the
* caller's {@code ProtectionDomain} has not been granted the
* {@literal "createAccessControlContext"}
* {@link java.security.SecurityPermission}, then the action is performed
* with no permissions.
*
* @param
* If the action's {@code run} method throws an (unchecked) exception,
* it will propagate through this method.
*
* This method preserves the current AccessControlContext's
* DomainCombiner (which may be null) while the action is performed.
*
* If a security manager is installed and the specified
* {@code AccessControlContext} was not created by system code and the
* caller's {@code ProtectionDomain} has not been granted the
* {@literal "createAccessControlContext"}
* {@link java.security.SecurityPermission}, then the action is performed
* with no permissions.
*
* @param
* {@code AlgorithmConstraints} objects are immutable. An implementation
* of this interface should not provide methods that can change the state
* of an instance once it has been created.
*
* Note that {@code AlgorithmConstraints} can be used to represent the
* restrictions described by the security properties
* {@code jdk.certpath.disabledAlgorithms} and
* {@code jdk.tls.disabledAlgorithms}, or could be used by a
* concrete {@code PKIXCertPathChecker} to check whether a specified
* certificate in the certification path contains the required algorithm
* constraints.
*
* @see javax.net.ssl.SSLParameters#getAlgorithmConstraints
* @see javax.net.ssl.SSLParameters#setAlgorithmConstraints(AlgorithmConstraints)
*
* @since 1.7
*/
public interface AlgorithmConstraints {
/**
* Determines whether an algorithm is granted permission for the
* specified cryptographic primitives.
*
* @param primitives a set of cryptographic primitives
* @param algorithm the algorithm name
* @param parameters the algorithm parameters, or null if no additional
* parameters
*
* @return true if the algorithm is permitted and can be used for all
* of the specified cryptographic primitives
*
* @throws IllegalArgumentException if primitives or algorithm is null
* or empty
*/
public boolean permits(Set
* This method is usually used to check key size and key usage.
*
* @param primitives a set of cryptographic primitives
* @param key the key
*
* @return true if the key can be used for all of the specified
* cryptographic primitives
*
* @throws IllegalArgumentException if primitives is null or empty,
* or the key is null
*/
public boolean permits(Set The object that will generate the parameters can be initialized
* in two different ways: in an algorithm-independent manner, or in an
* algorithm-specific manner:
*
* In case the client does not explicitly initialize the
* AlgorithmParameterGenerator
* (via a call to an {@code init} method), each provider must supply (and
* document) a default initialization. For example, the Sun provider uses a
* default modulus prime size of 1024 bits for the generation of DSA
* parameters.
*
* Every implementation of the Java platform is required to support the
* following standard {@code AlgorithmParameterGenerator} algorithms and
* keysizes in parentheses:
* This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new AlgorithmParameterGenerator object encapsulating the
* AlgorithmParameterGeneratorSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the name of the algorithm this
* parameter generator is associated with.
* See the AlgorithmParameterGenerator section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @return the new AlgorithmParameterGenerator object.
*
* @exception NoSuchAlgorithmException if no Provider supports an
* AlgorithmParameterGeneratorSpi implementation for the
* specified algorithm.
*
* @see Provider
*/
public static AlgorithmParameterGenerator getInstance(String algorithm)
throws NoSuchAlgorithmException {
try {
Object[] objs = Security.getImpl(algorithm,
"AlgorithmParameterGenerator",
(String)null);
return new AlgorithmParameterGenerator
((AlgorithmParameterGeneratorSpi)objs[0],
(Provider)objs[1],
algorithm);
} catch(NoSuchProviderException e) {
throw new NoSuchAlgorithmException(algorithm + " not found");
}
}
/**
* Returns an AlgorithmParameterGenerator object for generating
* a set of parameters to be used with the specified algorithm.
*
* A new AlgorithmParameterGenerator object encapsulating the
* AlgorithmParameterGeneratorSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the name of the algorithm this
* parameter generator is associated with.
* See the AlgorithmParameterGenerator section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the string name of the Provider.
*
* @return the new AlgorithmParameterGenerator object.
*
* @exception NoSuchAlgorithmException if an AlgorithmParameterGeneratorSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the provider name is null
* or empty.
*
* @see Provider
*/
public static AlgorithmParameterGenerator getInstance(String algorithm,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm,
"AlgorithmParameterGenerator",
provider);
return new AlgorithmParameterGenerator
((AlgorithmParameterGeneratorSpi)objs[0], (Provider)objs[1],
algorithm);
}
/**
* Returns an AlgorithmParameterGenerator object for generating
* a set of parameters to be used with the specified algorithm.
*
* A new AlgorithmParameterGenerator object encapsulating the
* AlgorithmParameterGeneratorSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the string name of the algorithm this
* parameter generator is associated with.
* See the AlgorithmParameterGenerator section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the Provider object.
*
* @return the new AlgorithmParameterGenerator object.
*
* @exception NoSuchAlgorithmException if an AlgorithmParameterGeneratorSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the specified provider is null.
*
* @see Provider
*
* @since 1.4
*/
public static AlgorithmParameterGenerator getInstance(String algorithm,
Provider provider)
throws NoSuchAlgorithmException
{
if (provider == null)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm,
"AlgorithmParameterGenerator",
provider);
return new AlgorithmParameterGenerator
((AlgorithmParameterGeneratorSpi)objs[0], (Provider)objs[1],
algorithm);
}
/**
* Returns the provider of this algorithm parameter generator object.
*
* @return the provider of this algorithm parameter generator object
*/
public final Provider getProvider() {
return this.provider;
}
/**
* Initializes this parameter generator for a certain size.
* To create the parameters, the {@code SecureRandom}
* implementation of the highest-priority installed provider is used as
* the source of randomness.
* (If none of the installed providers supply an implementation of
* {@code SecureRandom}, a system-provided source of randomness is
* used.)
*
* @param size the size (number of bits).
*/
public final void init(int size) {
paramGenSpi.engineInit(size, new SecureRandom());
}
/**
* Initializes this parameter generator for a certain size and source
* of randomness.
*
* @param size the size (number of bits).
* @param random the source of randomness.
*/
public final void init(int size, SecureRandom random) {
paramGenSpi.engineInit(size, random);
}
/**
* Initializes this parameter generator with a set of algorithm-specific
* parameter generation values.
* To generate the parameters, the {@code SecureRandom}
* implementation of the highest-priority installed provider is used as
* the source of randomness.
* (If none of the installed providers supply an implementation of
* {@code SecureRandom}, a system-provided source of randomness is
* used.)
*
* @param genParamSpec the set of algorithm-specific parameter generation values.
*
* @exception InvalidAlgorithmParameterException if the given parameter
* generation values are inappropriate for this parameter generator.
*/
public final void init(AlgorithmParameterSpec genParamSpec)
throws InvalidAlgorithmParameterException {
paramGenSpi.engineInit(genParamSpec, new SecureRandom());
}
/**
* Initializes this parameter generator with a set of algorithm-specific
* parameter generation values.
*
* @param genParamSpec the set of algorithm-specific parameter generation values.
* @param random the source of randomness.
*
* @exception InvalidAlgorithmParameterException if the given parameter
* generation values are inappropriate for this parameter generator.
*/
public final void init(AlgorithmParameterSpec genParamSpec,
SecureRandom random)
throws InvalidAlgorithmParameterException {
paramGenSpi.engineInit(genParamSpec, random);
}
/**
* Generates the parameters.
*
* @return the new AlgorithmParameters object.
*/
public final AlgorithmParameters generateParameters() {
return paramGenSpi.engineGenerateParameters();
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 3344
Content-Disposition: inline; filename="AlgorithmParameterGeneratorSpi.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "721fb52ac180726506bf4a263a6d2e821203346a"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.security.spec.AlgorithmParameterSpec;
/**
* This class defines the Service Provider Interface (SPI)
* for the {@code AlgorithmParameterGenerator} class, which
* is used to generate a set of parameters to be used with a certain algorithm.
*
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a parameter generator for a particular algorithm.
*
* In case the client does not explicitly initialize the
* AlgorithmParameterGenerator (via a call to an {@code engineInit}
* method), each provider must supply (and document) a default initialization.
* For example, the Sun provider uses a default modulus prime size of 1024
* bits for the generation of DSA parameters.
*
* @author Jan Luehe
*
*
* @see AlgorithmParameterGenerator
* @see AlgorithmParameters
* @see java.security.spec.AlgorithmParameterSpec
*
* @since 1.2
*/
public abstract class AlgorithmParameterGeneratorSpi {
/**
* Initializes this parameter generator for a certain size
* and source of randomness.
*
* @param size the size (number of bits).
* @param random the source of randomness.
*/
protected abstract void engineInit(int size, SecureRandom random);
/**
* Initializes this parameter generator with a set of
* algorithm-specific parameter generation values.
*
* @param genParamSpec the set of algorithm-specific parameter generation values.
* @param random the source of randomness.
*
* @exception InvalidAlgorithmParameterException if the given parameter
* generation values are inappropriate for this parameter generator.
*/
protected abstract void engineInit(AlgorithmParameterSpec genParamSpec,
SecureRandom random)
throws InvalidAlgorithmParameterException;
/**
* Generates the parameters.
*
* @return the new AlgorithmParameters object.
*/
protected abstract AlgorithmParameters engineGenerateParameters();
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 15314
Content-Disposition: inline; filename="AlgorithmParameters.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "b548fcb64c8a9c0e438dc81f3565ad32dfa50d00"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.io.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
/**
* This class is used as an opaque representation of cryptographic parameters.
*
* An {@code AlgorithmParameters} object for managing the parameters
* for a particular algorithm can be obtained by
* calling one of the {@code getInstance} factory methods
* (static methods that return instances of a given class).
*
* Once an {@code AlgorithmParameters} object is obtained, it must be
* initialized via a call to {@code init}, using an appropriate parameter
* specification or parameter encoding.
*
* A transparent parameter specification is obtained from an
* {@code AlgorithmParameters} object via a call to
* {@code getParameterSpec}, and a byte encoding of the parameters is
* obtained via a call to {@code getEncoded}.
*
* Every implementation of the Java platform is required to support the
* following standard {@code AlgorithmParameters} algorithms:
* This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new AlgorithmParameters object encapsulating the
* AlgorithmParametersSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* The returned parameter object must be initialized via a call to
* {@code init}, using an appropriate parameter specification or
* parameter encoding.
*
* @param algorithm the name of the algorithm requested.
* See the AlgorithmParameters section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @return the new parameter object.
*
* @exception NoSuchAlgorithmException if no Provider supports an
* AlgorithmParametersSpi implementation for the
* specified algorithm.
*
* @see Provider
*/
public static AlgorithmParameters getInstance(String algorithm)
throws NoSuchAlgorithmException {
try {
Object[] objs = Security.getImpl(algorithm, "AlgorithmParameters",
(String)null);
return new AlgorithmParameters((AlgorithmParametersSpi)objs[0],
(Provider)objs[1],
algorithm);
} catch(NoSuchProviderException e) {
throw new NoSuchAlgorithmException(algorithm + " not found");
}
}
/**
* Returns a parameter object for the specified algorithm.
*
* A new AlgorithmParameters object encapsulating the
* AlgorithmParametersSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* The returned parameter object must be initialized via a call to
* {@code init}, using an appropriate parameter specification or
* parameter encoding.
*
* @param algorithm the name of the algorithm requested.
* See the AlgorithmParameters section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new parameter object.
*
* @exception NoSuchAlgorithmException if an AlgorithmParametersSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the provider name is null
* or empty.
*
* @see Provider
*/
public static AlgorithmParameters getInstance(String algorithm,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm, "AlgorithmParameters",
provider);
return new AlgorithmParameters((AlgorithmParametersSpi)objs[0],
(Provider)objs[1],
algorithm);
}
/**
* Returns a parameter object for the specified algorithm.
*
* A new AlgorithmParameters object encapsulating the
* AlgorithmParametersSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* The returned parameter object must be initialized via a call to
* {@code init}, using an appropriate parameter specification or
* parameter encoding.
*
* @param algorithm the name of the algorithm requested.
* See the AlgorithmParameters section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new parameter object.
*
* @exception NoSuchAlgorithmException if an AlgorithmParameterGeneratorSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the provider is null.
*
* @see Provider
*
* @since 1.4
*/
public static AlgorithmParameters getInstance(String algorithm,
Provider provider)
throws NoSuchAlgorithmException
{
if (provider == null)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm, "AlgorithmParameters",
provider);
return new AlgorithmParameters((AlgorithmParametersSpi)objs[0],
(Provider)objs[1],
algorithm);
}
/**
* Returns the provider of this parameter object.
*
* @return the provider of this parameter object
*/
public final Provider getProvider() {
return this.provider;
}
/**
* Initializes this parameter object using the parameters
* specified in {@code paramSpec}.
*
* @param paramSpec the parameter specification.
*
* @exception InvalidParameterSpecException if the given parameter
* specification is inappropriate for the initialization of this parameter
* object, or if this parameter object has already been initialized.
*/
public final void init(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException
{
if (this.initialized)
throw new InvalidParameterSpecException("already initialized");
paramSpi.engineInit(paramSpec);
this.initialized = true;
}
/**
* Imports the specified parameters and decodes them according to the
* primary decoding format for parameters. The primary decoding
* format for parameters is ASN.1, if an ASN.1 specification for this type
* of parameters exists.
*
* @param params the encoded parameters.
*
* @exception IOException on decoding errors, or if this parameter object
* has already been initialized.
*/
public final void init(byte[] params) throws IOException {
if (this.initialized)
throw new IOException("already initialized");
paramSpi.engineInit(params);
this.initialized = true;
}
/**
* Imports the parameters from {@code params} and decodes them
* according to the specified decoding scheme.
* If {@code format} is null, the
* primary decoding format for parameters is used. The primary decoding
* format is ASN.1, if an ASN.1 specification for these parameters
* exists.
*
* @param params the encoded parameters.
*
* @param format the name of the decoding scheme.
*
* @exception IOException on decoding errors, or if this parameter object
* has already been initialized.
*/
public final void init(byte[] params, String format) throws IOException {
if (this.initialized)
throw new IOException("already initialized");
paramSpi.engineInit(params, format);
this.initialized = true;
}
/**
* Returns a (transparent) specification of this parameter object.
* {@code paramSpec} identifies the specification class in which
* the parameters should be returned. It could, for example, be
* {@code DSAParameterSpec.class}, to indicate that the
* parameters should be returned in an instance of the
* {@code DSAParameterSpec} class.
*
* @param All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply parameter management
* for a particular algorithm.
*
* @author Jan Luehe
*
*
* @see AlgorithmParameters
* @see java.security.spec.AlgorithmParameterSpec
* @see java.security.spec.DSAParameterSpec
*
* @since 1.2
*/
public abstract class AlgorithmParametersSpi {
/**
* Initializes this parameters object using the parameters
* specified in {@code paramSpec}.
*
* @param paramSpec the parameter specification.
*
* @exception InvalidParameterSpecException if the given parameter
* specification is inappropriate for the initialization of this parameter
* object.
*/
protected abstract void engineInit(AlgorithmParameterSpec paramSpec)
throws InvalidParameterSpecException;
/**
* Imports the specified parameters and decodes them
* according to the primary decoding format for parameters.
* The primary decoding format for parameters is ASN.1, if an ASN.1
* specification for this type of parameters exists.
*
* @param params the encoded parameters.
*
* @exception IOException on decoding errors
*/
protected abstract void engineInit(byte[] params)
throws IOException;
/**
* Imports the parameters from {@code params} and
* decodes them according to the specified decoding format.
* If {@code format} is null, the
* primary decoding format for parameters is used. The primary decoding
* format is ASN.1, if an ASN.1 specification for these parameters
* exists.
*
* @param params the encoded parameters.
*
* @param format the name of the decoding format.
*
* @exception IOException on decoding errors
*/
protected abstract void engineInit(byte[] params, String format)
throws IOException;
/**
* Returns a (transparent) specification of this parameters
* object.
* {@code paramSpec} identifies the specification class in which
* the parameters should be returned. It could, for example, be
* {@code DSAParameterSpec.class}, to indicate that the
* parameters should be returned in an instance of the
* {@code DSAParameterSpec} class.
*
* @param
* Note: Granting AllPermission should be done with extreme care,
* as it implies all other permissions. Thus, it grants code the ability
* to run with security
* disabled. Extreme caution should be taken before granting such
* a permission to code. This permission should be used only during testing,
* or in extremely rare cases where an application or applet is
* completely trusted and adding the necessary permissions to the policy
* is prohibitively cumbersome.
*
* @see java.security.Permission
* @see java.security.AccessController
* @see java.security.Permissions
* @see java.security.PermissionCollection
* @see java.lang.SecurityManager
*
*
* @author Roland Schemers
*
* @serial exclude
*/
public final class AllPermission extends Permission {
private static final long serialVersionUID = -2916474571451318075L;
/**
* Creates a new AllPermission object.
*/
public AllPermission() {
super("
*
* @return a new PermissionCollection object suitable for
* storing AllPermissions.
*/
public PermissionCollection newPermissionCollection() {
return new AllPermissionCollection();
}
}
/**
* A AllPermissionCollection stores a collection
* of AllPermission permissions. AllPermission objects
* must be stored in a manner that allows them to be inserted in any
* order, but enable the implies function to evaluate the implies
* method in an efficient (and consistent) manner.
*
* @see java.security.Permission
* @see java.security.Permissions
*
*
* @author Roland Schemers
*
* @serial include
*/
final class AllPermissionCollection
extends PermissionCollection
implements java.io.Serializable
{
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = -4023755556366636806L;
private boolean all_allowed; // true if any all permissions have been added
/**
* Create an empty AllPermissions object.
*
*/
public AllPermissionCollection() {
all_allowed = false;
}
/**
* Adds a permission to the AllPermissions. The key for the hash is
* permission.path.
*
* @param permission the Permission object to add.
*
* @exception IllegalArgumentException - if the permission is not a
* AllPermission
*
* @exception SecurityException - if this AllPermissionCollection object
* has been marked readonly
*/
public void add(Permission permission) {
if (! (permission instanceof AllPermission))
throw new IllegalArgumentException("invalid permission: "+
permission);
if (isReadOnly())
throw new SecurityException("attempt to add a Permission to a readonly PermissionCollection");
all_allowed = true; // No sync; staleness OK
}
/**
* Check and see if this set of permissions implies the permissions
* expressed in "permission".
*
* @param permission the Permission object to compare
*
* @return always returns true.
*/
public boolean implies(Permission permission) {
return all_allowed; // No sync; staleness OK
}
/**
* Returns an enumeration of all the AllPermission objects in the
* container.
*
* @return an enumeration of all the AllPermission objects.
*/
public Enumeration While callers may invoke {@code login} directly,
* the provider may also invoke {@code login} on behalf of callers
* if it determines that a login must be performed
* prior to certain operations.
*
* @since 1.5
*/
public abstract class AuthProvider extends Provider {
private static final long serialVersionUID = 4197859053084546461L;
/**
* Constructs a provider with the specified name, version number,
* and information.
*
* @param name the provider name.
* @param version the provider version number.
* @param info a description of the provider and its services.
*/
protected AuthProvider(String name, double version, String info) {
super(name, version, info);
}
/**
* Log in to this provider.
*
* The provider relies on a {@code CallbackHandler}
* to obtain authentication information from the caller
* (a PIN, for example). If the caller passes a {@code null}
* handler to this method, the provider uses the handler set in the
* {@code setCallbackHandler} method.
* If no handler was set in that method, the provider queries the
* auth.login.defaultCallbackHandler security property
* for the fully qualified class name of a default handler implementation.
* If the security property is not set,
* the provider is assumed to have alternative means
* for obtaining authentication information.
*
* @param subject the {@code Subject} which may contain
* principals/credentials used for authentication,
* or may be populated with additional principals/credentials
* after successful authentication has completed.
* This parameter may be {@code null}.
* @param handler the {@code CallbackHandler} used by
* this provider to obtain authentication information
* from the caller, which may be {@code null}
*
* @exception LoginException if the login operation fails
* @exception SecurityException if the caller does not pass a
* security check for
* {@code SecurityPermission("authProvider.name")},
* where {@code name} is the value returned by
* this provider's {@code getName} method
*/
public abstract void login(Subject subject, CallbackHandler handler)
throws LoginException;
/**
* Log out from this provider.
*
* @exception LoginException if the logout operation fails
* @exception SecurityException if the caller does not pass a
* security check for
* {@code SecurityPermission("authProvider.name")},
* where {@code name} is the value returned by
* this provider's {@code getName} method
*/
public abstract void logout() throws LoginException;
/**
* Set a {@code CallbackHandler}.
*
* The provider uses this handler if one is not passed to the
* {@code login} method. The provider also uses this handler
* if it invokes {@code login} on behalf of callers.
* In either case if a handler is not set via this method,
* the provider queries the
* auth.login.defaultCallbackHandler security property
* for the fully qualified class name of a default handler implementation.
* If the security property is not set,
* the provider is assumed to have alternative means
* for obtaining authentication information.
*
* @param handler a {@code CallbackHandler} for obtaining
* authentication information, which may be {@code null}
*
* @exception SecurityException if the caller does not pass a
* security check for
* {@code SecurityPermission("authProvider.name")},
* where {@code name} is the value returned by
* this provider's {@code getName} method
*/
public abstract void setCallbackHandler(CallbackHandler handler);
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 18383
Content-Disposition: inline; filename="BasicPermission.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "89cc2f921524934d96b40f05b96ef1bc1e7621f1"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Collections;
import java.io.ObjectStreamField;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
/**
* The BasicPermission class extends the Permission class, and
* can be used as the base class for permissions that want to
* follow the same naming convention as BasicPermission.
*
* The name for a BasicPermission is the name of the given permission
* (for example, "exit",
* "setFactory", "print.queueJob", etc). The naming
* convention follows the hierarchical property naming convention.
* An asterisk may appear by itself, or if immediately preceded by a "."
* may appear at the end of the name, to signify a wildcard match.
* For example, "*" and "java.*" signify a wildcard match, while "*java", "a*b",
* and "java*" do not.
*
* The action string (inherited from Permission) is unused.
* Thus, BasicPermission is commonly used as the base class for
* "named" permissions
* (ones that contain a name but no actions list; you either have the
* named permission or you don't.)
* Subclasses may implement actions on top of BasicPermission,
* if desired.
*
* @see java.security.Permission
* @see java.security.Permissions
* @see java.security.PermissionCollection
* @see java.lang.SecurityManager
*
* @author Marianne Mueller
* @author Roland Schemers
*/
public abstract class BasicPermission extends Permission
implements java.io.Serializable
{
private static final long serialVersionUID = 6279438298436773498L;
// does this permission have a wildcard at the end?
private transient boolean wildcard;
// the name without the wildcard on the end
private transient String path;
// is this permission the old-style exitVM permission (pre JDK 1.6)?
private transient boolean exitVM;
/**
* initialize a BasicPermission object. Common to all constructors.
*/
private void init(String name) {
if (name == null)
throw new NullPointerException("name can't be null");
int len = name.length();
if (len == 0) {
throw new IllegalArgumentException("name can't be empty");
}
char last = name.charAt(len - 1);
// Is wildcard or ends with ".*"?
if (last == '*' && (len == 1 || name.charAt(len - 2) == '.')) {
wildcard = true;
if (len == 1) {
path = "";
} else {
path = name.substring(0, len - 1);
}
} else {
if (name.equals("exitVM")) {
wildcard = true;
path = "exitVM.";
exitVM = true;
} else {
path = name;
}
}
}
/**
* Creates a new BasicPermission with the specified name.
* Name is the symbolic name of the permission, such as
* "setFactory",
* "print.queueJob", or "topLevelWindow", etc.
*
* @param name the name of the BasicPermission.
*
* @throws NullPointerException if {@code name} is {@code null}.
* @throws IllegalArgumentException if {@code name} is empty.
*/
public BasicPermission(String name) {
super(name);
init(name);
}
/**
* Creates a new BasicPermission object with the specified name.
* The name is the symbolic name of the BasicPermission, and the
* actions String is currently unused.
*
* @param name the name of the BasicPermission.
* @param actions ignored.
*
* @throws NullPointerException if {@code name} is {@code null}.
* @throws IllegalArgumentException if {@code name} is empty.
*/
public BasicPermission(String name, String actions) {
super(name);
init(name);
}
/**
* Checks if the specified permission is "implied" by
* this object.
*
* More specifically, this method returns true if:
*
* @param obj the object we are testing for equality with this object.
* @return true if obj's class is the same as this object's class
* and has the same name as this BasicPermission object, false otherwise.
*/
public boolean equals(Object obj) {
if (obj == this)
return true;
if ((obj == null) || (obj.getClass() != getClass()))
return false;
BasicPermission bp = (BasicPermission) obj;
return getName().equals(bp.getName());
}
/**
* Returns the hash code value for this object.
* The hash code used is the hash code of the name, that is,
* {@code getName().hashCode()}, where {@code getName} is
* from the Permission superclass.
*
* @return a hash code value for this object.
*/
public int hashCode() {
return this.getName().hashCode();
}
/**
* Returns the canonical string representation of the actions,
* which currently is the empty string "", since there are no actions for
* a BasicPermission.
*
* @return the empty string "".
*/
public String getActions() {
return "";
}
/**
* Returns a new PermissionCollection object for storing BasicPermission
* objects.
*
* BasicPermission objects must be stored in a manner that allows them
* to be inserted in any order, but that also enables the
* PermissionCollection {@code implies} method
* to be implemented in an efficient (and consistent) manner.
*
* @return a new PermissionCollection object suitable for
* storing BasicPermissions.
*/
public PermissionCollection newPermissionCollection() {
return new BasicPermissionCollection(this.getClass());
}
/**
* readObject is called to restore the state of the BasicPermission from
* a stream.
*/
private void readObject(ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
// init is called to initialize the rest of the values.
init(getName());
}
/**
* Returns the canonical name of this BasicPermission.
* All internal invocations of getName should invoke this method, so
* that the pre-JDK 1.6 "exitVM" and current "exitVM.*" permission are
* equivalent in equals/hashCode methods.
*
* @return the canonical name of this BasicPermission.
*/
final String getCanonicalName() {
return exitVM ? "exitVM.*" : getName();
}
}
/**
* A BasicPermissionCollection stores a collection
* of BasicPermission permissions. BasicPermission objects
* must be stored in a manner that allows them to be inserted in any
* order, but enable the implies function to evaluate the implies
* method in an efficient (and consistent) manner.
*
* A BasicPermissionCollection handles comparing a permission like "a.b.c.d.e"
* with a Permission such as "a.b.*", or "*".
*
* @see java.security.Permission
* @see java.security.Permissions
*
*
* @author Roland Schemers
*
* @serial include
*/
final class BasicPermissionCollection
extends PermissionCollection
implements java.io.Serializable
{
private static final long serialVersionUID = 739301742472979399L;
/**
* Key is name, value is permission. All permission objects in
* collection must be of the same type.
* Not serialized; see serialization section at end of class.
*/
private transient Map This is an interface of abstract methods for managing a
* variety of identity certificates.
* An identity certificate is a guarantee by a principal that
* a public key is that of another principal. (A principal represents
* an entity such as an individual user, a group, or a corporation.)
*
* In particular, this interface is intended to be a common
* abstraction for constructs that have different formats but
* important common uses. For example, different types of
* certificates, such as X.509 certificates and PGP certificates,
* share general certificate functionality (the need to encode and
* decode certificates) and some types of information, such as a
* public key, the principal whose key it is, and the guarantor
* guaranteeing that the public key is that of the specified
* principal. So an implementation of X.509 certificates and an
* implementation of PGP certificates can both utilize the Certificate
* interface, even though their formats and additional types and
* amounts of information stored are different.
*
* Important: This interface is useful for cataloging and
* grouping objects sharing certain common uses. It does not have any
* semantics of its own. In particular, a Certificate object does not
* make any statement as to the validity of the binding. It is
* the duty of the application implementing this interface to verify
* the certificate and satisfy itself of its validity.
*
* @author Benjamin Renaud
* @deprecated A new certificate handling package is created in the Java platform.
* This Certificate interface is entirely deprecated and
* is here to allow for a smooth transition to the new
* package.
* @see java.security.cert.Certificate
*/
@Deprecated
public interface Certificate {
/**
* Returns the guarantor of the certificate, that is, the principal
* guaranteeing that the public key associated with this certificate
* is that of the principal associated with this certificate. For X.509
* certificates, the guarantor will typically be a Certificate Authority
* (such as the United States Postal Service or Verisign, Inc.).
*
* @return the guarantor which guaranteed the principal-key
* binding.
*/
public abstract Principal getGuarantor();
/**
* Returns the principal of the principal-key pair being guaranteed by
* the guarantor.
*
* @return the principal to which this certificate is bound.
*/
public abstract Principal getPrincipal();
/**
* Returns the key of the principal-key pair being guaranteed by
* the guarantor.
*
* @return the public key that this certificate certifies belongs
* to a particular principal.
*/
public abstract PublicKey getPublicKey();
/**
* Encodes the certificate to an output stream in a format that can
* be decoded by the {@code decode} method.
*
* @param stream the output stream to which to encode the
* certificate.
*
* @exception KeyException if the certificate is not
* properly initialized, or data is missing, etc.
*
* @exception IOException if a stream exception occurs while
* trying to output the encoded certificate to the output stream.
*
* @see #decode
* @see #getFormat
*/
public abstract void encode(OutputStream stream)
throws KeyException, IOException;
/**
* Decodes a certificate from an input stream. The format should be
* that returned by {@code getFormat} and produced by
* {@code encode}.
*
* @param stream the input stream from which to fetch the data
* being decoded.
*
* @exception KeyException if the certificate is not properly initialized,
* or data is missing, etc.
*
* @exception IOException if an exception occurs while trying to input
* the encoded certificate from the input stream.
*
* @see #encode
* @see #getFormat
*/
public abstract void decode(InputStream stream)
throws KeyException, IOException;
/**
* Returns the name of the coding format. This is used as a hint to find
* an appropriate parser. It could be "X.509", "PGP", etc. This is
* the format produced and understood by the {@code encode}
* and {@code decode} methods.
*
* @return the name of the coding format.
*/
public abstract String getFormat();
/**
* Returns a string that represents the contents of the certificate.
*
* @param detailed whether or not to give detailed information
* about the certificate
*
* @return a string representing the contents of the certificate
*/
public String toString(boolean detailed);
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 5270
Content-Disposition: inline; filename="CodeSigner.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "37c12b153b3d8d06097c397c9f12ce80e420cef4"
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.io.*;
import java.security.cert.CertPath;
/**
* This class encapsulates information about a code signer.
* It is immutable.
*
* @since 1.5
* @author Vincent Ryan
*/
public final class CodeSigner implements Serializable {
private static final long serialVersionUID = 6819288105193937581L;
/**
* The signer's certificate path.
*
* @serial
*/
private CertPath signerCertPath;
/*
* The signature timestamp.
*
* @serial
*/
private Timestamp timestamp;
/*
* Hash code for this code signer.
*/
private transient int myhash = -1;
/**
* Constructs a CodeSigner object.
*
* @param signerCertPath The signer's certificate path.
* It must not be {@code null}.
* @param timestamp A signature timestamp.
* If {@code null} then no timestamp was generated
* for the signature.
* @throws NullPointerException if {@code signerCertPath} is
* {@code null}.
*/
public CodeSigner(CertPath signerCertPath, Timestamp timestamp) {
if (signerCertPath == null) {
throw new NullPointerException();
}
this.signerCertPath = signerCertPath;
this.timestamp = timestamp;
}
/**
* Returns the signer's certificate path.
*
* @return A certificate path.
*/
public CertPath getSignerCertPath() {
return signerCertPath;
}
/**
* Returns the signature timestamp.
*
* @return The timestamp or {@code null} if none is present.
*/
public Timestamp getTimestamp() {
return timestamp;
}
/**
* Returns the hash code value for this code signer.
* The hash code is generated using the signer's certificate path and the
* timestamp, if present.
*
* @return a hash code value for this code signer.
*/
public int hashCode() {
if (myhash == -1) {
if (timestamp == null) {
myhash = signerCertPath.hashCode();
} else {
myhash = signerCertPath.hashCode() + timestamp.hashCode();
}
}
return myhash;
}
/**
* Tests for equality between the specified object and this
* code signer. Two code signers are considered equal if their
* signer certificate paths are equal and if their timestamps are equal,
* if present in both.
*
* @param obj the object to test for equality with this object.
*
* @return true if the objects are considered equal, false otherwise.
*/
public boolean equals(Object obj) {
if (obj == null || (!(obj instanceof CodeSigner))) {
return false;
}
CodeSigner that = (CodeSigner)obj;
if (this == that) {
return true;
}
Timestamp thatTimestamp = that.getTimestamp();
if (timestamp == null) {
if (thatTimestamp != null) {
return false;
}
} else {
if (thatTimestamp == null ||
(! timestamp.equals(thatTimestamp))) {
return false;
}
}
return signerCertPath.equals(that.getSignerCertPath());
}
/**
* Returns a string describing this code signer.
*
* @return A string comprising the signer's certificate and a timestamp,
* if present.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("(");
sb.append("Signer: " + signerCertPath.getCertificates().get(0));
if (timestamp != null) {
sb.append("timestamp: " + timestamp);
}
sb.append(")");
return sb.toString();
}
// Explicitly reset hash code value to -1
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
ois.defaultReadObject();
myhash = -1;
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 23248
Content-Disposition: inline; filename="CodeSource.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "e2ca471360ad9f5826c5a668a1fac71e32561128"
/*
* Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.net.URL;
import java.net.SocketPermission;
import java.util.ArrayList;
import java.util.List;
import java.util.Hashtable;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.cert.*;
import sun.misc.IOUtils;
/**
*
* This class extends the concept of a codebase to
* encapsulate not only the location (URL) but also the certificate chains
* that were used to verify signed code originating from that location.
*
* @author Li Gong
* @author Roland Schemers
*/
public class CodeSource implements java.io.Serializable {
private static final long serialVersionUID = 4977541819976013951L;
/**
* The code location.
*
* @serial
*/
private URL location;
/*
* The code signers.
*/
private transient CodeSigner[] signers = null;
/*
* The code signers. Certificate chains are concatenated.
*/
private transient java.security.cert.Certificate certs[] = null;
// cached SocketPermission used for matchLocation
private transient SocketPermission sp;
// for generating cert paths
private transient CertificateFactory factory = null;
/**
* Constructs a CodeSource and associates it with the specified
* location and set of certificates.
*
* @param url the location (URL).
*
* @param certs the certificate(s). It may be null. The contents of the
* array are copied to protect against subsequent modification.
*/
public CodeSource(URL url, java.security.cert.Certificate certs[]) {
this.location = url;
// Copy the supplied certs
if (certs != null) {
this.certs = certs.clone();
}
}
/**
* Constructs a CodeSource and associates it with the specified
* location and set of code signers.
*
* @param url the location (URL).
* @param signers the code signers. It may be null. The contents of the
* array are copied to protect against subsequent modification.
*
* @since 1.5
*/
public CodeSource(URL url, CodeSigner[] signers) {
this.location = url;
// Copy the supplied signers
if (signers != null) {
this.signers = signers.clone();
}
}
/**
* Returns the hash code value for this object.
*
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
if (location != null)
return location.hashCode();
else
return 0;
}
/**
* Tests for equality between the specified object and this
* object. Two CodeSource objects are considered equal if their
* locations are of identical value and if their signer certificate
* chains are of identical value. It is not required that
* the certificate chains be in the same order.
*
* @param obj the object to test for equality with this object.
*
* @return true if the objects are considered equal, false otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj == this)
return true;
// objects types must be equal
if (!(obj instanceof CodeSource))
return false;
CodeSource cs = (CodeSource) obj;
// URLs must match
if (location == null) {
// if location is null, then cs.location must be null as well
if (cs.location != null) return false;
} else {
// if location is not null, then it must equal cs.location
if (!location.equals(cs.location)) return false;
}
// certs must match
return matchCerts(cs, true);
}
/**
* Returns the location associated with this CodeSource.
*
* @return the location (URL).
*/
public final URL getLocation() {
/* since URL is practically immutable, returning itself is not
a security problem */
return this.location;
}
/**
* Returns the certificates associated with this CodeSource.
*
* If this CodeSource object was created using the
* {@link #CodeSource(URL url, CodeSigner[] signers)}
* constructor then its certificate chains are extracted and used to
* create an array of Certificate objects. Each signer certificate is
* followed by its supporting certificate chain (which may be empty).
* Each signer certificate and its supporting certificate chain is ordered
* bottom-to-top (i.e., with the signer certificate first and the (root)
* certificate authority last).
*
* @return A copy of the certificates array, or null if there is none.
*/
public final java.security.cert.Certificate[] getCertificates() {
if (certs != null) {
return certs.clone();
} else if (signers != null) {
// Convert the code signers to certs
ArrayList
* If this CodeSource object was created using the
* {@link #CodeSource(URL url, java.security.cert.Certificate[] certs)}
* constructor then its certificate chains are extracted and used to
* create an array of CodeSigner objects. Note that only X.509 certificates
* are examined - all other certificate types are ignored.
*
* @return A copy of the code signer array, or null if there is none.
*
* @since 1.5
*/
public final CodeSigner[] getCodeSigners() {
if (signers != null) {
return signers.clone();
} else if (certs != null) {
// Convert the certs to code signers
signers = convertCertArrayToSignerArray(certs);
return signers.clone();
} else {
return null;
}
}
/**
* Returns true if this CodeSource object "implies" the specified CodeSource.
*
* More specifically, this method makes the following checks.
* If any fail, it returns false. If they all succeed, it returns true.
*
* For example, the codesource objects with the following locations
* and null certificates all imply
* the codesource with the location "http://java.sun.com/classes/foo.jar"
* and null certificates:
* To complete the message digest computation, call one of the
* {@code digest} methods on the associated message
* digest after your calls to one of this digest input stream's
* {@link #read() read} methods.
*
* It is possible to turn this stream on or off (see
* {@link #on(boolean) on}). When it is on, a call to one of the
* {@code read} methods
* results in an update on the message digest. But when it is off,
* the message digest is not updated. The default is for the stream
* to be on.
*
* Note that digest objects can compute only one digest (see
* {@link MessageDigest}),
* so that in order to compute intermediate digests, a caller should
* retain a handle onto the digest object, and clone it for each
* digest to be computed, leaving the orginal digest untouched.
*
* @see MessageDigest
*
* @see DigestOutputStream
*
* @author Benjamin Renaud
*/
public class DigestInputStream extends FilterInputStream {
/* NOTE: This should be made a generic UpdaterInputStream */
/* Are we on or off? */
private boolean on = true;
/**
* The message digest associated with this stream.
*/
protected MessageDigest digest;
/**
* Creates a digest input stream, using the specified input stream
* and message digest.
*
* @param stream the input stream.
*
* @param digest the message digest to associate with this stream.
*/
public DigestInputStream(InputStream stream, MessageDigest digest) {
super(stream);
setMessageDigest(digest);
}
/**
* Returns the message digest associated with this stream.
*
* @return the message digest associated with this stream.
* @see #setMessageDigest(java.security.MessageDigest)
*/
public MessageDigest getMessageDigest() {
return digest;
}
/**
* Associates the specified message digest with this stream.
*
* @param digest the message digest to be associated with this stream.
* @see #getMessageDigest()
*/
public void setMessageDigest(MessageDigest digest) {
this.digest = digest;
}
/**
* Reads a byte, and updates the message digest (if the digest
* function is on). That is, this method reads a byte from the
* input stream, blocking until the byte is actually read. If the
* digest function is on (see {@link #on(boolean) on}), this method
* will then call {@code update} on the message digest associated
* with this stream, passing it the byte read.
*
* @return the byte read.
*
* @exception IOException if an I/O error occurs.
*
* @see MessageDigest#update(byte)
*/
public int read() throws IOException {
int ch = in.read();
if (on && ch != -1) {
digest.update((byte)ch);
}
return ch;
}
/**
* Reads into a byte array, and updates the message digest (if the
* digest function is on). That is, this method reads up to
* {@code len} bytes from the input stream into the array
* {@code b}, starting at offset {@code off}. This method
* blocks until the data is actually
* read. If the digest function is on (see
* {@link #on(boolean) on}), this method will then call {@code update}
* on the message digest associated with this stream, passing it
* the data.
*
* @param b the array into which the data is read.
*
* @param off the starting offset into {@code b} of where the
* data should be placed.
*
* @param len the maximum number of bytes to be read from the input
* stream into b, starting at offset {@code off}.
*
* @return the actual number of bytes read. This is less than
* {@code len} if the end of the stream is reached prior to
* reading {@code len} bytes. -1 is returned if no bytes were
* read because the end of the stream had already been reached when
* the call was made.
*
* @exception IOException if an I/O error occurs.
*
* @see MessageDigest#update(byte[], int, int)
*/
public int read(byte[] b, int off, int len) throws IOException {
int result = in.read(b, off, len);
if (on && result != -1) {
digest.update(b, off, result);
}
return result;
}
/**
* Turns the digest function on or off. The default is on. When
* it is on, a call to one of the {@code read} methods results in an
* update on the message digest. But when it is off, the message
* digest is not updated.
*
* @param on true to turn the digest function on, false to turn
* it off.
*/
public void on(boolean on) {
this.on = on;
}
/**
* Prints a string representation of this digest input stream and
* its associated message digest object.
*/
public String toString() {
return "[Digest Input Stream] " + digest.toString();
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 5967
Content-Disposition: inline; filename="DigestOutputStream.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "51db133a5f67279a8c1685f3cefc73428235c827"
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.io.IOException;
import java.io.EOFException;
import java.io.OutputStream;
import java.io.FilterOutputStream;
import java.io.PrintStream;
import java.io.ByteArrayOutputStream;
/**
* A transparent stream that updates the associated message digest using
* the bits going through the stream.
*
* To complete the message digest computation, call one of the
* {@code digest} methods on the associated message
* digest after your calls to one of this digest output stream's
* {@link #write(int) write} methods.
*
* It is possible to turn this stream on or off (see
* {@link #on(boolean) on}). When it is on, a call to one of the
* {@code write} methods results in
* an update on the message digest. But when it is off, the message
* digest is not updated. The default is for the stream to be on.
*
* @see MessageDigest
* @see DigestInputStream
*
* @author Benjamin Renaud
*/
public class DigestOutputStream extends FilterOutputStream {
private boolean on = true;
/**
* The message digest associated with this stream.
*/
protected MessageDigest digest;
/**
* Creates a digest output stream, using the specified output stream
* and message digest.
*
* @param stream the output stream.
*
* @param digest the message digest to associate with this stream.
*/
public DigestOutputStream(OutputStream stream, MessageDigest digest) {
super(stream);
setMessageDigest(digest);
}
/**
* Returns the message digest associated with this stream.
*
* @return the message digest associated with this stream.
* @see #setMessageDigest(java.security.MessageDigest)
*/
public MessageDigest getMessageDigest() {
return digest;
}
/**
* Associates the specified message digest with this stream.
*
* @param digest the message digest to be associated with this stream.
* @see #getMessageDigest()
*/
public void setMessageDigest(MessageDigest digest) {
this.digest = digest;
}
/**
* Updates the message digest (if the digest function is on) using
* the specified byte, and in any case writes the byte
* to the output stream. That is, if the digest function is on
* (see {@link #on(boolean) on}), this method calls
* {@code update} on the message digest associated with this
* stream, passing it the byte {@code b}. This method then
* writes the byte to the output stream, blocking until the byte
* is actually written.
*
* @param b the byte to be used for updating and writing to the
* output stream.
*
* @exception IOException if an I/O error occurs.
*
* @see MessageDigest#update(byte)
*/
public void write(int b) throws IOException {
out.write(b);
if (on) {
digest.update((byte)b);
}
}
/**
* Updates the message digest (if the digest function is on) using
* the specified subarray, and in any case writes the subarray to
* the output stream. That is, if the digest function is on (see
* {@link #on(boolean) on}), this method calls {@code update}
* on the message digest associated with this stream, passing it
* the subarray specifications. This method then writes the subarray
* bytes to the output stream, blocking until the bytes are actually
* written.
*
* @param b the array containing the subarray to be used for updating
* and writing to the output stream.
*
* @param off the offset into {@code b} of the first byte to
* be updated and written.
*
* @param len the number of bytes of data to be updated and written
* from {@code b}, starting at offset {@code off}.
*
* @exception IOException if an I/O error occurs.
*
* @see MessageDigest#update(byte[], int, int)
*/
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
if (on) {
digest.update(b, off, len);
}
}
/**
* Turns the digest function on or off. The default is on. When
* it is on, a call to one of the {@code write} methods results in an
* update on the message digest. But when it is off, the message
* digest is not updated.
*
* @param on true to turn the digest function on, false to turn it
* off.
*/
public void on(boolean on) {
this.on = on;
}
/**
* Prints a string representation of this digest output stream and
* its associated message digest object.
*/
public String toString() {
return "[Digest Output Stream] " + digest.toString();
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 5518
Content-Disposition: inline; filename="DomainCombiner.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "7aadc7e7b2f3135871ff7af78db8813ddf9a9c3c"
/*
* Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* A {@code DomainCombiner} provides a means to dynamically
* update the ProtectionDomains associated with the current
* {@code AccessControlContext}.
*
* A {@code DomainCombiner} is passed as a parameter to the
* appropriate constructor for {@code AccessControlContext}.
* The newly constructed context is then passed to the
* {@code AccessController.doPrivileged(..., context)} method
* to bind the provided context (and associated {@code DomainCombiner})
* with the current execution Thread. Subsequent calls to
* {@code AccessController.getContext} or
* {@code AccessController.checkPermission}
* cause the {@code DomainCombiner.combine} to get invoked.
*
* The combine method takes two arguments. The first argument represents
* an array of ProtectionDomains from the current execution Thread,
* since the most recent call to {@code AccessController.doPrivileged}.
* If no call to doPrivileged was made, then the first argument will contain
* all the ProtectionDomains from the current execution Thread.
* The second argument represents an array of inherited ProtectionDomains,
* which may be {@code null}. ProtectionDomains may be inherited
* from a parent Thread, or from a privileged context. If no call to
* doPrivileged was made, then the second argument will contain the
* ProtectionDomains inherited from the parent Thread. If one or more calls
* to doPrivileged were made, and the most recent call was to
* doPrivileged(action, context), then the second argument will contain the
* ProtectionDomains from the privileged context. If the most recent call
* was to doPrivileged(action), then there is no privileged context,
* and the second argument will be {@code null}.
*
* The {@code combine} method investigates the two input arrays
* of ProtectionDomains and returns a single array containing the updated
* ProtectionDomains. In the simplest case, the {@code combine}
* method merges the two stacks into one. In more complex cases,
* the {@code combine} method returns a modified
* stack of ProtectionDomains. The modification may have added new
* ProtectionDomains, removed certain ProtectionDomains, or simply
* updated existing ProtectionDomains. Re-ordering and other optimizations
* to the ProtectionDomains are also permitted. Typically the
* {@code combine} method bases its updates on the information
* encapsulated in the {@code DomainCombiner}.
*
* After the {@code AccessController.getContext} method
* receives the combined stack of ProtectionDomains back from
* the {@code DomainCombiner}, it returns a new
* AccessControlContext that has both the combined ProtectionDomains
* as well as the {@code DomainCombiner}.
*
* @see AccessController
* @see AccessControlContext
* @since 1.3
*/
public interface DomainCombiner {
/**
* Modify or update the provided ProtectionDomains.
* ProtectionDomains may be added to or removed from the given
* ProtectionDomains. The ProtectionDomains may be re-ordered.
* Individual ProtectionDomains may be modified (with a new
* set of Permissions, for example).
*
*
*
* @param currentDomains the ProtectionDomains associated with the
* current execution Thread, up to the most recent
* privileged {@code ProtectionDomain}.
* The ProtectionDomains are are listed in order of execution,
* with the most recently executing {@code ProtectionDomain}
* residing at the beginning of the array. This parameter may
* be {@code null} if the current execution Thread
* has no associated ProtectionDomains.
*
* @param assignedDomains an array of inherited ProtectionDomains.
* ProtectionDomains may be inherited from a parent Thread,
* or from a privileged {@code AccessControlContext}.
* This parameter may be {@code null}
* if there are no inherited ProtectionDomains.
*
* @return a new array consisting of the updated ProtectionDomains,
* or {@code null}.
*/
ProtectionDomain[] combine(ProtectionDomain[] currentDomains,
ProtectionDomain[] assignedDomains);
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 6879
Content-Disposition: inline; filename="DomainLoadStoreParameter.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "bc9697597e50633c0801777a957831e1d8709f06"
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.net.URI;
import java.util.*;
import static java.security.KeyStore.*;
/**
* Configuration data that specifies the keystores in a keystore domain.
* A keystore domain is a collection of keystores that are presented as a
* single logical keystore. The configuration data is used during
* {@code KeyStore}
* {@link KeyStore#load(KeyStore.LoadStoreParameter) load} and
* {@link KeyStore#store(KeyStore.LoadStoreParameter) store} operations.
*
* The following syntax is supported for configuration data:
*
* To ensure that keystore entries are uniquely identified, each
* entry's alias is prefixed by its {@code keystoreName} followed
* by the entry name separator and each {@code keystoreName} must be
* unique within its domain. Entry name prefixes are omitted when
* storing a keystore.
*
* Properties are context-sensitive: properties that apply to
* all the keystores in a domain are located in the domain clause,
* and properties that apply only to a specific keystore are located
* in that keystore's clause.
* Unless otherwise specified, a property in a keystore clause overrides
* a property of the same name in the domain clause. All property names
* are case-insensitive. The following properties are supported:
*
* For example, configuration data for a simple keystore domain
* comprising three keystores is shown below:
* This interface represents a guard, which is an object that is used
* to protect access to another object.
*
* This interface contains a single method, {@code checkGuard},
* with a single {@code object} argument. {@code checkGuard} is
* invoked (by the GuardedObject {@code getObject} method)
* to determine whether or not to allow access to the object.
*
* @see GuardedObject
*
* @author Roland Schemers
* @author Li Gong
*/
public interface Guard {
/**
* Determines whether or not to allow access to the guarded object
* {@code object}. Returns silently if access is allowed.
* Otherwise, throws a SecurityException.
*
* @param object the object being protected by the guard.
*
* @exception SecurityException if access is denied.
*
*/
void checkGuard(Object object) throws SecurityException;
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 3320
Content-Disposition: inline; filename="GuardedObject.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "a275ddf043ee593eaf04a311b8682676e0993ff1"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* A GuardedObject is an object that is used to protect access to
* another object.
*
* A GuardedObject encapsulates a target object and a Guard object,
* such that access to the target object is possible
* only if the Guard object allows it.
* Once an object is encapsulated by a GuardedObject,
* access to that object is controlled by the {@code getObject}
* method, which invokes the
* {@code checkGuard} method on the Guard object that is
* guarding access. If access is not allowed,
* an exception is thrown.
*
* @see Guard
* @see Permission
*
* @author Roland Schemers
* @author Li Gong
*/
public class GuardedObject implements java.io.Serializable {
private static final long serialVersionUID = -5240450096227834308L;
private Object object; // the object we are guarding
private Guard guard; // the guard
/**
* Constructs a GuardedObject using the specified object and guard.
* If the Guard object is null, then no restrictions will
* be placed on who can access the object.
*
* @param object the object to be guarded.
*
* @param guard the Guard object that guards access to the object.
*/
public GuardedObject(Object object, Guard guard)
{
this.guard = guard;
this.object = object;
}
/**
* Retrieves the guarded object, or throws an exception if access
* to the guarded object is denied by the guard.
*
* @return the guarded object.
*
* @exception SecurityException if access to the guarded object is
* denied.
*/
public Object getObject()
throws SecurityException
{
if (guard != null)
guard.checkGuard(object);
return object;
}
/**
* Writes this object out to a stream (i.e., serializes it).
* We check the guard if there is one.
*/
private void writeObject(java.io.ObjectOutputStream oos)
throws java.io.IOException
{
if (guard != null)
guard.checkGuard(object);
oos.defaultWriteObject();
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 15805
Content-Disposition: inline; filename="Identity.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "6eada6d9fd798e30c20c0a4027365671aeac2198"
/*
* Copyright (c) 1996, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.io.Serializable;
import java.util.*;
/**
* This class represents identities: real-world objects such as people,
* companies or organizations whose identities can be authenticated using
* their public keys. Identities may also be more abstract (or concrete)
* constructs, such as daemon threads or smart cards.
*
* All Identity objects have a name and a public key. Names are
* immutable. Identities may also be scoped. That is, if an Identity is
* specified to have a particular scope, then the name and public
* key of the Identity are unique within that scope.
*
* An Identity also has a set of certificates (all certifying its own
* public key). The Principal names specified in these certificates need
* not be the same, only the key.
*
* An Identity can be subclassed, to include postal and email addresses,
* telephone numbers, images of faces and logos, and so on.
*
* @see IdentityScope
* @see Signer
* @see Principal
*
* @author Benjamin Renaud
* @deprecated This class is no longer used. Its functionality has been
* replaced by {@code java.security.KeyStore}, the
* {@code java.security.cert} package, and
* {@code java.security.Principal}.
*/
@Deprecated
public abstract class Identity implements Principal, Serializable {
/** use serialVersionUID from JDK 1.1.x for interoperability */
private static final long serialVersionUID = 3609922007826600659L;
/**
* The name for this identity.
*
* @serial
*/
private String name;
/**
* The public key for this identity.
*
* @serial
*/
private PublicKey publicKey;
/**
* Generic, descriptive information about the identity.
*
* @serial
*/
String info = "No further information available.";
/**
* The scope of the identity.
*
* @serial
*/
IdentityScope scope;
/**
* The certificates for this identity.
*
* @serial
*/
Vector First, if there is a security manager, its {@code checkSecurityAccess}
* method is called with {@code "setIdentityPublicKey"}
* as its argument to see if it's ok to set the public key.
*
* @param key the public key for this identity.
*
* @exception KeyManagementException if another identity in the
* identity's scope has the same public key, or if another exception occurs.
*
* @exception SecurityException if a security manager exists and its
* {@code checkSecurityAccess} method doesn't allow
* setting the public key.
*
* @see #getPublicKey
* @see SecurityManager#checkSecurityAccess
*/
/* Should we throw an exception if this is already set? */
public void setPublicKey(PublicKey key) throws KeyManagementException {
check("setIdentityPublicKey");
this.publicKey = key;
certificates = new Vector First, if there is a security manager, its {@code checkSecurityAccess}
* method is called with {@code "setIdentityInfo"}
* as its argument to see if it's ok to specify the information string.
*
* @param info the information string.
*
* @exception SecurityException if a security manager exists and its
* {@code checkSecurityAccess} method doesn't allow
* setting the information string.
*
* @see #getInfo
* @see SecurityManager#checkSecurityAccess
*/
public void setInfo(String info) {
check("setIdentityInfo");
this.info = info;
}
/**
* Returns general information previously specified for this identity.
*
* @return general information about this identity.
*
* @see #setInfo
*/
public String getInfo() {
return info;
}
/**
* Adds a certificate for this identity. If the identity has a public
* key, the public key in the certificate must be the same, and if
* the identity does not have a public key, the identity's
* public key is set to be that specified in the certificate.
*
* First, if there is a security manager, its {@code checkSecurityAccess}
* method is called with {@code "addIdentityCertificate"}
* as its argument to see if it's ok to add a certificate.
*
* @param certificate the certificate to be added.
*
* @exception KeyManagementException if the certificate is not valid,
* if the public key in the certificate being added conflicts with
* this identity's public key, or if another exception occurs.
*
* @exception SecurityException if a security manager exists and its
* {@code checkSecurityAccess} method doesn't allow
* adding a certificate.
*
* @see SecurityManager#checkSecurityAccess
*/
public void addCertificate(Certificate certificate)
throws KeyManagementException {
check("addIdentityCertificate");
if (certificates == null) {
certificates = new Vector First, if there is a security manager, its {@code checkSecurityAccess}
* method is called with {@code "removeIdentityCertificate"}
* as its argument to see if it's ok to remove a certificate.
*
* @param certificate the certificate to be removed.
*
* @exception KeyManagementException if the certificate is
* missing, or if another exception occurs.
*
* @exception SecurityException if a security manager exists and its
* {@code checkSecurityAccess} method doesn't allow
* removing a certificate.
*
* @see SecurityManager#checkSecurityAccess
*/
public void removeCertificate(Certificate certificate)
throws KeyManagementException {
check("removeIdentityCertificate");
if (certificates != null) {
certificates.removeElement(certificate);
}
}
/**
* Returns a copy of all the certificates for this identity.
*
* @return a copy of all the certificates for this identity.
*/
public Certificate[] certificates() {
if (certificates == null) {
return new Certificate[0];
}
int len = certificates.size();
Certificate[] certs = new Certificate[len];
certificates.copyInto(certs);
return certs;
}
/**
* Tests for equality between the specified object and this identity.
* This first tests to see if the entities actually refer to the same
* object, in which case it returns true. Next, it checks to see if
* the entities have the same name and the same scope. If they do,
* the method returns true. Otherwise, it calls
* {@link #identityEquals(Identity) identityEquals}, which subclasses should
* override.
*
* @param identity the object to test for equality with this identity.
*
* @return true if the objects are considered equal, false otherwise.
*
* @see #identityEquals
*/
public final boolean equals(Object identity) {
if (identity == this) {
return true;
}
if (identity instanceof Identity) {
Identity i = (Identity)identity;
if (this.fullName().equals(i.fullName())) {
return true;
} else {
return identityEquals(i);
}
}
return false;
}
/**
* Tests for equality between the specified identity and this identity.
* This method should be overriden by subclasses to test for equality.
* The default behavior is to return true if the names and public keys
* are equal.
*
* @param identity the identity to test for equality with this identity.
*
* @return true if the identities are considered equal, false
* otherwise.
*
* @see #equals
*/
protected boolean identityEquals(Identity identity) {
if (!name.equalsIgnoreCase(identity.name))
return false;
if ((publicKey == null) ^ (identity.publicKey == null))
return false;
if (publicKey != null && identity.publicKey != null)
if (!publicKey.equals(identity.publicKey))
return false;
return true;
}
/**
* Returns a parsable name for identity: identityName.scopeName
*/
String fullName() {
String parsable = name;
if (scope != null) {
parsable += "." + scope.getName();
}
return parsable;
}
/**
* Returns a short string describing this identity, telling its
* name and its scope (if any).
*
* First, if there is a security manager, its {@code checkSecurityAccess}
* method is called with {@code "printIdentity"}
* as its argument to see if it's ok to return the string.
*
* @return information about this identity, such as its name and the
* name of its scope (if any).
*
* @exception SecurityException if a security manager exists and its
* {@code checkSecurityAccess} method doesn't allow
* returning a string describing this identity.
*
* @see SecurityManager#checkSecurityAccess
*/
public String toString() {
check("printIdentity");
String printable = name;
if (scope != null) {
printable += "[" + scope.getName() + "]";
}
return printable;
}
/**
* Returns a string representation of this identity, with
* optionally more details than that provided by the
* {@code toString} method without any arguments.
*
* First, if there is a security manager, its {@code checkSecurityAccess}
* method is called with {@code "printIdentity"}
* as its argument to see if it's ok to return the string.
*
* @param detailed whether or not to provide detailed information.
*
* @return information about this identity. If {@code detailed}
* is true, then this method returns more information than that
* provided by the {@code toString} method without any arguments.
*
* @exception SecurityException if a security manager exists and its
* {@code checkSecurityAccess} method doesn't allow
* returning a string describing this identity.
*
* @see #toString
* @see SecurityManager#checkSecurityAccess
*/
public String toString(boolean detailed) {
String out = toString();
if (detailed) {
out += "\n";
out += printKeys();
out += "\n" + printCertificates();
if (info != null) {
out += "\n\t" + info;
} else {
out += "\n\tno additional information available.";
}
}
return out;
}
String printKeys() {
String key = "";
if (publicKey != null) {
key = "\tpublic key initialized";
} else {
key = "\tno public key";
}
return key;
}
String printCertificates() {
String out = "";
if (certificates == null) {
return "\tno certificates";
} else {
out += "\tcertificates: \n";
int i = 1;
for (Certificate cert : certificates) {
out += "\tcertificate " + i++ +
"\tfor : " + cert.getPrincipal() + "\n";
out += "\t\t\tfrom : " +
cert.getGuarantor() + "\n";
}
}
return out;
}
/**
* Returns a hashcode for this identity.
*
* @return a hashcode for this identity.
*/
public int hashCode() {
return name.hashCode();
}
private static void check(String directive) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkSecurityAccess(directive);
}
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 8445
Content-Disposition: inline; filename="IdentityScope.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "7b18387a353c1c9979c9857e0bb5aa7f5f066d2b"
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Properties;
/**
* This class represents a scope for identities. It is an Identity
* itself, and therefore has a name and can have a scope. It can also
* optionally have a public key and associated certificates.
*
* An IdentityScope can contain Identity objects of all kinds, including
* Signers. All types of Identity objects can be retrieved, added, and
* removed using the same methods. Note that it is possible, and in fact
* expected, that different types of identity scopes will
* apply different policies for their various operations on the
* various types of Identities.
*
* There is a one-to-one mapping between keys and identities, and
* there can only be one copy of one key per scope. For example, suppose
* Acme Software, Inc is a software publisher known to a user.
* Suppose it is an Identity, that is, it has a public key, and a set of
* associated certificates. It is named in the scope using the name
* "Acme Software". No other named Identity in the scope has the same
* public key. Of course, none has the same name as well.
*
* @see Identity
* @see Signer
* @see Principal
* @see Key
*
* @author Benjamin Renaud
*
* @deprecated This class is no longer used. Its functionality has been
* replaced by {@code java.security.KeyStore}, the
* {@code java.security.cert} package, and
* {@code java.security.Principal}.
*/
@Deprecated
public abstract
class IdentityScope extends Identity {
private static final long serialVersionUID = -2337346281189773310L;
/* The system's scope */
private static IdentityScope scope;
// initialize the system scope
private static void initializeSystemScope() {
String classname = AccessController.doPrivileged(
new PrivilegedAction First, if there is a security manager, its
* {@code checkSecurityAccess}
* method is called with {@code "setSystemScope"}
* as its argument to see if it's ok to set the identity scope.
*
* @param scope the scope to set.
*
* @exception SecurityException if a security manager exists and its
* {@code checkSecurityAccess} method doesn't allow
* setting the identity scope.
*
* @see #getSystemScope
* @see SecurityManager#checkSecurityAccess
*/
protected static void setSystemScope(IdentityScope scope) {
check("setSystemScope");
IdentityScope.scope = scope;
}
/**
* Returns the number of identities within this identity scope.
*
* @return the number of identities within this identity scope.
*/
public abstract int size();
/**
* Returns the identity in this scope with the specified name (if any).
*
* @param name the name of the identity to be retrieved.
*
* @return the identity named {@code name}, or null if there are
* no identities named {@code name} in this scope.
*/
public abstract Identity getIdentity(String name);
/**
* Retrieves the identity whose name is the same as that of the
* specified principal. (Note: Identity implements Principal.)
*
* @param principal the principal corresponding to the identity
* to be retrieved.
*
* @return the identity whose name is the same as that of the
* principal, or null if there are no identities of the same name
* in this scope.
*/
public Identity getIdentity(Principal principal) {
return getIdentity(principal.getName());
}
/**
* Retrieves the identity with the specified public key.
*
* @param key the public key for the identity to be returned.
*
* @return the identity with the given key, or null if there are
* no identities in this scope with that key.
*/
public abstract Identity getIdentity(PublicKey key);
/**
* Adds an identity to this identity scope.
*
* @param identity the identity to be added.
*
* @exception KeyManagementException if the identity is not
* valid, a name conflict occurs, another identity has the same
* public key as the identity being added, or another exception
* occurs. */
public abstract void addIdentity(Identity identity)
throws KeyManagementException;
/**
* Removes an identity from this identity scope.
*
* @param identity the identity to be removed.
*
* @exception KeyManagementException if the identity is missing,
* or another exception occurs.
*/
public abstract void removeIdentity(Identity identity)
throws KeyManagementException;
/**
* Returns an enumeration of all identities in this identity scope.
*
* @return an enumeration of all identities in this identity scope.
*/
public abstract Enumeration This is the key algorithm for that key. The key algorithm is usually
* an encryption or asymmetric operation algorithm (such as DSA or
* RSA), which will work with those algorithms and with related
* algorithms (such as MD5 with RSA, SHA-1 with RSA, Raw DSA, etc.)
* The name of the algorithm of a key is obtained using the
* {@link #getAlgorithm() getAlgorithm} method.
*
* This is an external encoded form for the key used when a standard
* representation of the key is needed outside the Java Virtual Machine,
* as when transmitting the key to some other party. The key
* is encoded according to a standard format (such as
* X.509 {@code SubjectPublicKeyInfo} or PKCS#8), and
* is returned using the {@link #getEncoded() getEncoded} method.
* Note: The syntax of the ASN.1 type {@code SubjectPublicKeyInfo}
* is defined as follows:
*
* This is the name of the format of the encoded key. It is returned
* by the {@link #getFormat() getFormat} method.
*
* A Key should use KeyRep as its serialized representation.
* Note that a serialized Key may contain sensitive information
* which should not be exposed in untrusted environments. See the
*
* Security Appendix
* of the Serialization Specification for more information.
*
* @see PublicKey
* @see PrivateKey
* @see KeyPair
* @see KeyPairGenerator
* @see KeyFactory
* @see KeyRep
* @see java.security.spec.KeySpec
* @see Identity
* @see Signer
*
* @author Benjamin Renaud
*/
public interface Key extends java.io.Serializable {
// Declare serialVersionUID to be compatible with JDK1.1
/**
* The class fingerprint that is set to indicate
* serialization compatibility with a previous
* version of the class.
*/
static final long serialVersionUID = 6603384152749567654L;
/**
* Returns the standard algorithm name for this key. For
* example, "DSA" would indicate that this key is a DSA key.
* See Appendix A in the
* Java Cryptography Architecture API Specification & Reference
* for information about standard algorithm names.
*
* @return the name of the algorithm associated with this key.
*/
public String getAlgorithm();
/**
* Returns the name of the primary encoding format of this key,
* or null if this key does not support encoding.
* The primary encoding format is
* named in terms of the appropriate ASN.1 data format, if an
* ASN.1 specification for this key exists.
* For example, the name of the ASN.1 data format for public
* keys is SubjectPublicKeyInfo, as
* defined by the X.509 standard; in this case, the returned format is
* {@code "X.509"}. Similarly,
* the name of the ASN.1 data format for private keys is
* PrivateKeyInfo,
* as defined by the PKCS #8 standard; in this case, the returned format is
* {@code "PKCS#8"}.
*
* @return the primary encoding format of the key.
*/
public String getFormat();
/**
* Returns the key in its primary encoding format, or null
* if this key does not support encoding.
*
* @return the encoded key, or null if the key does not support
* encoding.
*/
public byte[] getEncoded();
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 3153
Content-Disposition: inline; filename="KeyException.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "59cdd6f3ab515be6ac0e660827d189b3b4d7fcf5"
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* This is the basic key exception.
*
* @see Key
* @see InvalidKeyException
* @see KeyManagementException
*
* @author Benjamin Renaud
*/
public class KeyException extends GeneralSecurityException {
private static final long serialVersionUID = -7483676942812432108L;
/**
* Constructs a KeyException with no detail message. A detail
* message is a String that describes this particular exception.
*/
public KeyException() {
super();
}
/**
* Constructs a KeyException with the specified detail message.
* A detail message is a String that describes this particular
* exception.
*
* @param msg the detail message.
*/
public KeyException(String msg) {
super(msg);
}
/**
* Creates a {@code KeyException} with the specified
* detail message and cause.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @since 1.5
*/
public KeyException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a {@code KeyException} with the specified cause
* and a detail message of {@code (cause==null ? null : cause.toString())}
* (which typically contains the class and detail message of
* {@code cause}).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @since 1.5
*/
public KeyException(Throwable cause) {
super(cause);
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 17406
Content-Disposition: inline; filename="KeyFactory.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "8e761ff41f727d3311f897d60d4e9b1d42cfe5ba"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.util.*;
import java.security.Provider.Service;
import java.security.spec.KeySpec;
import java.security.spec.InvalidKeySpecException;
import sun.security.util.Debug;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
/**
* Key factories are used to convert keys (opaque
* cryptographic keys of type {@code Key}) into key specifications
* (transparent representations of the underlying key material), and vice
* versa.
*
* Key factories are bi-directional. That is, they allow you to build an
* opaque key object from a given key specification (key material), or to
* retrieve the underlying key material of a key object in a suitable format.
*
* Multiple compatible key specifications may exist for the same key.
* For example, a DSA public key may be specified using
* {@code DSAPublicKeySpec} or
* {@code X509EncodedKeySpec}. A key factory can be used to translate
* between compatible key specifications.
*
* The following is an example of how to use a key factory in order to
* instantiate a DSA public key from its encoding.
* Assume Alice has received a digital signature from Bob.
* Bob also sent her his public key (in encoded format) to verify
* his signature. Alice then performs the following actions:
*
* Every implementation of the Java platform is required to support the
* following standard {@code KeyFactory} algorithms:
* This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new KeyFactory object encapsulating the
* KeyFactorySpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the name of the requested key algorithm.
* See the KeyFactory section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @return the new KeyFactory object.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* KeyFactorySpi implementation for the
* specified algorithm.
*
* @see Provider
*/
public static KeyFactory getInstance(String algorithm)
throws NoSuchAlgorithmException {
return new KeyFactory(algorithm);
}
/**
* Returns a KeyFactory object that converts
* public/private keys of the specified algorithm.
*
* A new KeyFactory object encapsulating the
* KeyFactorySpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the name of the requested key algorithm.
* See the KeyFactory section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return the new KeyFactory object.
*
* @exception NoSuchAlgorithmException if a KeyFactorySpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the provider name is null
* or empty.
*
* @see Provider
*/
public static KeyFactory getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Instance instance = GetInstance.getInstance("KeyFactory",
KeyFactorySpi.class, algorithm, provider);
return new KeyFactory((KeyFactorySpi)instance.impl,
instance.provider, algorithm);
}
/**
* Returns a KeyFactory object that converts
* public/private keys of the specified algorithm.
*
* A new KeyFactory object encapsulating the
* KeyFactorySpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the name of the requested key algorithm.
* See the KeyFactory section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @return the new KeyFactory object.
*
* @exception NoSuchAlgorithmException if a KeyFactorySpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the specified provider is null.
*
* @see Provider
*
* @since 1.4
*/
public static KeyFactory getInstance(String algorithm, Provider provider)
throws NoSuchAlgorithmException {
Instance instance = GetInstance.getInstance("KeyFactory",
KeyFactorySpi.class, algorithm, provider);
return new KeyFactory((KeyFactorySpi)instance.impl,
instance.provider, algorithm);
}
/**
* Returns the provider of this key factory object.
*
* @return the provider of this key factory object
*/
public final Provider getProvider() {
synchronized (lock) {
// disable further failover after this call
serviceIterator = null;
return provider;
}
}
/**
* Gets the name of the algorithm
* associated with this {@code KeyFactory}.
*
* @return the name of the algorithm associated with this
* {@code KeyFactory}
*/
public final String getAlgorithm() {
return this.algorithm;
}
/**
* Update the active KeyFactorySpi of this class and return the next
* implementation for failover. If no more implemenations are
* available, this method returns null. However, the active spi of
* this class is never set to null.
*/
private KeyFactorySpi nextSpi(KeyFactorySpi oldSpi) {
synchronized (lock) {
// somebody else did a failover concurrently
// try that spi now
if ((oldSpi != null) && (oldSpi != spi)) {
return spi;
}
if (serviceIterator == null) {
return null;
}
while (serviceIterator.hasNext()) {
Service s = serviceIterator.next();
try {
Object obj = s.newInstance(null);
if (obj instanceof KeyFactorySpi == false) {
continue;
}
KeyFactorySpi spi = (KeyFactorySpi)obj;
provider = s.getProvider();
this.spi = spi;
return spi;
} catch (NoSuchAlgorithmException e) {
// ignore
}
}
serviceIterator = null;
return null;
}
}
/**
* Generates a public key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the public key.
*
* @return the public key.
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
public final PublicKey generatePublic(KeySpec keySpec)
throws InvalidKeySpecException {
if (serviceIterator == null) {
return spi.engineGeneratePublic(keySpec);
}
Exception failure = null;
KeyFactorySpi mySpi = spi;
do {
try {
return mySpi.engineGeneratePublic(keySpec);
} catch (Exception e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi);
}
} while (mySpi != null);
if (failure instanceof RuntimeException) {
throw (RuntimeException)failure;
}
if (failure instanceof InvalidKeySpecException) {
throw (InvalidKeySpecException)failure;
}
throw new InvalidKeySpecException
("Could not generate public key", failure);
}
/**
* Generates a private key object from the provided key specification
* (key material).
*
* @param keySpec the specification (key material) of the private key.
*
* @return the private key.
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a private key.
*/
public final PrivateKey generatePrivate(KeySpec keySpec)
throws InvalidKeySpecException {
if (serviceIterator == null) {
return spi.engineGeneratePrivate(keySpec);
}
Exception failure = null;
KeyFactorySpi mySpi = spi;
do {
try {
return mySpi.engineGeneratePrivate(keySpec);
} catch (Exception e) {
if (failure == null) {
failure = e;
}
mySpi = nextSpi(mySpi);
}
} while (mySpi != null);
if (failure instanceof RuntimeException) {
throw (RuntimeException)failure;
}
if (failure instanceof InvalidKeySpecException) {
throw (InvalidKeySpecException)failure;
}
throw new InvalidKeySpecException
("Could not generate private key", failure);
}
/**
* Returns a specification (key material) of the given key object.
* {@code keySpec} identifies the specification class in which
* the key material should be returned. It could, for example, be
* {@code DSAPublicKeySpec.class}, to indicate that the
* key material should be returned in an instance of the
* {@code DSAPublicKeySpec} class.
*
* @param Key factories are used to convert keys (opaque
* cryptographic keys of type {@code Key}) into key specifications
* (transparent representations of the underlying key material), and vice
* versa.
*
* Key factories are bi-directional. That is, they allow you to build an
* opaque key object from a given key specification (key material), or to
* retrieve the underlying key material of a key object in a suitable format.
*
* Multiple compatible key specifications may exist for the same key.
* For example, a DSA public key may be specified using
* {@code DSAPublicKeySpec} or
* {@code X509EncodedKeySpec}. A key factory can be used to translate
* between compatible key specifications.
*
* A provider should document all the key specifications supported by its
* key factory.
*
* @author Jan Luehe
*
*
* @see KeyFactory
* @see Key
* @see PublicKey
* @see PrivateKey
* @see java.security.spec.KeySpec
* @see java.security.spec.DSAPublicKeySpec
* @see java.security.spec.X509EncodedKeySpec
*
* @since 1.2
*/
public abstract class KeyFactorySpi {
/**
* Generates a public key object from the provided key
* specification (key material).
*
* @param keySpec the specification (key material) of the public key.
*
* @return the public key.
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a public key.
*/
protected abstract PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException;
/**
* Generates a private key object from the provided key
* specification (key material).
*
* @param keySpec the specification (key material) of the private key.
*
* @return the private key.
*
* @exception InvalidKeySpecException if the given key specification
* is inappropriate for this key factory to produce a private key.
*/
protected abstract PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException;
/**
* Returns a specification (key material) of the given key
* object.
* {@code keySpec} identifies the specification class in which
* the key material should be returned. It could, for example, be
* {@code DSAPublicKeySpec.class}, to indicate that the
* key material should be returned in an instance of the
* {@code DSAPublicKeySpec} class.
*
* @param Note that this constructor only stores references to the public
* and private key components in the generated key pair. This is safe,
* because {@code Key} objects are immutable.
*
* @param publicKey the public key.
*
* @param privateKey the private key.
*/
public KeyPair(PublicKey publicKey, PrivateKey privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
/**
* Returns a reference to the public key component of this key pair.
*
* @return a reference to the public key.
*/
public PublicKey getPublic() {
return publicKey;
}
/**
* Returns a reference to the private key component of this key pair.
*
* @return a reference to the private key.
*/
public PrivateKey getPrivate() {
return privateKey;
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 28793
Content-Disposition: inline; filename="KeyPairGenerator.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "2056768893917b4d7c3df482a17f968e37c64d5a"
/*
* Copyright (c) 1997, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.util.*;
import java.security.spec.AlgorithmParameterSpec;
import java.security.Provider.Service;
import sun.security.jca.*;
import sun.security.jca.GetInstance.Instance;
import sun.security.util.Debug;
/**
* The KeyPairGenerator class is used to generate pairs of
* public and private keys. Key pair generators are constructed using the
* {@code getInstance} factory methods (static methods that
* return instances of a given class).
*
* A Key pair generator for a particular algorithm creates a public/private
* key pair that can be used with this algorithm. It also associates
* algorithm-specific parameters with each of the generated keys.
*
* There are two ways to generate a key pair: in an algorithm-independent
* manner, and in an algorithm-specific manner.
* The only difference between the two is the initialization of the object:
*
* All key pair generators share the concepts of a keysize and a
* source of randomness. The keysize is interpreted differently for different
* algorithms (e.g., in the case of the DSA algorithm, the keysize
* corresponds to the length of the modulus).
* There is an
* {@link #initialize(int, java.security.SecureRandom) initialize}
* method in this KeyPairGenerator class that takes these two universally
* shared types of arguments. There is also one that takes just a
* {@code keysize} argument, and uses the {@code SecureRandom}
* implementation of the highest-priority installed provider as the source
* of randomness. (If none of the installed providers supply an implementation
* of {@code SecureRandom}, a system-provided source of randomness is
* used.)
*
* Since no other parameters are specified when you call the above
* algorithm-independent {@code initialize} methods, it is up to the
* provider what to do about the algorithm-specific parameters (if any) to be
* associated with each of the keys.
*
* If the algorithm is the DSA algorithm, and the keysize (modulus
* size) is 512, 768, or 1024, then the Sun provider uses a set of
* precomputed values for the {@code p}, {@code q}, and
* {@code g} parameters. If the modulus size is not one of the above
* values, the Sun provider creates a new set of parameters. Other
* providers might have precomputed parameter sets for more than just the
* three modulus sizes mentioned above. Still others might not have a list of
* precomputed parameters at all and instead always create new parameter sets.
*
* For situations where a set of algorithm-specific parameters already
* exists (e.g., so-called community parameters in DSA), there are two
* {@link #initialize(java.security.spec.AlgorithmParameterSpec)
* initialize} methods that have an {@code AlgorithmParameterSpec}
* argument. One also has a {@code SecureRandom} argument, while the
* the other uses the {@code SecureRandom}
* implementation of the highest-priority installed provider as the source
* of randomness. (If none of the installed providers supply an implementation
* of {@code SecureRandom}, a system-provided source of randomness is
* used.)
* In case the client does not explicitly initialize the KeyPairGenerator
* (via a call to an {@code initialize} method), each provider must
* supply (and document) a default initialization.
* For example, the Sun provider uses a default modulus size (keysize)
* of 1024 bits.
*
* Note that this class is abstract and extends from
* {@code KeyPairGeneratorSpi} for historical reasons.
* Application developers should only take notice of the methods defined in
* this {@code KeyPairGenerator} class; all the methods in
* the superclass are intended for cryptographic service providers who wish to
* supply their own implementations of key pair generators.
*
* Every implementation of the Java platform is required to support the
* following standard {@code KeyPairGenerator} algorithms and keysizes in
* parentheses:
* This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new KeyPairGenerator object encapsulating the
* KeyPairGeneratorSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard string name of the algorithm.
* See the KeyPairGenerator section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @return the new KeyPairGenerator object.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* KeyPairGeneratorSpi implementation for the
* specified algorithm.
*
* @see Provider
*/
public static KeyPairGenerator getInstance(String algorithm)
throws NoSuchAlgorithmException {
List A new KeyPairGenerator object encapsulating the
* KeyPairGeneratorSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the standard string name of the algorithm.
* See the KeyPairGenerator section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the string name of the provider.
*
* @return the new KeyPairGenerator object.
*
* @exception NoSuchAlgorithmException if a KeyPairGeneratorSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the provider name is null
* or empty.
*
* @see Provider
*/
public static KeyPairGenerator getInstance(String algorithm,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Instance instance = GetInstance.getInstance("KeyPairGenerator",
KeyPairGeneratorSpi.class, algorithm, provider);
return getInstance(instance, algorithm);
}
/**
* Returns a KeyPairGenerator object that generates public/private
* key pairs for the specified algorithm.
*
* A new KeyPairGenerator object encapsulating the
* KeyPairGeneratorSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the standard string name of the algorithm.
* See the KeyPairGenerator section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @return the new KeyPairGenerator object.
*
* @exception NoSuchAlgorithmException if a KeyPairGeneratorSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the specified provider is null.
*
* @see Provider
*
* @since 1.4
*/
public static KeyPairGenerator getInstance(String algorithm,
Provider provider) throws NoSuchAlgorithmException {
Instance instance = GetInstance.getInstance("KeyPairGenerator",
KeyPairGeneratorSpi.class, algorithm, provider);
return getInstance(instance, algorithm);
}
/**
* Returns the provider of this key pair generator object.
*
* @return the provider of this key pair generator object
*/
public final Provider getProvider() {
disableFailover();
return this.provider;
}
void disableFailover() {
// empty, overridden in Delegate
}
/**
* Initializes the key pair generator for a certain keysize using
* a default parameter set and the {@code SecureRandom}
* implementation of the highest-priority installed provider as the source
* of randomness.
* (If none of the installed providers supply an implementation of
* {@code SecureRandom}, a system-provided source of randomness is
* used.)
*
* @param keysize the keysize. This is an
* algorithm-specific metric, such as modulus length, specified in
* number of bits.
*
* @exception InvalidParameterException if the {@code keysize} is not
* supported by this KeyPairGenerator object.
*/
public void initialize(int keysize) {
initialize(keysize, JCAUtil.getSecureRandom());
}
/**
* Initializes the key pair generator for a certain keysize with
* the given source of randomness (and a default parameter set).
*
* @param keysize the keysize. This is an
* algorithm-specific metric, such as modulus length, specified in
* number of bits.
* @param random the source of randomness.
*
* @exception InvalidParameterException if the {@code keysize} is not
* supported by this KeyPairGenerator object.
*
* @since 1.2
*/
public void initialize(int keysize, SecureRandom random) {
// This does nothing, because either
// 1. the implementation object returned by getInstance() is an
// instance of KeyPairGenerator which has its own
// initialize(keysize, random) method, so the application would
// be calling that method directly, or
// 2. the implementation returned by getInstance() is an instance
// of Delegate, in which case initialize(keysize, random) is
// overridden to call the corresponding SPI method.
// (This is a special case, because the API and SPI method have the
// same name.)
}
/**
* Initializes the key pair generator using the specified parameter
* set and the {@code SecureRandom}
* implementation of the highest-priority installed provider as the source
* of randomness.
* (If none of the installed providers supply an implementation of
* {@code SecureRandom}, a system-provided source of randomness is
* used.).
*
* This concrete method has been added to this previously-defined
* abstract class.
* This method calls the KeyPairGeneratorSpi
* {@link KeyPairGeneratorSpi#initialize(
* java.security.spec.AlgorithmParameterSpec,
* java.security.SecureRandom) initialize} method,
* passing it {@code params} and a source of randomness (obtained
* from the highest-priority installed provider or system-provided if none
* of the installed providers supply one).
* That {@code initialize} method always throws an
* UnsupportedOperationException if it is not overridden by the provider.
*
* @param params the parameter set used to generate the keys.
*
* @exception InvalidAlgorithmParameterException if the given parameters
* are inappropriate for this key pair generator.
*
* @since 1.2
*/
public void initialize(AlgorithmParameterSpec params)
throws InvalidAlgorithmParameterException {
initialize(params, JCAUtil.getSecureRandom());
}
/**
* Initializes the key pair generator with the given parameter
* set and source of randomness.
*
* This concrete method has been added to this previously-defined
* abstract class.
* This method calls the KeyPairGeneratorSpi {@link
* KeyPairGeneratorSpi#initialize(
* java.security.spec.AlgorithmParameterSpec,
* java.security.SecureRandom) initialize} method,
* passing it {@code params} and {@code random}.
* That {@code initialize}
* method always throws an
* UnsupportedOperationException if it is not overridden by the provider.
*
* @param params the parameter set used to generate the keys.
* @param random the source of randomness.
*
* @exception InvalidAlgorithmParameterException if the given parameters
* are inappropriate for this key pair generator.
*
* @since 1.2
*/
public void initialize(AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
// This does nothing, because either
// 1. the implementation object returned by getInstance() is an
// instance of KeyPairGenerator which has its own
// initialize(params, random) method, so the application would
// be calling that method directly, or
// 2. the implementation returned by getInstance() is an instance
// of Delegate, in which case initialize(params, random) is
// overridden to call the corresponding SPI method.
// (This is a special case, because the API and SPI method have the
// same name.)
}
/**
* Generates a key pair.
*
* If this KeyPairGenerator has not been initialized explicitly,
* provider-specific defaults will be used for the size and other
* (algorithm-specific) values of the generated keys.
*
* This will generate a new key pair every time it is called.
*
* This method is functionally equivalent to
* {@link #generateKeyPair() generateKeyPair}.
*
* @return the generated key pair
*
* @since 1.2
*/
public final KeyPair genKeyPair() {
return generateKeyPair();
}
/**
* Generates a key pair.
*
* If this KeyPairGenerator has not been initialized explicitly,
* provider-specific defaults will be used for the size and other
* (algorithm-specific) values of the generated keys.
*
* This will generate a new key pair every time it is called.
*
* This method is functionally equivalent to
* {@link #genKeyPair() genKeyPair}.
*
* @return the generated key pair
*/
public KeyPair generateKeyPair() {
// This does nothing (except returning null), because either:
//
// 1. the implementation object returned by getInstance() is an
// instance of KeyPairGenerator which has its own implementation
// of generateKeyPair (overriding this one), so the application
// would be calling that method directly, or
//
// 2. the implementation returned by getInstance() is an instance
// of Delegate, in which case generateKeyPair is
// overridden to invoke the corresponding SPI method.
//
// (This is a special case, because in JDK 1.1.x the generateKeyPair
// method was used both as an API and a SPI method.)
return null;
}
/*
* The following class allows providers to extend from KeyPairGeneratorSpi
* rather than from KeyPairGenerator. It represents a KeyPairGenerator
* with an encapsulated, provider-supplied SPI object (of type
* KeyPairGeneratorSpi).
* If the provider implementation is an instance of KeyPairGeneratorSpi,
* the getInstance() methods above return an instance of this class, with
* the SPI object encapsulated.
*
* Note: All SPI methods from the original KeyPairGenerator class have been
* moved up the hierarchy into a new class (KeyPairGeneratorSpi), which has
* been interposed in the hierarchy between the API (KeyPairGenerator)
* and its original parent (Object).
*/
//
// error failover notes:
//
// . we failover if the implementation throws an error during init
// by retrying the init on other providers
//
// . we also failover if the init succeeded but the subsequent call
// to generateKeyPair() fails. In order for this to work, we need
// to remember the parameters to the last successful call to init
// and initialize() the next spi using them.
//
// . although not specified, KeyPairGenerators could be thread safe,
// so we make sure we do not interfere with that
//
// . failover is not available, if:
// . getInstance(algorithm, provider) was used
// . a provider extends KeyPairGenerator rather than
// KeyPairGeneratorSpi (JDK 1.1 style)
// . once getProvider() is called
//
private static final class Delegate extends KeyPairGenerator {
// The provider implementation (delegate)
private volatile KeyPairGeneratorSpi spi;
private final Object lock = new Object();
private Iterator This class defines the Service Provider Interface (SPI)
* for the {@code KeyPairGenerator} class, which is used to generate
* pairs of public and private keys.
*
* All the abstract methods in this class must be implemented by each
* cryptographic service provider who wishes to supply the implementation
* of a key pair generator for a particular algorithm.
*
* In case the client does not explicitly initialize the KeyPairGenerator
* (via a call to an {@code initialize} method), each provider must
* supply (and document) a default initialization.
* For example, the Sun provider uses a default modulus size (keysize)
* of 1024 bits.
*
* @author Benjamin Renaud
*
*
* @see KeyPairGenerator
* @see java.security.spec.AlgorithmParameterSpec
*/
public abstract class KeyPairGeneratorSpi {
/**
* Initializes the key pair generator for a certain keysize, using
* the default parameter set.
*
* @param keysize the keysize. This is an
* algorithm-specific metric, such as modulus length, specified in
* number of bits.
*
* @param random the source of randomness for this generator.
*
* @exception InvalidParameterException if the {@code keysize} is not
* supported by this KeyPairGeneratorSpi object.
*/
public abstract void initialize(int keysize, SecureRandom random);
/**
* Initializes the key pair generator using the specified parameter
* set and user-provided source of randomness.
*
* This concrete method has been added to this previously-defined
* abstract class. (For backwards compatibility, it cannot be abstract.)
* It may be overridden by a provider to initialize the key pair
* generator. Such an override
* is expected to throw an InvalidAlgorithmParameterException if
* a parameter is inappropriate for this key pair generator.
* If this method is not overridden, it always throws an
* UnsupportedOperationException.
*
* @param params the parameter set used to generate the keys.
*
* @param random the source of randomness for this generator.
*
* @exception InvalidAlgorithmParameterException if the given parameters
* are inappropriate for this key pair generator.
*
* @since 1.2
*/
public void initialize(AlgorithmParameterSpec params,
SecureRandom random)
throws InvalidAlgorithmParameterException {
throw new UnsupportedOperationException();
}
/**
* Generates a key pair. Unless an initialization method is called
* using a KeyPairGenerator interface, algorithm-specific defaults
* will be used. This will generate a new key pair every time it
* is called.
*
* @return the newly generated {@code KeyPair}
*/
public abstract KeyPair generateKeyPair();
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 6397
Content-Disposition: inline; filename="KeyRep.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "0b1412c1563c15e843d18d07b5b76b9fe5a81434"
/*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.io.*;
import java.util.Locale;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;
/**
* Standardized representation for serialized Key objects.
*
*
*
* Note that a serialized Key may contain sensitive information
* which should not be exposed in untrusted environments. See the
*
* Security Appendix
* of the Serialization Specification for more information.
*
* @see Key
* @see KeyFactory
* @see javax.crypto.spec.SecretKeySpec
* @see java.security.spec.X509EncodedKeySpec
* @see java.security.spec.PKCS8EncodedKeySpec
*
* @since 1.5
*/
public class KeyRep implements Serializable {
private static final long serialVersionUID = -4757683898830641853L;
/**
* Key type.
*
* @since 1.5
*/
public static enum Type {
/** Type for secret keys. */
SECRET,
/** Type for public keys. */
PUBLIC,
/** Type for private keys. */
PRIVATE,
}
private static final String PKCS8 = "PKCS#8";
private static final String X509 = "X.509";
private static final String RAW = "RAW";
/**
* Either one of Type.SECRET, Type.PUBLIC, or Type.PRIVATE
*
* @serial
*/
private Type type;
/**
* The Key algorithm
*
* @serial
*/
private String algorithm;
/**
* The Key encoding format
*
* @serial
*/
private String format;
/**
* The encoded Key bytes
*
* @serial
*/
private byte[] encoded;
/**
* Construct the alternate Key class.
*
*
*
* @param type either one of Type.SECRET, Type.PUBLIC, or Type.PRIVATE
* @param algorithm the algorithm returned from
* {@code Key.getAlgorithm()}
* @param format the encoding format returned from
* {@code Key.getFormat()}
* @param encoded the encoded bytes returned from
* {@code Key.getEncoded()}
*
* @exception NullPointerException
* if type is {@code null},
* if algorithm is {@code null},
* if format is {@code null},
* or if encoded is {@code null}
*/
public KeyRep(Type type, String algorithm,
String format, byte[] encoded) {
if (type == null || algorithm == null ||
format == null || encoded == null) {
throw new NullPointerException("invalid null input(s)");
}
this.type = type;
this.algorithm = algorithm;
this.format = format.toUpperCase(Locale.ENGLISH);
this.encoded = encoded.clone();
}
/**
* Resolve the Key object.
*
* This method supports three Type/format combinations:
*
*
* @return the resolved Key object
*
* @exception ObjectStreamException if the Type/format
* combination is unrecognized, if the algorithm, key format, or
* encoded key bytes are unrecognized/invalid, of if the
* resolution of the key fails for any reason
*/
protected Object readResolve() throws ObjectStreamException {
try {
if (type == Type.SECRET && RAW.equals(format)) {
return new SecretKeySpec(encoded, algorithm);
} else if (type == Type.PUBLIC && X509.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePublic(new X509EncodedKeySpec(encoded));
} else if (type == Type.PRIVATE && PKCS8.equals(format)) {
KeyFactory f = KeyFactory.getInstance(algorithm);
return f.generatePrivate(new PKCS8EncodedKeySpec(encoded));
} else {
throw new NotSerializableException
("unrecognized type/format combination: " +
type + "/" + format);
}
} catch (NotSerializableException nse) {
throw nse;
} catch (Exception e) {
NotSerializableException nse = new NotSerializableException
("java.security.Key: " +
"[" + type + "] " +
"[" + algorithm + "] " +
"[" + format + "]");
nse.initCause(e);
throw nse;
}
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 76179
Content-Disposition: inline; filename="KeyStore.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "4278369e8be966cc596d4e9f21f28602479b1248"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.io.*;
import java.net.URI;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.security.cert.CertificateException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.*;
import javax.crypto.SecretKey;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.callback.*;
import sun.security.util.Debug;
/**
* This class represents a storage facility for cryptographic
* keys and certificates.
*
* A {@code KeyStore} manages different types of entries.
* Each type of entry implements the {@code KeyStore.Entry} interface.
* Three basic {@code KeyStore.Entry} implementations are provided:
*
* This type of entry holds a cryptographic {@code PrivateKey},
* which is optionally stored in a protected format to prevent
* unauthorized access. It is also accompanied by a certificate chain
* for the corresponding public key.
*
* Private keys and certificate chains are used by a given entity for
* self-authentication. Applications for this authentication include software
* distribution organizations which sign JAR files as part of releasing
* and/or licensing software.
*
* This type of entry holds a cryptographic {@code SecretKey},
* which is optionally stored in a protected format to prevent
* unauthorized access.
*
* This type of entry contains a single public key {@code Certificate}
* belonging to another party. It is called a trusted certificate
* because the keystore owner trusts that the public key in the certificate
* indeed belongs to the identity identified by the subject (owner)
* of the certificate.
*
* This type of entry can be used to authenticate other parties.
* Each entry in a keystore is identified by an "alias" string. In the
* case of private keys and their associated certificate chains, these strings
* distinguish among the different ways in which the entity may authenticate
* itself. For example, the entity may authenticate itself using different
* certificate authorities, or using different public key algorithms.
*
* Whether aliases are case sensitive is implementation dependent. In order
* to avoid problems, it is recommended not to use aliases in a KeyStore that
* only differ in case.
*
* Whether keystores are persistent, and the mechanisms used by the
* keystore if it is persistent, are not specified here. This allows
* use of a variety of techniques for protecting sensitive (e.g., private or
* secret) keys. Smart cards or other integrated cryptographic engines
* (SafeKeyper) are one option, and simpler mechanisms such as files may also
* be used (in a variety of formats).
*
* Typical ways to request a KeyStore object include
* relying on the default type and providing a specific keystore type.
*
*
* Before a keystore can be accessed, it must be
* {@link #load(java.io.InputStream, char[]) loaded}.
* Once the keystore has been loaded, it is possible
* to read existing entries from the keystore, or to write new entries
* into the keystore:
* Every implementation of the Java platform is required to support
* the following standard {@code KeyStore} type:
* The information stored in a {@code ProtectionParameter}
* object protects the contents of a keystore.
* For example, protection parameters may be used to check
* the integrity of keystore data, or to protect the
* confidentiality of sensitive keystore data
* (such as a {@code PrivateKey}).
*
* @since 1.5
*/
public static interface ProtectionParameter { }
/**
* A password-based implementation of {@code ProtectionParameter}.
*
* @since 1.5
*/
public static class PasswordProtection implements
ProtectionParameter, javax.security.auth.Destroyable {
private final char[] password;
private final String protectionAlgorithm;
private final AlgorithmParameterSpec protectionParameters;
private volatile boolean destroyed = false;
/**
* Creates a password parameter.
*
* The specified {@code password} is cloned before it is stored
* in the new {@code PasswordProtection} object.
*
* @param password the password, which may be {@code null}
*/
public PasswordProtection(char[] password) {
this.password = (password == null) ? null : password.clone();
this.protectionAlgorithm = null;
this.protectionParameters = null;
}
/**
* Creates a password parameter and specifies the protection algorithm
* and associated parameters to use when encrypting a keystore entry.
*
* The specified {@code password} is cloned before it is stored in the
* new {@code PasswordProtection} object.
*
* @param password the password, which may be {@code null}
* @param protectionAlgorithm the encryption algorithm name, for
* example, {@code PBEWithHmacSHA256AndAES_256}.
* See the Cipher section in the
* Java Cryptography Architecture Standard Algorithm Name
* Documentation
* for information about standard encryption algorithm names.
* @param protectionParameters the encryption algorithm parameter
* specification, which may be {@code null}
* @exception NullPointerException if {@code protectionAlgorithm} is
* {@code null}
*
* @since 1.8
*/
public PasswordProtection(char[] password, String protectionAlgorithm,
AlgorithmParameterSpec protectionParameters) {
if (protectionAlgorithm == null) {
throw new NullPointerException("invalid null input");
}
this.password = (password == null) ? null : password.clone();
this.protectionAlgorithm = protectionAlgorithm;
this.protectionParameters = protectionParameters;
}
/**
* Gets the name of the protection algorithm.
* If none was set then the keystore provider will use its default
* protection algorithm. The name of the default protection algorithm
* for a given keystore type is set using the
* {@code 'keystore. Note that this method returns a reference to the password.
* If a clone of the array is created it is the caller's
* responsibility to zero out the password information
* after it is no longer needed.
*
* @see #destroy()
* @return the password, which may be {@code null}
* @exception IllegalStateException if the password has
* been cleared (destroyed)
*/
public synchronized char[] getPassword() {
if (destroyed) {
throw new IllegalStateException("password has been cleared");
}
return password;
}
/**
* Clears the password.
*
* @exception DestroyFailedException if this method was unable
* to clear the password
*/
public synchronized void destroy() throws DestroyFailedException {
destroyed = true;
if (password != null) {
Arrays.fill(password, ' ');
}
}
/**
* Determines if password has been cleared.
*
* @return true if the password has been cleared, false otherwise
*/
public synchronized boolean isDestroyed() {
return destroyed;
}
}
/**
* A ProtectionParameter encapsulating a CallbackHandler.
*
* @since 1.5
*/
public static class CallbackHandlerProtection
implements ProtectionParameter {
private final CallbackHandler handler;
/**
* Constructs a new CallbackHandlerProtection from a
* CallbackHandler.
*
* @param handler the CallbackHandler
* @exception NullPointerException if handler is null
*/
public CallbackHandlerProtection(CallbackHandler handler) {
if (handler == null) {
throw new NullPointerException("handler must not be null");
}
this.handler = handler;
}
/**
* Returns the CallbackHandler.
*
* @return the CallbackHandler.
*/
public CallbackHandler getCallbackHandler() {
return handler;
}
}
/**
* A marker interface for {@code KeyStore} entry types.
*
* @since 1.5
*/
public static interface Entry {
/**
* Retrieves the attributes associated with an entry.
*
* The default implementation returns an empty {@code Set}.
*
* @return an unmodifiable {@code Set} of attributes, possibly empty
*
* @since 1.8
*/
public default Set The specified {@code chain} is cloned before it is stored
* in the new {@code PrivateKeyEntry} object.
*
* @param privateKey the {@code PrivateKey}
* @param chain an array of {@code Certificate}s
* representing the certificate chain.
* The chain must be ordered and contain a
* {@code Certificate} at index 0
* corresponding to the private key.
*
* @exception NullPointerException if
* {@code privateKey} or {@code chain}
* is {@code null}
* @exception IllegalArgumentException if the specified chain has a
* length of 0, if the specified chain does not contain
* {@code Certificate}s of the same type,
* or if the {@code PrivateKey} algorithm
* does not match the algorithm of the {@code PublicKey}
* in the end entity {@code Certificate} (at index 0)
*/
public PrivateKeyEntry(PrivateKey privateKey, Certificate[] chain) {
this(privateKey, chain, Collections. The specified {@code chain} and {@code attributes} are cloned
* before they are stored in the new {@code PrivateKeyEntry} object.
*
* @param privateKey the {@code PrivateKey}
* @param chain an array of {@code Certificate}s
* representing the certificate chain.
* The chain must be ordered and contain a
* {@code Certificate} at index 0
* corresponding to the private key.
* @param attributes the attributes
*
* @exception NullPointerException if {@code privateKey}, {@code chain}
* or {@code attributes} is {@code null}
* @exception IllegalArgumentException if the specified chain has a
* length of 0, if the specified chain does not contain
* {@code Certificate}s of the same type,
* or if the {@code PrivateKey} algorithm
* does not match the algorithm of the {@code PublicKey}
* in the end entity {@code Certificate} (at index 0)
*
* @since 1.8
*/
public PrivateKeyEntry(PrivateKey privateKey, Certificate[] chain,
Set The stored chain is cloned before being returned.
*
* @return an array of {@code Certificate}s corresponding
* to the certificate chain for the public key.
* If the certificates are of type X.509,
* the runtime type of the returned array is
* {@code X509Certificate[]}.
*/
public Certificate[] getCertificateChain() {
return chain.clone();
}
/**
* Gets the end entity {@code Certificate}
* from the certificate chain in this entry.
*
* @return the end entity {@code Certificate} (at index 0)
* from the certificate chain in this entry.
* If the certificate is of type X.509,
* the runtime type of the returned certificate is
* {@code X509Certificate}.
*/
public Certificate getCertificate() {
return chain[0];
}
/**
* Retrieves the attributes associated with an entry.
*
*
* @return an unmodifiable {@code Set} of attributes, possibly empty
*
* @since 1.8
*/
@Override
public Set The specified {@code attributes} is cloned before it is stored
* in the new {@code SecretKeyEntry} object.
*
* @param secretKey the {@code SecretKey}
* @param attributes the attributes
*
* @exception NullPointerException if {@code secretKey} or
* {@code attributes} is {@code null}
*
* @since 1.8
*/
public SecretKeyEntry(SecretKey secretKey, Set
*
* @return an unmodifiable {@code Set} of attributes, possibly empty
*
* @since 1.8
*/
@Override
public Set The specified {@code attributes} is cloned before it is stored
* in the new {@code TrustedCertificateEntry} object.
*
* @param trustedCert the trusted {@code Certificate}
* @param attributes the attributes
*
* @exception NullPointerException if {@code trustedCert} or
* {@code attributes} is {@code null}
*
* @since 1.8
*/
public TrustedCertificateEntry(Certificate trustedCert,
Set
*
* @return an unmodifiable {@code Set} of attributes, possibly empty
*
* @since 1.8
*/
@Override
public Set This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new KeyStore object encapsulating the
* KeyStoreSpi implementation from the first
* Provider that supports the specified type is returned.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param type the type of keystore.
* See the KeyStore section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard keystore types.
*
* @return a keystore object of the specified type.
*
* @exception KeyStoreException if no Provider supports a
* KeyStoreSpi implementation for the
* specified type.
*
* @see Provider
*/
public static KeyStore getInstance(String type)
throws KeyStoreException
{
try {
Object[] objs = Security.getImpl(type, "KeyStore", (String)null);
return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
} catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException(type + " not found", nsae);
} catch (NoSuchProviderException nspe) {
throw new KeyStoreException(type + " not found", nspe);
}
}
/**
* Returns a keystore object of the specified type.
*
* A new KeyStore object encapsulating the
* KeyStoreSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param type the type of keystore.
* See the KeyStore section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard keystore types.
*
* @param provider the name of the provider.
*
* @return a keystore object of the specified type.
*
* @exception KeyStoreException if a KeyStoreSpi
* implementation for the specified type is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the provider name is null
* or empty.
*
* @see Provider
*/
public static KeyStore getInstance(String type, String provider)
throws KeyStoreException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
try {
Object[] objs = Security.getImpl(type, "KeyStore", provider);
return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
} catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException(type + " not found", nsae);
}
}
/**
* Returns a keystore object of the specified type.
*
* A new KeyStore object encapsulating the
* KeyStoreSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param type the type of keystore.
* See the KeyStore section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard keystore types.
*
* @param provider the provider.
*
* @return a keystore object of the specified type.
*
* @exception KeyStoreException if KeyStoreSpi
* implementation for the specified type is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the specified provider is null.
*
* @see Provider
*
* @since 1.4
*/
public static KeyStore getInstance(String type, Provider provider)
throws KeyStoreException
{
if (provider == null)
throw new IllegalArgumentException("missing provider");
try {
Object[] objs = Security.getImpl(type, "KeyStore", provider);
return new KeyStore((KeyStoreSpi)objs[0], (Provider)objs[1], type);
} catch (NoSuchAlgorithmException nsae) {
throw new KeyStoreException(type + " not found", nsae);
}
}
/**
* Returns the default keystore type as specified by the
* {@code keystore.type} security property, or the string
* {@literal "jks"} (acronym for {@literal "Java keystore"})
* if no such property exists.
*
* The default keystore type can be used by applications that do not
* want to use a hard-coded keystore type when calling one of the
* {@code getInstance} methods, and want to provide a default keystore
* type in case a user does not specify its own.
*
* The default keystore type can be changed by setting the value of the
* {@code keystore.type} security property to the desired keystore type.
*
* @return the default keystore type as specified by the
* {@code keystore.type} security property, or the string {@literal "jks"}
* if no such property exists.
* @see java.security.Security security properties
*/
public final static String getDefaultType() {
String kstype;
kstype = AccessController.doPrivileged(new PrivilegedAction If the given alias name identifies an entry
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* then the trusted certificate contained in that entry is returned.
*
* If the given alias name identifies an entry
* created by a call to {@code setKeyEntry},
* or created by a call to {@code setEntry} with a
* {@code PrivateKeyEntry},
* then the first element of the certificate chain in that entry
* is returned.
*
* @param alias the alias name
*
* @return the certificate, or null if the given alias does not exist or
* does not contain a certificate.
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final Certificate getCertificate(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetCertificate(alias);
}
/**
* Returns the creation date of the entry identified by the given alias.
*
* @param alias the alias name
*
* @return the creation date of this entry, or null if the given alias does
* not exist
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final Date getCreationDate(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetCreationDate(alias);
}
/**
* Assigns the given key to the given alias, protecting it with the given
* password.
*
* If the given key is of type {@code java.security.PrivateKey},
* it must be accompanied by a certificate chain certifying the
* corresponding public key.
*
* If the given alias already exists, the keystore information
* associated with it is overridden by the given key (and possibly
* certificate chain).
*
* @param alias the alias name
* @param key the key to be associated with the alias
* @param password the password to protect the key
* @param chain the certificate chain for the corresponding public
* key (only required if the given key is of type
* {@code java.security.PrivateKey}).
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded), the given key cannot be protected, or this operation fails
* for some other reason
*/
public final void setKeyEntry(String alias, Key key, char[] password,
Certificate[] chain)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
if ((key instanceof PrivateKey) &&
(chain == null || chain.length == 0)) {
throw new IllegalArgumentException("Private key must be "
+ "accompanied by certificate "
+ "chain");
}
keyStoreSpi.engineSetKeyEntry(alias, key, password, chain);
}
/**
* Assigns the given key (that has already been protected) to the given
* alias.
*
* If the protected key is of type
* {@code java.security.PrivateKey}, it must be accompanied by a
* certificate chain certifying the corresponding public key. If the
* underlying keystore implementation is of type {@code jks},
* {@code key} must be encoded as an
* {@code EncryptedPrivateKeyInfo} as defined in the PKCS #8 standard.
*
* If the given alias already exists, the keystore information
* associated with it is overridden by the given key (and possibly
* certificate chain).
*
* @param alias the alias name
* @param key the key (in protected format) to be associated with the alias
* @param chain the certificate chain for the corresponding public
* key (only useful if the protected key is of type
* {@code java.security.PrivateKey}).
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded), or if this operation fails for some other reason.
*/
public final void setKeyEntry(String alias, byte[] key,
Certificate[] chain)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineSetKeyEntry(alias, key, chain);
}
/**
* Assigns the given trusted certificate to the given alias.
*
* If the given alias identifies an existing entry
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* the trusted certificate in the existing entry
* is overridden by the given certificate.
*
* @param alias the alias name
* @param cert the certificate
*
* @exception KeyStoreException if the keystore has not been initialized,
* or the given alias already exists and does not identify an
* entry containing a trusted certificate,
* or this operation fails for some other reason.
*/
public final void setCertificateEntry(String alias, Certificate cert)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineSetCertificateEntry(alias, cert);
}
/**
* Deletes the entry identified by the given alias from this keystore.
*
* @param alias the alias name
*
* @exception KeyStoreException if the keystore has not been initialized,
* or if the entry cannot be removed.
*/
public final void deleteEntry(String alias)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineDeleteEntry(alias);
}
/**
* Lists all the alias names of this keystore.
*
* @return enumeration of the alias names
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final Enumeration This method attempts to match the given certificate with each
* keystore entry. If the entry being considered was
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* then the given certificate is compared to that entry's certificate.
*
* If the entry being considered was
* created by a call to {@code setKeyEntry},
* or created by a call to {@code setEntry} with a
* {@code PrivateKeyEntry},
* then the given certificate is compared to the first
* element of that entry's certificate chain.
*
* @param cert the certificate to match with.
*
* @return the alias name of the first entry with a matching certificate,
* or null if no such entry exists in this keystore.
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
*/
public final String getCertificateAlias(Certificate cert)
throws KeyStoreException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetCertificateAlias(cert);
}
/**
* Stores this keystore to the given output stream, and protects its
* integrity with the given password.
*
* @param stream the output stream to which this keystore is written.
* @param password the password to generate the keystore integrity check
*
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
* @exception IOException if there was an I/O problem with data
* @exception NoSuchAlgorithmException if the appropriate data integrity
* algorithm could not be found
* @exception CertificateException if any of the certificates included in
* the keystore data could not be stored
*/
public final void store(OutputStream stream, char[] password)
throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException
{
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineStore(stream, password);
}
/**
* Stores this keystore using the given {@code LoadStoreParameter}.
*
* @param param the {@code LoadStoreParameter}
* that specifies how to store the keystore,
* which may be {@code null}
*
* @exception IllegalArgumentException if the given
* {@code LoadStoreParameter}
* input is not recognized
* @exception KeyStoreException if the keystore has not been initialized
* (loaded)
* @exception IOException if there was an I/O problem with data
* @exception NoSuchAlgorithmException if the appropriate data integrity
* algorithm could not be found
* @exception CertificateException if any of the certificates included in
* the keystore data could not be stored
*
* @since 1.5
*/
public final void store(LoadStoreParameter param)
throws KeyStoreException, IOException,
NoSuchAlgorithmException, CertificateException {
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineStore(param);
}
/**
* Loads this KeyStore from the given input stream.
*
* A password may be given to unlock the keystore
* (e.g. the keystore resides on a hardware token device),
* or to check the integrity of the keystore data.
* If a password is not given for integrity checking,
* then integrity checking is not performed.
*
* In order to create an empty keystore, or if the keystore cannot
* be initialized from a stream, pass {@code null}
* as the {@code stream} argument.
*
* Note that if this keystore has already been loaded, it is
* reinitialized and loaded again from the given input stream.
*
* @param stream the input stream from which the keystore is loaded,
* or {@code null}
* @param password the password used to check the integrity of
* the keystore, the password used to unlock the keystore,
* or {@code null}
*
* @exception IOException if there is an I/O or format problem with the
* keystore data, if a password is required but not given,
* or if the given password was incorrect. If the error is due to a
* wrong password, the {@link Throwable#getCause cause} of the
* {@code IOException} should be an
* {@code UnrecoverableKeyException}
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*/
public final void load(InputStream stream, char[] password)
throws IOException, NoSuchAlgorithmException, CertificateException
{
keyStoreSpi.engineLoad(stream, password);
initialized = true;
}
/**
* Loads this keystore using the given {@code LoadStoreParameter}.
*
* Note that if this KeyStore has already been loaded, it is
* reinitialized and loaded again from the given parameter.
*
* @param param the {@code LoadStoreParameter}
* that specifies how to load the keystore,
* which may be {@code null}
*
* @exception IllegalArgumentException if the given
* {@code LoadStoreParameter}
* input is not recognized
* @exception IOException if there is an I/O or format problem with the
* keystore data. If the error is due to an incorrect
* {@code ProtectionParameter} (e.g. wrong password)
* the {@link Throwable#getCause cause} of the
* {@code IOException} should be an
* {@code UnrecoverableKeyException}
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*
* @since 1.5
*/
public final void load(LoadStoreParameter param)
throws IOException, NoSuchAlgorithmException,
CertificateException {
keyStoreSpi.engineLoad(param);
initialized = true;
}
/**
* Gets a keystore {@code Entry} for the specified alias
* with the specified protection parameter.
*
* @param alias get the keystore {@code Entry} for this alias
* @param protParam the {@code ProtectionParameter}
* used to protect the {@code Entry},
* which may be {@code null}
*
* @return the keystore {@code Entry} for the specified alias,
* or {@code null} if there is no such entry
*
* @exception NullPointerException if
* {@code alias} is {@code null}
* @exception NoSuchAlgorithmException if the algorithm for recovering the
* entry cannot be found
* @exception UnrecoverableEntryException if the specified
* {@code protParam} were insufficient or invalid
* @exception UnrecoverableKeyException if the entry is a
* {@code PrivateKeyEntry} or {@code SecretKeyEntry}
* and the specified {@code protParam} does not contain
* the information needed to recover the key (e.g. wrong password)
* @exception KeyStoreException if the keystore has not been initialized
* (loaded).
* @see #setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter)
*
* @since 1.5
*/
public final Entry getEntry(String alias, ProtectionParameter protParam)
throws NoSuchAlgorithmException, UnrecoverableEntryException,
KeyStoreException {
if (alias == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineGetEntry(alias, protParam);
}
/**
* Saves a keystore {@code Entry} under the specified alias.
* The protection parameter is used to protect the
* {@code Entry}.
*
* If an entry already exists for the specified alias,
* it is overridden.
*
* @param alias save the keystore {@code Entry} under this alias
* @param entry the {@code Entry} to save
* @param protParam the {@code ProtectionParameter}
* used to protect the {@code Entry},
* which may be {@code null}
*
* @exception NullPointerException if
* {@code alias} or {@code entry}
* is {@code null}
* @exception KeyStoreException if the keystore has not been initialized
* (loaded), or if this operation fails for some other reason
*
* @see #getEntry(String, KeyStore.ProtectionParameter)
*
* @since 1.5
*/
public final void setEntry(String alias, Entry entry,
ProtectionParameter protParam)
throws KeyStoreException {
if (alias == null || entry == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
keyStoreSpi.engineSetEntry(alias, entry, protParam);
}
/**
* Determines if the keystore {@code Entry} for the specified
* {@code alias} is an instance or subclass of the specified
* {@code entryClass}.
*
* @param alias the alias name
* @param entryClass the entry class
*
* @return true if the keystore {@code Entry} for the specified
* {@code alias} is an instance or subclass of the
* specified {@code entryClass}, false otherwise
*
* @exception NullPointerException if
* {@code alias} or {@code entryClass}
* is {@code null}
* @exception KeyStoreException if the keystore has not been
* initialized (loaded)
*
* @since 1.5
*/
public final boolean
entryInstanceOf(String alias,
Class extends KeyStore.Entry> entryClass)
throws KeyStoreException
{
if (alias == null || entryClass == null) {
throw new NullPointerException("invalid null input");
}
if (!initialized) {
throw new KeyStoreException("Uninitialized keystore");
}
return keyStoreSpi.engineEntryInstanceOf(alias, entryClass);
}
/**
* A description of a to-be-instantiated KeyStore object.
*
* An instance of this class encapsulates the information needed to
* instantiate and initialize a KeyStore object. That process is
* triggered when the {@linkplain #getKeyStore} method is called.
*
* This makes it possible to decouple configuration from KeyStore
* object creation and e.g. delay a password prompt until it is
* needed.
*
* @see KeyStore
* @see javax.net.ssl.KeyStoreBuilderParameters
* @since 1.5
*/
public static abstract class Builder {
// maximum times to try the callbackhandler if the password is wrong
static final int MAX_CALLBACK_TRIES = 3;
/**
* Construct a new Builder.
*/
protected Builder() {
// empty
}
/**
* Returns the KeyStore described by this object.
*
* @return the {@code KeyStore} described by this object
* @exception KeyStoreException if an error occurred during the
* operation, for example if the KeyStore could not be
* instantiated or loaded
*/
public abstract KeyStore getKeyStore() throws KeyStoreException;
/**
* Returns the ProtectionParameters that should be used to obtain
* the {@link KeyStore.Entry Entry} with the given alias.
* The {@code getKeyStore} method must be invoked before this
* method may be called.
*
* @return the ProtectionParameters that should be used to obtain
* the {@link KeyStore.Entry Entry} with the given alias.
* @param alias the alias of the KeyStore entry
* @throws NullPointerException if alias is null
* @throws KeyStoreException if an error occurred during the
* operation
* @throws IllegalStateException if the getKeyStore method has
* not been invoked prior to calling this method
*/
public abstract ProtectionParameter getProtectionParameter(String alias)
throws KeyStoreException;
/**
* Returns a new Builder that encapsulates the given KeyStore.
* The {@linkplain #getKeyStore} method of the returned object
* will return {@code keyStore}, the {@linkplain
* #getProtectionParameter getProtectionParameter()} method will
* return {@code protectionParameters}.
*
* This is useful if an existing KeyStore object needs to be
* used with Builder-based APIs.
*
* @return a new Builder object
* @param keyStore the KeyStore to be encapsulated
* @param protectionParameter the ProtectionParameter used to
* protect the KeyStore entries
* @throws NullPointerException if keyStore or
* protectionParameters is null
* @throws IllegalArgumentException if the keyStore has not been
* initialized
*/
public static Builder newInstance(final KeyStore keyStore,
final ProtectionParameter protectionParameter) {
if ((keyStore == null) || (protectionParameter == null)) {
throw new NullPointerException();
}
if (keyStore.initialized == false) {
throw new IllegalArgumentException("KeyStore not initialized");
}
return new Builder() {
private volatile boolean getCalled;
public KeyStore getKeyStore() {
getCalled = true;
return keyStore;
}
public ProtectionParameter getProtectionParameter(String alias)
{
if (alias == null) {
throw new NullPointerException();
}
if (getCalled == false) {
throw new IllegalStateException
("getKeyStore() must be called first");
}
return protectionParameter;
}
};
}
/**
* Returns a new Builder object.
*
* The first call to the {@link #getKeyStore} method on the returned
* builder will create a KeyStore of type {@code type} and call
* its {@link KeyStore#load load()} method.
* The {@code inputStream} argument is constructed from
* {@code file}.
* If {@code protection} is a
* {@code PasswordProtection}, the password is obtained by
* calling the {@code getPassword} method.
* Otherwise, if {@code protection} is a
* {@code CallbackHandlerProtection}, the password is obtained
* by invoking the CallbackHandler.
*
* Subsequent calls to {@link #getKeyStore} return the same object
* as the initial call. If the initial call to failed with a
* KeyStoreException, subsequent calls also throw a
* KeyStoreException.
*
* The KeyStore is instantiated from {@code provider} if
* non-null. Otherwise, all installed providers are searched.
*
* Calls to {@link #getProtectionParameter getProtectionParameter()}
* will return a {@link KeyStore.PasswordProtection PasswordProtection}
* object encapsulating the password that was used to invoke the
* {@code load} method.
*
* Note that the {@link #getKeyStore} method is executed
* within the {@link AccessControlContext} of the code invoking this
* method.
*
* @return a new Builder object
* @param type the type of KeyStore to be constructed
* @param provider the provider from which the KeyStore is to
* be instantiated (or null)
* @param file the File that contains the KeyStore data
* @param protection the ProtectionParameter securing the KeyStore data
* @throws NullPointerException if type, file or protection is null
* @throws IllegalArgumentException if protection is not an instance
* of either PasswordProtection or CallbackHandlerProtection; or
* if file does not exist or does not refer to a normal file
*/
public static Builder newInstance(String type, Provider provider,
File file, ProtectionParameter protection) {
if ((type == null) || (file == null) || (protection == null)) {
throw new NullPointerException();
}
if ((protection instanceof PasswordProtection == false) &&
(protection instanceof CallbackHandlerProtection == false)) {
throw new IllegalArgumentException
("Protection must be PasswordProtection or " +
"CallbackHandlerProtection");
}
if (file.isFile() == false) {
throw new IllegalArgumentException
("File does not exist or it does not refer " +
"to a normal file: " + file);
}
return new FileBuilder(type, provider, file, protection,
AccessController.getContext());
}
private static final class FileBuilder extends Builder {
private final String type;
private final Provider provider;
private final File file;
private ProtectionParameter protection;
private ProtectionParameter keyProtection;
private final AccessControlContext context;
private KeyStore keyStore;
private Throwable oldException;
FileBuilder(String type, Provider provider, File file,
ProtectionParameter protection,
AccessControlContext context) {
this.type = type;
this.provider = provider;
this.file = file;
this.protection = protection;
this.context = context;
}
public synchronized KeyStore getKeyStore() throws KeyStoreException
{
if (keyStore != null) {
return keyStore;
}
if (oldException != null) {
throw new KeyStoreException
("Previous KeyStore instantiation failed",
oldException);
}
PrivilegedExceptionAction Each call to the {@link #getKeyStore} method on the returned
* builder will return a new KeyStore object of type {@code type}.
* Its {@link KeyStore#load(KeyStore.LoadStoreParameter) load()}
* method is invoked using a
* {@code LoadStoreParameter} that encapsulates
* {@code protection}.
*
* The KeyStore is instantiated from {@code provider} if
* non-null. Otherwise, all installed providers are searched.
*
* Calls to {@link #getProtectionParameter getProtectionParameter()}
* will return {@code protection}.
*
* Note that the {@link #getKeyStore} method is executed
* within the {@link AccessControlContext} of the code invoking this
* method.
*
* @return a new Builder object
* @param type the type of KeyStore to be constructed
* @param provider the provider from which the KeyStore is to
* be instantiated (or null)
* @param protection the ProtectionParameter securing the Keystore
* @throws NullPointerException if type or protection is null
*/
public static Builder newInstance(final String type,
final Provider provider, final ProtectionParameter protection) {
if ((type == null) || (protection == null)) {
throw new NullPointerException();
}
final AccessControlContext context = AccessController.getContext();
return new Builder() {
private volatile boolean getCalled;
private IOException oldException;
private final PrivilegedExceptionAction If the given alias name identifies an entry
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* then the trusted certificate contained in that entry is returned.
*
* If the given alias name identifies an entry
* created by a call to {@code setKeyEntry},
* or created by a call to {@code setEntry} with a
* {@code PrivateKeyEntry},
* then the first element of the certificate chain in that entry
* (if a chain exists) is returned.
*
* @param alias the alias name
*
* @return the certificate, or null if the given alias does not exist or
* does not contain a certificate.
*/
public abstract Certificate engineGetCertificate(String alias);
/**
* Returns the creation date of the entry identified by the given alias.
*
* @param alias the alias name
*
* @return the creation date of this entry, or null if the given alias does
* not exist
*/
public abstract Date engineGetCreationDate(String alias);
/**
* Assigns the given key to the given alias, protecting it with the given
* password.
*
* If the given key is of type {@code java.security.PrivateKey},
* it must be accompanied by a certificate chain certifying the
* corresponding public key.
*
* If the given alias already exists, the keystore information
* associated with it is overridden by the given key (and possibly
* certificate chain).
*
* @param alias the alias name
* @param key the key to be associated with the alias
* @param password the password to protect the key
* @param chain the certificate chain for the corresponding public
* key (only required if the given key is of type
* {@code java.security.PrivateKey}).
*
* @exception KeyStoreException if the given key cannot be protected, or
* this operation fails for some other reason
*/
public abstract void engineSetKeyEntry(String alias, Key key,
char[] password,
Certificate[] chain)
throws KeyStoreException;
/**
* Assigns the given key (that has already been protected) to the given
* alias.
*
* If the protected key is of type
* {@code java.security.PrivateKey},
* it must be accompanied by a certificate chain certifying the
* corresponding public key.
*
* If the given alias already exists, the keystore information
* associated with it is overridden by the given key (and possibly
* certificate chain).
*
* @param alias the alias name
* @param key the key (in protected format) to be associated with the alias
* @param chain the certificate chain for the corresponding public
* key (only useful if the protected key is of type
* {@code java.security.PrivateKey}).
*
* @exception KeyStoreException if this operation fails.
*/
public abstract void engineSetKeyEntry(String alias, byte[] key,
Certificate[] chain)
throws KeyStoreException;
/**
* Assigns the given certificate to the given alias.
*
* If the given alias identifies an existing entry
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* the trusted certificate in the existing entry
* is overridden by the given certificate.
*
* @param alias the alias name
* @param cert the certificate
*
* @exception KeyStoreException if the given alias already exists and does
* not identify an entry containing a trusted certificate,
* or this operation fails for some other reason.
*/
public abstract void engineSetCertificateEntry(String alias,
Certificate cert)
throws KeyStoreException;
/**
* Deletes the entry identified by the given alias from this keystore.
*
* @param alias the alias name
*
* @exception KeyStoreException if the entry cannot be removed.
*/
public abstract void engineDeleteEntry(String alias)
throws KeyStoreException;
/**
* Lists all the alias names of this keystore.
*
* @return enumeration of the alias names
*/
public abstract Enumeration This method attempts to match the given certificate with each
* keystore entry. If the entry being considered was
* created by a call to {@code setCertificateEntry},
* or created by a call to {@code setEntry} with a
* {@code TrustedCertificateEntry},
* then the given certificate is compared to that entry's certificate.
*
* If the entry being considered was
* created by a call to {@code setKeyEntry},
* or created by a call to {@code setEntry} with a
* {@code PrivateKeyEntry},
* then the given certificate is compared to the first
* element of that entry's certificate chain.
*
* @param cert the certificate to match with.
*
* @return the alias name of the first entry with matching certificate,
* or null if no such entry exists in this keystore.
*/
public abstract String engineGetCertificateAlias(Certificate cert);
/**
* Stores this keystore to the given output stream, and protects its
* integrity with the given password.
*
* @param stream the output stream to which this keystore is written.
* @param password the password to generate the keystore integrity check
*
* @exception IOException if there was an I/O problem with data
* @exception NoSuchAlgorithmException if the appropriate data integrity
* algorithm could not be found
* @exception CertificateException if any of the certificates included in
* the keystore data could not be stored
*/
public abstract void engineStore(OutputStream stream, char[] password)
throws IOException, NoSuchAlgorithmException, CertificateException;
/**
* Stores this keystore using the given
* {@code KeyStore.LoadStoreParmeter}.
*
* @param param the {@code KeyStore.LoadStoreParmeter}
* that specifies how to store the keystore,
* which may be {@code null}
*
* @exception IllegalArgumentException if the given
* {@code KeyStore.LoadStoreParmeter}
* input is not recognized
* @exception IOException if there was an I/O problem with data
* @exception NoSuchAlgorithmException if the appropriate data integrity
* algorithm could not be found
* @exception CertificateException if any of the certificates included in
* the keystore data could not be stored
*
* @since 1.5
*/
public void engineStore(KeyStore.LoadStoreParameter param)
throws IOException, NoSuchAlgorithmException,
CertificateException {
throw new UnsupportedOperationException();
}
/**
* Loads the keystore from the given input stream.
*
* A password may be given to unlock the keystore
* (e.g. the keystore resides on a hardware token device),
* or to check the integrity of the keystore data.
* If a password is not given for integrity checking,
* then integrity checking is not performed.
*
* @param stream the input stream from which the keystore is loaded,
* or {@code null}
* @param password the password used to check the integrity of
* the keystore, the password used to unlock the keystore,
* or {@code null}
*
* @exception IOException if there is an I/O or format problem with the
* keystore data, if a password is required but not given,
* or if the given password was incorrect. If the error is due to a
* wrong password, the {@link Throwable#getCause cause} of the
* {@code IOException} should be an
* {@code UnrecoverableKeyException}
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*/
public abstract void engineLoad(InputStream stream, char[] password)
throws IOException, NoSuchAlgorithmException, CertificateException;
/**
* Loads the keystore using the given
* {@code KeyStore.LoadStoreParameter}.
*
* Note that if this KeyStore has already been loaded, it is
* reinitialized and loaded again from the given parameter.
*
* @param param the {@code KeyStore.LoadStoreParameter}
* that specifies how to load the keystore,
* which may be {@code null}
*
* @exception IllegalArgumentException if the given
* {@code KeyStore.LoadStoreParameter}
* input is not recognized
* @exception IOException if there is an I/O or format problem with the
* keystore data. If the error is due to an incorrect
* {@code ProtectionParameter} (e.g. wrong password)
* the {@link Throwable#getCause cause} of the
* {@code IOException} should be an
* {@code UnrecoverableKeyException}
* @exception NoSuchAlgorithmException if the algorithm used to check
* the integrity of the keystore cannot be found
* @exception CertificateException if any of the certificates in the
* keystore could not be loaded
*
* @since 1.5
*/
public void engineLoad(KeyStore.LoadStoreParameter param)
throws IOException, NoSuchAlgorithmException,
CertificateException {
if (param == null) {
engineLoad((InputStream)null, (char[])null);
return;
}
if (param instanceof KeyStore.SimpleLoadStoreParameter) {
ProtectionParameter protection = param.getProtectionParameter();
char[] password;
if (protection instanceof PasswordProtection) {
password = ((PasswordProtection)protection).getPassword();
} else if (protection instanceof CallbackHandlerProtection) {
CallbackHandler handler =
((CallbackHandlerProtection)protection).getCallbackHandler();
PasswordCallback callback =
new PasswordCallback("Password: ", false);
try {
handler.handle(new Callback[] {callback});
} catch (UnsupportedCallbackException e) {
throw new NoSuchAlgorithmException
("Could not obtain password", e);
}
password = callback.getPassword();
callback.clearPassword();
if (password == null) {
throw new NoSuchAlgorithmException
("No password provided");
}
} else {
throw new NoSuchAlgorithmException("ProtectionParameter must"
+ " be PasswordProtection or CallbackHandlerProtection");
}
engineLoad(null, password);
return;
}
throw new UnsupportedOperationException();
}
/**
* Gets a {@code KeyStore.Entry} for the specified alias
* with the specified protection parameter.
*
* @param alias get the {@code KeyStore.Entry} for this alias
* @param protParam the {@code ProtectionParameter}
* used to protect the {@code Entry},
* which may be {@code null}
*
* @return the {@code KeyStore.Entry} for the specified alias,
* or {@code null} if there is no such entry
*
* @exception KeyStoreException if the operation failed
* @exception NoSuchAlgorithmException if the algorithm for recovering the
* entry cannot be found
* @exception UnrecoverableEntryException if the specified
* {@code protParam} were insufficient or invalid
* @exception UnrecoverableKeyException if the entry is a
* {@code PrivateKeyEntry} or {@code SecretKeyEntry}
* and the specified {@code protParam} does not contain
* the information needed to recover the key (e.g. wrong password)
*
* @since 1.5
*/
public KeyStore.Entry engineGetEntry(String alias,
KeyStore.ProtectionParameter protParam)
throws KeyStoreException, NoSuchAlgorithmException,
UnrecoverableEntryException {
if (!engineContainsAlias(alias)) {
return null;
}
if (protParam == null) {
if (engineIsCertificateEntry(alias)) {
return new KeyStore.TrustedCertificateEntry
(engineGetCertificate(alias));
} else {
throw new UnrecoverableKeyException
("requested entry requires a password");
}
}
if (protParam instanceof KeyStore.PasswordProtection) {
if (engineIsCertificateEntry(alias)) {
throw new UnsupportedOperationException
("trusted certificate entries are not password-protected");
} else if (engineIsKeyEntry(alias)) {
KeyStore.PasswordProtection pp =
(KeyStore.PasswordProtection)protParam;
char[] password = pp.getPassword();
Key key = engineGetKey(alias, password);
if (key instanceof PrivateKey) {
Certificate[] chain = engineGetCertificateChain(alias);
return new KeyStore.PrivateKeyEntry((PrivateKey)key, chain);
} else if (key instanceof SecretKey) {
return new KeyStore.SecretKeyEntry((SecretKey)key);
}
}
}
throw new UnsupportedOperationException();
}
/**
* Saves a {@code KeyStore.Entry} under the specified alias.
* The specified protection parameter is used to protect the
* {@code Entry}.
*
* If an entry already exists for the specified alias,
* it is overridden.
*
* @param alias save the {@code KeyStore.Entry} under this alias
* @param entry the {@code Entry} to save
* @param protParam the {@code ProtectionParameter}
* used to protect the {@code Entry},
* which may be {@code null}
*
* @exception KeyStoreException if this operation fails
*
* @since 1.5
*/
public void engineSetEntry(String alias, KeyStore.Entry entry,
KeyStore.ProtectionParameter protParam)
throws KeyStoreException {
// get password
if (protParam != null &&
!(protParam instanceof KeyStore.PasswordProtection)) {
throw new KeyStoreException("unsupported protection parameter");
}
KeyStore.PasswordProtection pProtect = null;
if (protParam != null) {
pProtect = (KeyStore.PasswordProtection)protParam;
}
// set entry
if (entry instanceof KeyStore.TrustedCertificateEntry) {
if (protParam != null && pProtect.getPassword() != null) {
// pre-1.5 style setCertificateEntry did not allow password
throw new KeyStoreException
("trusted certificate entries are not password-protected");
} else {
KeyStore.TrustedCertificateEntry tce =
(KeyStore.TrustedCertificateEntry)entry;
engineSetCertificateEntry(alias, tce.getTrustedCertificate());
return;
}
} else if (entry instanceof KeyStore.PrivateKeyEntry) {
if (pProtect == null || pProtect.getPassword() == null) {
// pre-1.5 style setKeyEntry required password
throw new KeyStoreException
("non-null password required to create PrivateKeyEntry");
} else {
engineSetKeyEntry
(alias,
((KeyStore.PrivateKeyEntry)entry).getPrivateKey(),
pProtect.getPassword(),
((KeyStore.PrivateKeyEntry)entry).getCertificateChain());
return;
}
} else if (entry instanceof KeyStore.SecretKeyEntry) {
if (pProtect == null || pProtect.getPassword() == null) {
// pre-1.5 style setKeyEntry required password
throw new KeyStoreException
("non-null password required to create SecretKeyEntry");
} else {
engineSetKeyEntry
(alias,
((KeyStore.SecretKeyEntry)entry).getSecretKey(),
pProtect.getPassword(),
(Certificate[])null);
return;
}
}
throw new KeyStoreException
("unsupported entry type: " + entry.getClass().getName());
}
/**
* Determines if the keystore {@code Entry} for the specified
* {@code alias} is an instance or subclass of the specified
* {@code entryClass}.
*
* @param alias the alias name
* @param entryClass the entry class
*
* @return true if the keystore {@code Entry} for the specified
* {@code alias} is an instance or subclass of the
* specified {@code entryClass}, false otherwise
*
* @since 1.5
*/
public boolean
engineEntryInstanceOf(String alias,
Class extends KeyStore.Entry> entryClass)
{
if (entryClass == KeyStore.TrustedCertificateEntry.class) {
return engineIsCertificateEntry(alias);
}
if (entryClass == KeyStore.PrivateKeyEntry.class) {
return engineIsKeyEntry(alias) &&
engineGetCertificate(alias) != null;
}
if (entryClass == KeyStore.SecretKeyEntry.class) {
return engineIsKeyEntry(alias) &&
engineGetCertificate(alias) == null;
}
return false;
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 21630
Content-Disposition: inline; filename="MessageDigest.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "a72de0ca21a715b87595d4dad19cb55389604c96"
/*
* Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.util.*;
import java.lang.*;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.nio.ByteBuffer;
import sun.security.util.Debug;
/**
* This MessageDigest class provides applications the functionality of a
* message digest algorithm, such as SHA-1 or SHA-256.
* Message digests are secure one-way hash functions that take arbitrary-sized
* data and output a fixed-length hash value.
*
* A MessageDigest object starts out initialized. The data is
* processed through it using the {@link #update(byte) update}
* methods. At any point {@link #reset() reset} can be called
* to reset the digest. Once all the data to be updated has been
* updated, one of the {@link #digest() digest} methods should
* be called to complete the hash computation.
*
* The {@code digest} method can be called once for a given number
* of updates. After {@code digest} has been called, the MessageDigest
* object is reset to its initialized state.
*
* Implementations are free to implement the Cloneable interface.
* Client applications can test cloneability by attempting cloning
* and catching the CloneNotSupportedException:
*
* Note that if a given implementation is not cloneable, it is
* still possible to compute intermediate digests by instantiating
* several instances, if the number of digests is known in advance.
*
* Note that this class is abstract and extends from
* {@code MessageDigestSpi} for historical reasons.
* Application developers should only take notice of the methods defined in
* this {@code MessageDigest} class; all the methods in
* the superclass are intended for cryptographic service providers who wish to
* supply their own implementations of message digest algorithms.
*
* Every implementation of the Java platform is required to support
* the following standard {@code MessageDigest} algorithms:
* This method traverses the list of registered security Providers,
* starting with the most preferred Provider.
* A new MessageDigest object encapsulating the
* MessageDigestSpi implementation from the first
* Provider that supports the specified algorithm is returned.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the name of the algorithm requested.
* See the MessageDigest section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @return a Message Digest object that implements the specified algorithm.
*
* @exception NoSuchAlgorithmException if no Provider supports a
* MessageDigestSpi implementation for the
* specified algorithm.
*
* @see Provider
*/
public static MessageDigest getInstance(String algorithm)
throws NoSuchAlgorithmException {
try {
MessageDigest md;
Object[] objs = Security.getImpl(algorithm, "MessageDigest",
(String)null);
if (objs[0] instanceof MessageDigest) {
md = (MessageDigest)objs[0];
} else {
md = new Delegate((MessageDigestSpi)objs[0], algorithm);
}
md.provider = (Provider)objs[1];
if (!skipDebug && pdebug != null) {
pdebug.println("MessageDigest." + algorithm +
" algorithm from: " + md.provider.getName());
}
return md;
} catch(NoSuchProviderException e) {
throw new NoSuchAlgorithmException(algorithm + " not found");
}
}
/**
* Returns a MessageDigest object that implements the specified digest
* algorithm.
*
* A new MessageDigest object encapsulating the
* MessageDigestSpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the security provider list.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param algorithm the name of the algorithm requested.
* See the MessageDigest section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the name of the provider.
*
* @return a MessageDigest object that implements the specified algorithm.
*
* @exception NoSuchAlgorithmException if a MessageDigestSpi
* implementation for the specified algorithm is not
* available from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception IllegalArgumentException if the provider name is null
* or empty.
*
* @see Provider
*/
public static MessageDigest getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException
{
if (provider == null || provider.length() == 0)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
if (objs[0] instanceof MessageDigest) {
MessageDigest md = (MessageDigest)objs[0];
md.provider = (Provider)objs[1];
return md;
} else {
MessageDigest delegate =
new Delegate((MessageDigestSpi)objs[0], algorithm);
delegate.provider = (Provider)objs[1];
return delegate;
}
}
/**
* Returns a MessageDigest object that implements the specified digest
* algorithm.
*
* A new MessageDigest object encapsulating the
* MessageDigestSpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param algorithm the name of the algorithm requested.
* See the MessageDigest section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @param provider the provider.
*
* @return a MessageDigest object that implements the specified algorithm.
*
* @exception NoSuchAlgorithmException if a MessageDigestSpi
* implementation for the specified algorithm is not available
* from the specified Provider object.
*
* @exception IllegalArgumentException if the specified provider is null.
*
* @see Provider
*
* @since 1.4
*/
public static MessageDigest getInstance(String algorithm,
Provider provider)
throws NoSuchAlgorithmException
{
if (provider == null)
throw new IllegalArgumentException("missing provider");
Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
if (objs[0] instanceof MessageDigest) {
MessageDigest md = (MessageDigest)objs[0];
md.provider = (Provider)objs[1];
return md;
} else {
MessageDigest delegate =
new Delegate((MessageDigestSpi)objs[0], algorithm);
delegate.provider = (Provider)objs[1];
return delegate;
}
}
/**
* Returns the provider of this message digest object.
*
* @return the provider of this message digest object
*/
public final Provider getProvider() {
return this.provider;
}
/**
* Updates the digest using the specified byte.
*
* @param input the byte with which to update the digest.
*/
public void update(byte input) {
engineUpdate(input);
state = IN_PROGRESS;
}
/**
* Updates the digest using the specified array of bytes, starting
* at the specified offset.
*
* @param input the array of bytes.
*
* @param offset the offset to start from in the array of bytes.
*
* @param len the number of bytes to use, starting at
* {@code offset}.
*/
public void update(byte[] input, int offset, int len) {
if (input == null) {
throw new IllegalArgumentException("No input buffer given");
}
if (input.length - offset < len) {
throw new IllegalArgumentException("Input buffer too short");
}
engineUpdate(input, offset, len);
state = IN_PROGRESS;
}
/**
* Updates the digest using the specified array of bytes.
*
* @param input the array of bytes.
*/
public void update(byte[] input) {
engineUpdate(input, 0, input.length);
state = IN_PROGRESS;
}
/**
* Update the digest using the specified ByteBuffer. The digest is
* updated using the {@code input.remaining()} bytes starting
* at {@code input.position()}.
* Upon return, the buffer's position will be equal to its limit;
* its limit will not have changed.
*
* @param input the ByteBuffer
* @since 1.5
*/
public final void update(ByteBuffer input) {
if (input == null) {
throw new NullPointerException();
}
engineUpdate(input);
state = IN_PROGRESS;
}
/**
* Completes the hash computation by performing final operations
* such as padding. The digest is reset after this call is made.
*
* @return the array of bytes for the resulting hash value.
*/
public byte[] digest() {
/* Resetting is the responsibility of implementors. */
byte[] result = engineDigest();
state = INITIAL;
return result;
}
/**
* Completes the hash computation by performing final operations
* such as padding. The digest is reset after this call is made.
*
* @param buf output buffer for the computed digest
*
* @param offset offset into the output buffer to begin storing the digest
*
* @param len number of bytes within buf allotted for the digest
*
* @return the number of bytes placed into {@code buf}
*
* @exception DigestException if an error occurs.
*/
public int digest(byte[] buf, int offset, int len) throws DigestException {
if (buf == null) {
throw new IllegalArgumentException("No output buffer given");
}
if (buf.length - offset < len) {
throw new IllegalArgumentException
("Output buffer too small for specified offset and length");
}
int numBytes = engineDigest(buf, offset, len);
state = INITIAL;
return numBytes;
}
/**
* Performs a final update on the digest using the specified array
* of bytes, then completes the digest computation. That is, this
* method first calls {@link #update(byte[]) update(input)},
* passing the input array to the {@code update} method,
* then calls {@link #digest() digest()}.
*
* @param input the input to be updated before the digest is
* completed.
*
* @return the array of bytes for the resulting hash value.
*/
public byte[] digest(byte[] input) {
update(input);
return digest();
}
/**
* Returns a string representation of this message digest object.
*/
public String toString() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream p = new PrintStream(baos);
p.print(algorithm+" Message Digest from "+provider.getName()+", ");
switch (state) {
case INITIAL:
p.print(" All the abstract methods in this class must be implemented by a
* cryptographic service provider who wishes to supply the implementation
* of a particular message digest algorithm.
*
* Implementations are free to implement the Cloneable interface.
*
* @author Benjamin Renaud
*
*
* @see MessageDigest
*/
public abstract class MessageDigestSpi {
// for re-use in engineUpdate(ByteBuffer input)
private byte[] tempArray;
/**
* Returns the digest length in bytes.
*
* This concrete method has been added to this previously-defined
* abstract class. (For backwards compatibility, it cannot be abstract.)
*
* The default behavior is to return 0.
*
* This method may be overridden by a provider to return the digest
* length.
*
* @return the digest length in bytes.
*
* @since 1.2
*/
protected int engineGetDigestLength() {
return 0;
}
/**
* Updates the digest using the specified byte.
*
* @param input the byte to use for the update.
*/
protected abstract void engineUpdate(byte input);
/**
* Updates the digest using the specified array of bytes,
* starting at the specified offset.
*
* @param input the array of bytes to use for the update.
*
* @param offset the offset to start from in the array of bytes.
*
* @param len the number of bytes to use, starting at
* {@code offset}.
*/
protected abstract void engineUpdate(byte[] input, int offset, int len);
/**
* Update the digest using the specified ByteBuffer. The digest is
* updated using the {@code input.remaining()} bytes starting
* at {@code input.position()}.
* Upon return, the buffer's position will be equal to its limit;
* its limit will not have changed.
*
* @param input the ByteBuffer
* @since 1.5
*/
protected void engineUpdate(ByteBuffer input) {
if (input.hasRemaining() == false) {
return;
}
if (input.hasArray()) {
byte[] b = input.array();
int ofs = input.arrayOffset();
int pos = input.position();
int lim = input.limit();
engineUpdate(b, ofs + pos, lim - pos);
input.position(lim);
} else {
int len = input.remaining();
int n = JCAUtil.getTempArraySize(len);
if ((tempArray == null) || (n > tempArray.length)) {
tempArray = new byte[n];
}
while (len > 0) {
int chunk = Math.min(len, tempArray.length);
input.get(tempArray, 0, chunk);
engineUpdate(tempArray, 0, chunk);
len -= chunk;
}
}
}
/**
* Completes the hash computation by performing final
* operations such as padding. Once {@code engineDigest} has
* been called, the engine should be reset (see
* {@link #engineReset() engineReset}).
* Resetting is the responsibility of the
* engine implementor.
*
* @return the array of bytes for the resulting hash value.
*/
protected abstract byte[] engineDigest();
/**
* Completes the hash computation by performing final
* operations such as padding. Once {@code engineDigest} has
* been called, the engine should be reset (see
* {@link #engineReset() engineReset}).
* Resetting is the responsibility of the
* engine implementor.
*
* This method should be abstract, but we leave it concrete for
* binary compatibility. Knowledgeable providers should override this
* method.
*
* @param buf the output buffer in which to store the digest
*
* @param offset offset to start from in the output buffer
*
* @param len number of bytes within buf allotted for the digest.
* Both this default implementation and the SUN provider do not
* return partial digests. The presence of this parameter is solely
* for consistency in our API's. If the value of this parameter is less
* than the actual digest length, the method will throw a DigestException.
* This parameter is ignored if its value is greater than or equal to
* the actual digest length.
*
* @return the length of the digest stored in the output buffer.
*
* @exception DigestException if an error occurs.
*
* @since 1.2
*/
protected int engineDigest(byte[] buf, int offset, int len)
throws DigestException {
byte[] digest = engineDigest();
if (len < digest.length)
throw new DigestException("partial digests not returned");
if (buf.length - offset < digest.length)
throw new DigestException("insufficient space in the output "
+ "buffer to store the digest");
System.arraycopy(digest, 0, buf, offset, digest.length);
return digest.length;
}
/**
* Resets the digest for further use.
*/
protected abstract void engineReset();
/**
* Returns a clone if the implementation is cloneable.
*
* @return a clone if the implementation is cloneable.
*
* @exception CloneNotSupportedException if this is called on an
* implementation that does not support {@code Cloneable}.
*/
public Object clone() throws CloneNotSupportedException {
if (this instanceof Cloneable) {
return super.clone();
} else {
throw new CloneNotSupportedException();
}
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 3358
Content-Disposition: inline; filename="NoSuchAlgorithmException.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "951e44e41dcb031fc49db62aca2bc8ae249014d9"
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* This exception is thrown when a particular cryptographic algorithm is
* requested but is not available in the environment.
*
* @author Benjamin Renaud
*/
public class NoSuchAlgorithmException extends GeneralSecurityException {
private static final long serialVersionUID = -7443947487218346562L;
/**
* Constructs a NoSuchAlgorithmException with no detail
* message. A detail message is a String that describes this
* particular exception.
*/
public NoSuchAlgorithmException() {
super();
}
/**
* Constructs a NoSuchAlgorithmException with the specified
* detail message. A detail message is a String that describes
* this particular exception, which may, for example, specify which
* algorithm is not available.
*
* @param msg the detail message.
*/
public NoSuchAlgorithmException(String msg) {
super(msg);
}
/**
* Creates a {@code NoSuchAlgorithmException} with the specified
* detail message and cause.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @since 1.5
*/
public NoSuchAlgorithmException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a {@code NoSuchAlgorithmException} with the specified cause
* and a detail message of {@code (cause==null ? null : cause.toString())}
* (which typically contains the class and detail message of
* {@code cause}).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @since 1.5
*/
public NoSuchAlgorithmException(Throwable cause) {
super(cause);
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 2077
Content-Disposition: inline; filename="NoSuchProviderException.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "9874adb145e3f03321837a2a81f4a5ebc1ad7396"
/*
* Copyright (c) 1996, 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* This exception is thrown when a particular security provider is
* requested but is not available in the environment.
*
* @author Benjamin Renaud
*/
public class NoSuchProviderException extends GeneralSecurityException {
private static final long serialVersionUID = 8488111756688534474L;
/**
* Constructs a NoSuchProviderException with no detail message. A
* detail message is a String that describes this particular
* exception.
*/
public NoSuchProviderException() {
super();
}
/**
* Constructs a NoSuchProviderException with the specified detail
* message. A detail message is a String that describes this
* particular exception.
*
* @param msg the detail message.
*/
public NoSuchProviderException(String msg) {
super(msg);
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 10302
Content-Disposition: inline; filename="PKCS12Attribute.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "e3898628820fed51cd73575de5c11c4c7b4cb0b5"
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.regex.Pattern;
import sun.security.util.*;
/**
* An attribute associated with a PKCS12 keystore entry.
* The attribute name is an ASN.1 Object Identifier and the attribute
* value is a set of ASN.1 types.
*
* @since 1.8
*/
public final class PKCS12Attribute implements KeyStore.Entry.Attribute {
private static final Pattern COLON_SEPARATED_HEX_PAIRS =
Pattern.compile("^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2})+$");
private String name;
private String value;
private byte[] encoded;
private int hashValue = -1;
/**
* Constructs a PKCS12 attribute from its name and value.
* The name is an ASN.1 Object Identifier represented as a list of
* dot-separated integers.
* A string value is represented as the string itself.
* A binary value is represented as a string of colon-separated
* pairs of hexadecimal digits.
* Multi-valued attributes are represented as a comma-separated
* list of values, enclosed in square brackets. See
* {@link Arrays#toString(java.lang.Object[])}.
*
* A string value will be DER-encoded as an ASN.1 UTF8String and a
* binary value will be DER-encoded as an ASN.1 Octet String.
*
* @param name the attribute's identifier
* @param value the attribute's value
*
* @exception NullPointerException if {@code name} or {@code value}
* is {@code null}
* @exception IllegalArgumentException if {@code name} or
* {@code value} is incorrectly formatted
*/
public PKCS12Attribute(String name, String value) {
if (name == null || value == null) {
throw new NullPointerException();
}
// Validate name
ObjectIdentifier type;
try {
type = new ObjectIdentifier(name);
} catch (IOException e) {
throw new IllegalArgumentException("Incorrect format: name", e);
}
this.name = name;
// Validate value
int length = value.length();
String[] values;
if (value.charAt(0) == '[' && value.charAt(length - 1) == ']') {
values = value.substring(1, length - 1).split(", ");
} else {
values = new String[]{ value };
}
this.value = value;
try {
this.encoded = encode(type, values);
} catch (IOException e) {
throw new IllegalArgumentException("Incorrect format: value", e);
}
}
/**
* Constructs a PKCS12 attribute from its ASN.1 DER encoding.
* The DER encoding is specified by the following ASN.1 definition:
* Most Permission objects also include an "actions" list that tells the actions
* that are permitted for the object. For example,
* for a {@code java.io.FilePermission} object, the permission name is
* the pathname of a file (or directory), and the actions list
* (such as "read, write") specifies which actions are granted for the
* specified file (or for files in the specified directory).
* The actions list is optional for Permission objects, such as
* {@code java.lang.RuntimePermission},
* that don't need such a list; you either have the named permission (such
* as "system.exit") or you don't.
*
* An important method that must be implemented by each subclass is
* the {@code implies} method to compare Permissions. Basically,
* "permission p1 implies permission p2" means that
* if one is granted permission p1, one is naturally granted permission p2.
* Thus, this is not an equality test, but rather more of a
* subset test.
*
* Permission objects are similar to String objects in that they
* are immutable once they have been created. Subclasses should not
* provide methods that can change the state of a permission
* once it has been created.
*
* @see Permissions
* @see PermissionCollection
*
*
* @author Marianne Mueller
* @author Roland Schemers
*/
public abstract class Permission implements Guard, java.io.Serializable {
private static final long serialVersionUID = -5636570222231596674L;
private String name;
/**
* Constructs a permission with the specified name.
*
* @param name name of the Permission object being created.
*
*/
public Permission(String name) {
this.name = name;
}
/**
* Implements the guard interface for a permission. The
* {@code SecurityManager.checkPermission} method is called,
* passing this permission object as the permission to check.
* Returns silently if access is granted. Otherwise, throws
* a SecurityException.
*
* @param object the object being guarded (currently ignored).
*
* @throws SecurityException
* if a security manager exists and its
* {@code checkPermission} method doesn't allow access.
*
* @see Guard
* @see GuardedObject
* @see SecurityManager#checkPermission
*
*/
public void checkGuard(Object object) throws SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) sm.checkPermission(this);
}
/**
* Checks if the specified permission's actions are "implied by"
* this object's actions.
*
* This must be implemented by subclasses of Permission, as they are the
* only ones that can impose semantics on a Permission object.
*
* The {@code implies} method is used by the AccessController to determine
* whether or not a requested permission is implied by another permission that
* is known to be valid in the current execution context.
*
* @param permission the permission to check against.
*
* @return true if the specified permission is implied by this object,
* false if not.
*/
public abstract boolean implies(Permission permission);
/**
* Checks two Permission objects for equality.
*
* Do not use the {@code equals} method for making access control
* decisions; use the {@code implies} method.
*
* @param obj the object we are testing for equality with this object.
*
* @return true if both Permission objects are equivalent.
*/
public abstract boolean equals(Object obj);
/**
* Returns the hash code value for this Permission object.
*
* The required {@code hashCode} behavior for Permission Objects is
* the following:
* With a PermissionCollection, you can:
* When it is desirable to group together a number of Permission objects
* of the same type, the {@code newPermissionCollection} method on that
* particular type of Permission object should first be called. The default
* behavior (from the Permission class) is to simply return null.
* Subclasses of class Permission override the method if they need to store
* their permissions in a particular PermissionCollection object in order
* to provide the correct semantics when the
* {@code PermissionCollection.implies} method is called.
* If a non-null value is returned, that PermissionCollection must be used.
* If null is returned, then the caller of {@code newPermissionCollection}
* is free to store permissions of the
* given type in any PermissionCollection they choose
* (one that uses a Hashtable, one that uses a Vector, etc).
*
* The PermissionCollection returned by the
* {@code Permission.newPermissionCollection}
* method is a homogeneous collection, which stores only Permission objects
* for a given Permission type. A PermissionCollection may also be
* heterogeneous. For example, Permissions is a PermissionCollection
* subclass that represents a collection of PermissionCollections.
* That is, its members are each a homogeneous PermissionCollection.
* For example, a Permissions object might have a FilePermissionCollection
* for all the FilePermission objects, a SocketPermissionCollection for all the
* SocketPermission objects, and so on. Its {@code add} method adds a
* permission to the appropriate collection.
*
* Whenever a permission is added to a heterogeneous PermissionCollection
* such as Permissions, and the PermissionCollection doesn't yet contain a
* PermissionCollection of the specified permission's type, the
* PermissionCollection should call
* the {@code newPermissionCollection} method on the permission's class
* to see if it requires a special PermissionCollection. If
* {@code newPermissionCollection}
* returns null, the PermissionCollection
* is free to store the permission in any type of PermissionCollection it
* desires (one using a Hashtable, one using a Vector, etc.). For example,
* the Permissions object uses a default PermissionCollection implementation
* that stores the permission objects in a Hashtable.
*
* Subclass implementations of PermissionCollection should assume
* that they may be called simultaneously from multiple threads,
* and therefore should be synchronized properly. Furthermore,
* Enumerations returned via the {@code elements} method are
* not fail-fast. Modifications to a collection should not be
* performed while enumerating over that collection.
*
* @see Permission
* @see Permissions
*
*
* @author Roland Schemers
*/
public abstract class PermissionCollection implements java.io.Serializable {
private static final long serialVersionUID = -6727011328946861783L;
// when set, add will throw an exception.
private volatile boolean readOnly;
/**
* Adds a permission object to the current collection of permission objects.
*
* @param permission the Permission object to add.
*
* @exception SecurityException - if this PermissionCollection object
* has been marked readonly
* @exception IllegalArgumentException - if this PermissionCollection
* object is a homogeneous collection and the permission
* is not of the correct type.
*/
public abstract void add(Permission permission);
/**
* Checks to see if the specified permission is implied by
* the collection of Permission objects held in this PermissionCollection.
*
* @param permission the Permission object to compare.
*
* @return true if "permission" is implied by the permissions in
* the collection, false if not.
*/
public abstract boolean implies(Permission permission);
/**
* Returns an enumeration of all the Permission objects in the collection.
*
* @return an enumeration of all the Permissions.
*/
public abstract Enumeration By default, the object is not readonly. It can be set to
* readonly by a call to {@code setReadOnly}.
*
* @return true if this PermissionCollection object is marked as readonly,
* false otherwise.
*/
public boolean isReadOnly() {
return readOnly;
}
/**
* Returns a string describing this PermissionCollection object,
* providing information about all the permissions it contains.
* The format is:
* When the {@code add} method is called to add a Permission, the
* Permission is stored in the appropriate PermissionCollection. If no such
* collection exists yet, the Permission object's class is determined and the
* {@code newPermissionCollection} method is called on that class to create
* the PermissionCollection and add it to the Permissions object. If
* {@code newPermissionCollection} returns null, then a default
* PermissionCollection that uses a hashtable will be created and used. Each
* hashtable entry stores a Permission object as both the key and the value.
*
* Enumerations returned via the {@code elements} method are
* not fail-fast. Modifications to a collection should not be
* performed while enumerating over that collection.
*
* @see Permission
* @see PermissionCollection
* @see AllPermission
*
*
* @author Marianne Mueller
* @author Roland Schemers
*
* @serial exclude
*/
public final class Permissions extends PermissionCollection
implements Serializable
{
/**
* Key is permissions Class, value is PermissionCollection for that class.
* Not serialized; see serialization section at end of class.
*/
private transient Map
*
* @param permission the Permission object to add.
*
* @exception SecurityException if this Permissions object is
* marked as readonly.
*
* @see PermissionCollection#isReadOnly()
*/
public void add(Permission permission) {
if (isReadOnly())
throw new SecurityException(
"attempt to add a Permission to a readonly Permissions object");
PermissionCollection pc;
synchronized (this) {
pc = getPermissionCollection(permission, true);
pc.add(permission);
}
// No sync; staleness -> optimizations delayed, which is OK
if (permission instanceof AllPermission) {
allPermission = pc;
}
if (permission instanceof UnresolvedPermission) {
hasUnresolved = true;
}
}
/**
* Checks to see if this object's PermissionCollection for permissions of
* the specified permission's class implies the permissions
* expressed in the permission object. Returns true if the
* combination of permissions in the appropriate PermissionCollection
* (e.g., a FilePermissionCollection for a FilePermission) together
* imply the specified permission.
*
* For example, suppose there is a FilePermissionCollection in this
* Permissions object, and it contains one FilePermission that specifies
* "read" access for all files in all subdirectories of the "/tmp"
* directory, and another FilePermission that specifies "write" access
* for all files in the "/tmp/scratch/foo" directory.
* Then if the {@code implies} method
* is called with a permission specifying both "read" and "write" access
* to files in the "/tmp/scratch/foo" directory, {@code true} is
* returned.
*
* Additionally, if this PermissionCollection contains the
* AllPermission, this method will always return true.
*
* @param permission the Permission object to check.
*
* @return true if "permission" is implied by the permissions in the
* PermissionCollection it
* belongs to, false if not.
*/
public boolean implies(Permission permission) {
// No sync; staleness -> skip optimization, which is OK
if (allPermission != null) {
return true; // AllPermission has already been added
} else {
synchronized (this) {
PermissionCollection pc = getPermissionCollection(permission,
false);
if (pc != null) {
return pc.implies(permission);
} else {
// none found
return false;
}
}
}
}
/**
* Returns an enumeration of all the Permission objects in all the
* PermissionCollections in this Permissions object.
*
* @return an enumeration of all the Permissions.
*/
public Enumeration There is only one Policy object installed in the runtime at any
* given time. A Policy object can be installed by calling the
* {@code setPolicy} method. The installed Policy object can be
* obtained by calling the {@code getPolicy} method.
*
* If no Policy object has been installed in the runtime, a call to
* {@code getPolicy} installs an instance of the default Policy
* implementation (a default subclass implementation of this abstract class).
* The default Policy implementation can be changed by setting the value
* of the {@code policy.provider} security property to the fully qualified
* name of the desired Policy subclass implementation.
*
* Application code can directly subclass Policy to provide a custom
* implementation. In addition, an instance of a Policy object can be
* constructed by invoking one of the {@code getInstance} factory methods
* with a standard type. The default policy type is "JavaPolicy".
*
* Once a Policy instance has been installed (either by default, or by
* calling {@code setPolicy}), the Java runtime invokes its
* {@code implies} method when it needs to
* determine whether executing code (encapsulated in a ProtectionDomain)
* can perform SecurityManager-protected operations. How a Policy object
* retrieves its policy data is up to the Policy implementation itself.
* The policy data may be stored, for example, in a flat ASCII file,
* in a serialized binary file of the Policy class, or in a database.
*
* The {@code refresh} method causes the policy object to
* refresh/reload its data. This operation is implementation-dependent.
* For example, if the policy object stores its data in configuration files,
* calling {@code refresh} will cause it to re-read the configuration
* policy files. If a refresh operation is not supported, this method does
* nothing. Note that refreshed policy may not have an effect on classes
* in a particular ProtectionDomain. This is dependent on the Policy
* provider's implementation of the {@code implies}
* method and its PermissionCollection caching strategy.
*
* @author Roland Schemers
* @author Gary Ellison
* @see java.security.Provider
* @see java.security.ProtectionDomain
* @see java.security.Permission
* @see java.security.Security security properties
*/
public abstract class Policy {
/**
* A read-only empty PermissionCollection instance.
* @since 1.6
*/
public static final PermissionCollection UNSUPPORTED_EMPTY_COLLECTION =
new UnsupportedEmptyCollection();
// Information about the system-wide policy.
private static class PolicyInfo {
// the system-wide policy
final Policy policy;
// a flag indicating if the system-wide policy has been initialized
final boolean initialized;
PolicyInfo(Policy policy, boolean initialized) {
this.policy = policy;
this.initialized = initialized;
}
}
// PolicyInfo is stored in an AtomicReference
private static AtomicReference This method traverses the list of registered security providers,
* starting with the most preferred Provider.
* A new Policy object encapsulating the
* PolicySpi implementation from the first
* Provider that supports the specified type is returned.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param type the specified Policy type. See the Policy section in the
*
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for a list of standard Policy types.
*
* @param params parameters for the Policy, which may be null.
*
* @return the new Policy object.
*
* @exception SecurityException if the caller does not have permission
* to get a Policy instance for the specified type.
*
* @exception NullPointerException if the specified type is null.
*
* @exception IllegalArgumentException if the specified parameters
* are not understood by the PolicySpi implementation
* from the selected Provider.
*
* @exception NoSuchAlgorithmException if no Provider supports a PolicySpi
* implementation for the specified type.
*
* @see Provider
* @since 1.6
*/
public static Policy getInstance(String type, Policy.Parameters params)
throws NoSuchAlgorithmException {
checkPermission(type);
try {
GetInstance.Instance instance = GetInstance.getInstance("Policy",
PolicySpi.class,
type,
params);
return new PolicyDelegate((PolicySpi)instance.impl,
instance.provider,
type,
params);
} catch (NoSuchAlgorithmException nsae) {
return handleException(nsae);
}
}
/**
* Returns a Policy object of the specified type.
*
* A new Policy object encapsulating the
* PolicySpi implementation from the specified provider
* is returned. The specified provider must be registered
* in the provider list.
*
* Note that the list of registered providers may be retrieved via
* the {@link Security#getProviders() Security.getProviders()} method.
*
* @param type the specified Policy type. See the Policy section in the
*
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for a list of standard Policy types.
*
* @param params parameters for the Policy, which may be null.
*
* @param provider the provider.
*
* @return the new Policy object.
*
* @exception SecurityException if the caller does not have permission
* to get a Policy instance for the specified type.
*
* @exception NullPointerException if the specified type is null.
*
* @exception IllegalArgumentException if the specified provider
* is null or empty,
* or if the specified parameters are not understood by
* the PolicySpi implementation from the specified provider.
*
* @exception NoSuchProviderException if the specified provider is not
* registered in the security provider list.
*
* @exception NoSuchAlgorithmException if the specified provider does not
* support a PolicySpi implementation for the specified type.
*
* @see Provider
* @since 1.6
*/
public static Policy getInstance(String type,
Policy.Parameters params,
String provider)
throws NoSuchProviderException, NoSuchAlgorithmException {
if (provider == null || provider.length() == 0) {
throw new IllegalArgumentException("missing provider");
}
checkPermission(type);
try {
GetInstance.Instance instance = GetInstance.getInstance("Policy",
PolicySpi.class,
type,
params,
provider);
return new PolicyDelegate((PolicySpi)instance.impl,
instance.provider,
type,
params);
} catch (NoSuchAlgorithmException nsae) {
return handleException(nsae);
}
}
/**
* Returns a Policy object of the specified type.
*
* A new Policy object encapsulating the
* PolicySpi implementation from the specified Provider
* object is returned. Note that the specified Provider object
* does not have to be registered in the provider list.
*
* @param type the specified Policy type. See the Policy section in the
*
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for a list of standard Policy types.
*
* @param params parameters for the Policy, which may be null.
*
* @param provider the Provider.
*
* @return the new Policy object.
*
* @exception SecurityException if the caller does not have permission
* to get a Policy instance for the specified type.
*
* @exception NullPointerException if the specified type is null.
*
* @exception IllegalArgumentException if the specified Provider is null,
* or if the specified parameters are not understood by
* the PolicySpi implementation from the specified Provider.
*
* @exception NoSuchAlgorithmException if the specified Provider does not
* support a PolicySpi implementation for the specified type.
*
* @see Provider
* @since 1.6
*/
public static Policy getInstance(String type,
Policy.Parameters params,
Provider provider)
throws NoSuchAlgorithmException {
if (provider == null) {
throw new IllegalArgumentException("missing provider");
}
checkPermission(type);
try {
GetInstance.Instance instance = GetInstance.getInstance("Policy",
PolicySpi.class,
type,
params,
provider);
return new PolicyDelegate((PolicySpi)instance.impl,
instance.provider,
type,
params);
} catch (NoSuchAlgorithmException nsae) {
return handleException(nsae);
}
}
private static Policy handleException(NoSuchAlgorithmException nsae)
throws NoSuchAlgorithmException {
Throwable cause = nsae.getCause();
if (cause instanceof IllegalArgumentException) {
throw (IllegalArgumentException)cause;
}
throw nsae;
}
/**
* Return the Provider of this Policy.
*
* This Policy instance will only have a Provider if it
* was obtained via a call to {@code Policy.getInstance}.
* Otherwise this method returns null.
*
* @return the Provider of this Policy, or null.
*
* @since 1.6
*/
public Provider getProvider() {
return null;
}
/**
* Return the type of this Policy.
*
* This Policy instance will only have a type if it
* was obtained via a call to {@code Policy.getInstance}.
* Otherwise this method returns null.
*
* @return the type of this Policy, or null.
*
* @since 1.6
*/
public String getType() {
return null;
}
/**
* Return Policy parameters.
*
* This Policy instance will only have parameters if it
* was obtained via a call to {@code Policy.getInstance}.
* Otherwise this method returns null.
*
* @return Policy parameters, or null.
*
* @since 1.6
*/
public Policy.Parameters getParameters() {
return null;
}
/**
* Return a PermissionCollection object containing the set of
* permissions granted to the specified CodeSource.
*
* Applications are discouraged from calling this method
* since this operation may not be supported by all policy implementations.
* Applications should solely rely on the {@code implies} method
* to perform policy checks. If an application absolutely must call
* a getPermissions method, it should call
* {@code getPermissions(ProtectionDomain)}.
*
* The default implementation of this method returns
* Policy.UNSUPPORTED_EMPTY_COLLECTION. This method can be
* overridden if the policy implementation can return a set of
* permissions granted to a CodeSource.
*
* @param codesource the CodeSource to which the returned
* PermissionCollection has been granted.
*
* @return a set of permissions granted to the specified CodeSource.
* If this operation is supported, the returned
* set of permissions must be a new mutable instance
* and it must support heterogeneous Permission types.
* If this operation is not supported,
* Policy.UNSUPPORTED_EMPTY_COLLECTION is returned.
*/
public PermissionCollection getPermissions(CodeSource codesource) {
return Policy.UNSUPPORTED_EMPTY_COLLECTION;
}
/**
* Return a PermissionCollection object containing the set of
* permissions granted to the specified ProtectionDomain.
*
* Applications are discouraged from calling this method
* since this operation may not be supported by all policy implementations.
* Applications should rely on the {@code implies} method
* to perform policy checks.
*
* The default implementation of this method first retrieves
* the permissions returned via {@code getPermissions(CodeSource)}
* (the CodeSource is taken from the specified ProtectionDomain),
* as well as the permissions located inside the specified ProtectionDomain.
* All of these permissions are then combined and returned in a new
* PermissionCollection object. If {@code getPermissions(CodeSource)}
* returns Policy.UNSUPPORTED_EMPTY_COLLECTION, then this method
* returns the permissions contained inside the specified ProtectionDomain
* in a new PermissionCollection object.
*
* This method can be overridden if the policy implementation
* supports returning a set of permissions granted to a ProtectionDomain.
*
* @param domain the ProtectionDomain to which the returned
* PermissionCollection has been granted.
*
* @return a set of permissions granted to the specified ProtectionDomain.
* If this operation is supported, the returned
* set of permissions must be a new mutable instance
* and it must support heterogeneous Permission types.
* If this operation is not supported,
* Policy.UNSUPPORTED_EMPTY_COLLECTION is returned.
*
* @since 1.4
*/
public PermissionCollection getPermissions(ProtectionDomain domain) {
PermissionCollection pc = null;
if (domain == null)
return new Permissions();
if (pdMapping == null) {
initPolicy(this);
}
synchronized (pdMapping) {
pc = pdMapping.get(domain.key);
}
if (pc != null) {
Permissions perms = new Permissions();
synchronized (pc) {
for (Enumeration The default implementation of this method does nothing.
* This method should be overridden if a refresh operation is supported
* by the policy implementation.
*/
public void refresh() { }
/**
* This subclass is returned by the getInstance calls. All Policy calls
* are delegated to the underlying PolicySpi.
*/
private static class PolicyDelegate extends Policy {
private PolicySpi spi;
private Provider p;
private String type;
private Policy.Parameters params;
private PolicyDelegate(PolicySpi spi, Provider p,
String type, Policy.Parameters params) {
this.spi = spi;
this.p = p;
this.type = type;
this.params = params;
}
@Override public String getType() { return type; }
@Override public Policy.Parameters getParameters() { return params; }
@Override public Provider getProvider() { return p; }
@Override
public PermissionCollection getPermissions(CodeSource codesource) {
return spi.engineGetPermissions(codesource);
}
@Override
public PermissionCollection getPermissions(ProtectionDomain domain) {
return spi.engineGetPermissions(domain);
}
@Override
public boolean implies(ProtectionDomain domain, Permission perm) {
return spi.engineImplies(domain, perm);
}
@Override
public void refresh() {
spi.engineRefresh();
}
}
/**
* This represents a marker interface for Policy parameters.
*
* @since 1.6
*/
public static interface Parameters { }
/**
* This class represents a read-only empty PermissionCollection object that
* is returned from the {@code getPermissions(CodeSource)} and
* {@code getPermissions(ProtectionDomain)}
* methods in the Policy class when those operations are not
* supported by the Policy implementation.
*/
private static class UnsupportedEmptyCollection
extends PermissionCollection {
private static final long serialVersionUID = -8492269157353014774L;
private Permissions perms;
/**
* Create a read-only empty PermissionCollection object.
*/
public UnsupportedEmptyCollection() {
this.perms = new Permissions();
perms.setReadOnly();
}
/**
* Adds a permission object to the current collection of permission
* objects.
*
* @param permission the Permission object to add.
*
* @exception SecurityException - if this PermissionCollection object
* has been marked readonly
*/
@Override public void add(Permission permission) {
perms.add(permission);
}
/**
* Checks to see if the specified permission is implied by the
* collection of Permission objects held in this PermissionCollection.
*
* @param permission the Permission object to compare.
*
* @return true if "permission" is implied by the permissions in
* the collection, false if not.
*/
@Override public boolean implies(Permission permission) {
return perms.implies(permission);
}
/**
* Returns an enumeration of all the Permission objects in the
* collection.
*
* @return an enumeration of all the Permissions.
*/
@Override public Enumeration Subclass implementations of this abstract class must provide
* a public constructor that takes a {@code Policy.Parameters}
* object as an input parameter. This constructor also must throw
* an IllegalArgumentException if it does not understand the
* {@code Policy.Parameters} input.
*
*
* @since 1.6
*/
public abstract class PolicySpi {
/**
* Check whether the policy has granted a Permission to a ProtectionDomain.
*
* @param domain the ProtectionDomain to check.
*
* @param permission check whether this permission is granted to the
* specified domain.
*
* @return boolean true if the permission is granted to the domain.
*/
protected abstract boolean engineImplies
(ProtectionDomain domain, Permission permission);
/**
* Refreshes/reloads the policy configuration. The behavior of this method
* depends on the implementation. For example, calling {@code refresh}
* on a file-based policy will cause the file to be re-read.
*
* The default implementation of this method does nothing.
* This method should be overridden if a refresh operation is supported
* by the policy implementation.
*/
protected void engineRefresh() { }
/**
* Return a PermissionCollection object containing the set of
* permissions granted to the specified CodeSource.
*
* The default implementation of this method returns
* Policy.UNSUPPORTED_EMPTY_COLLECTION object. This method can be
* overridden if the policy implementation can return a set of
* permissions granted to a CodeSource.
*
* @param codesource the CodeSource to which the returned
* PermissionCollection has been granted.
*
* @return a set of permissions granted to the specified CodeSource.
* If this operation is supported, the returned
* set of permissions must be a new mutable instance
* and it must support heterogeneous Permission types.
* If this operation is not supported,
* Policy.UNSUPPORTED_EMPTY_COLLECTION is returned.
*/
protected PermissionCollection engineGetPermissions
(CodeSource codesource) {
return Policy.UNSUPPORTED_EMPTY_COLLECTION;
}
/**
* Return a PermissionCollection object containing the set of
* permissions granted to the specified ProtectionDomain.
*
* The default implementation of this method returns
* Policy.UNSUPPORTED_EMPTY_COLLECTION object. This method can be
* overridden if the policy implementation can return a set of
* permissions granted to a ProtectionDomain.
*
* @param domain the ProtectionDomain to which the returned
* PermissionCollection has been granted.
*
* @return a set of permissions granted to the specified ProtectionDomain.
* If this operation is supported, the returned
* set of permissions must be a new mutable instance
* and it must support heterogeneous Permission types.
* If this operation is not supported,
* Policy.UNSUPPORTED_EMPTY_COLLECTION is returned.
*/
protected PermissionCollection engineGetPermissions
(ProtectionDomain domain) {
return Policy.UNSUPPORTED_EMPTY_COLLECTION;
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 3175
Content-Disposition: inline; filename="Principal.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "a538e707ee761179d0223d1131f8b9c2fca15183"
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import javax.security.auth.Subject;
/**
* This interface represents the abstract notion of a principal, which
* can be used to represent any entity, such as an individual, a
* corporation, and a login id.
*
* @see java.security.cert.X509Certificate
*
* @author Li Gong
*/
public interface Principal {
/**
* Compares this principal to the specified object. Returns true
* if the object passed in matches the principal represented by
* the implementation of this interface.
*
* @param another principal to compare with.
*
* @return true if the principal passed in is the same as that
* encapsulated by this principal, and false otherwise.
*/
public boolean equals(Object another);
/**
* Returns a string representation of this principal.
*
* @return a string representation of this principal.
*/
public String toString();
/**
* Returns a hashcode for this principal.
*
* @return a hashcode for this principal.
*/
public int hashCode();
/**
* Returns the name of this principal.
*
* @return the name of this principal.
*/
public String getName();
/**
* Returns true if the specified subject is implied by this principal.
*
* The default implementation of this method returns true if
* {@code subject} is non-null and contains at least one principal that
* is equal to this principal.
*
* Subclasses may override this with a different implementation, if
* necessary.
*
* @param subject the {@code Subject}
* @return true if {@code subject} is non-null and is
* implied by this principal, or false otherwise.
* @since 1.8
*/
public default boolean implies(Subject subject) {
if (subject == null)
return false;
return subject.getPrincipals().contains(this);
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 2706
Content-Disposition: inline; filename="PrivateKey.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "7d8a7ea704184ab14905080b3898ea5d21c9dda4"
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* A private key.
* The purpose of this interface is to group (and provide type safety
* for) all private key interfaces.
*
* Note: The specialized private key interfaces extend this interface.
* See, for example, the {@code DSAPrivateKey} interface in
* {@link java.security.interfaces}.
*
* Implementations should override the default {@code destroy} and
* {@code isDestroyed} methods from the
* {@link javax.security.auth.Destroyable} interface to enable
* sensitive key information to be destroyed, cleared, or in the case
* where such information is immutable, unreferenced.
* Finally, since {@code PrivateKey} is {@code Serializable}, implementations
* should also override
* {@link java.io.ObjectOutputStream#writeObject(java.lang.Object)}
* to prevent keys that have been destroyed from being serialized.
*
* @see Key
* @see PublicKey
* @see Certificate
* @see Signature#initVerify
* @see java.security.interfaces.DSAPrivateKey
* @see java.security.interfaces.RSAPrivateKey
* @see java.security.interfaces.RSAPrivateCrtKey
*
* @author Benjamin Renaud
* @author Josh Bloch
*/
public interface PrivateKey extends Key, javax.security.auth.Destroyable {
// Declare serialVersionUID to be compatible with JDK1.1
/**
* The class fingerprint that is set to indicate serialization
* compatibility with a previous version of the class.
*/
static final long serialVersionUID = 6034044314589513430L;
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 2381
Content-Disposition: inline; filename="PrivilegedAction.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "b993cea4d2f8d64c3d5fbd853480df8e69ee821d"
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* A computation to be performed with privileges enabled. The computation is
* performed by invoking {@code AccessController.doPrivileged} on the
* {@code PrivilegedAction} object. This interface is used only for
* computations that do not throw checked exceptions; computations that
* throw checked exceptions must use {@code PrivilegedExceptionAction}
* instead.
*
* @see AccessController
* @see AccessController#doPrivileged(PrivilegedAction)
* @see PrivilegedExceptionAction
*/
public interface PrivilegedAction As of release 1.4, this exception has been retrofitted to conform to
* the general purpose exception-chaining mechanism. The "exception thrown
* by the privileged computation" that is provided at construction time and
* accessed via the {@link #getException()} method is now known as the
* cause, and may be accessed via the {@link Throwable#getCause()}
* method, as well as the aforementioned "legacy method."
*
* @see PrivilegedExceptionAction
* @see AccessController#doPrivileged(PrivilegedExceptionAction)
* @see AccessController#doPrivileged(PrivilegedExceptionAction,AccessControlContext)
*/
public class PrivilegedActionException extends Exception {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 4724086851538908602L;
/**
* @serial
*/
private Exception exception;
/**
* Constructs a new PrivilegedActionException "wrapping"
* the specific Exception.
*
* @param exception The exception thrown
*/
public PrivilegedActionException(Exception exception) {
super((Throwable)null); // Disallow initCause
this.exception = exception;
}
/**
* Returns the exception thrown by the privileged computation that
* resulted in this {@code PrivilegedActionException}.
*
* This method predates the general-purpose exception chaining facility.
* The {@link Throwable#getCause()} method is now the preferred means of
* obtaining this information.
*
* @return the exception thrown by the privileged computation that
* resulted in this {@code PrivilegedActionException}.
* @see PrivilegedExceptionAction
* @see AccessController#doPrivileged(PrivilegedExceptionAction)
* @see AccessController#doPrivileged(PrivilegedExceptionAction,
* AccessControlContext)
*/
public Exception getException() {
return exception;
}
/**
* Returns the cause of this exception (the exception thrown by
* the privileged computation that resulted in this
* {@code PrivilegedActionException}).
*
* @return the cause of this exception.
* @since 1.4
*/
public Throwable getCause() {
return exception;
}
public String toString() {
String s = getClass().getName();
return (exception != null) ? (s + ": " + exception.toString()) : s;
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 2794
Content-Disposition: inline; filename="PrivilegedExceptionAction.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "59a9ba7dc18d43073b597ea225c127cf46712a08"
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* A computation to be performed with privileges enabled, that throws one or
* more checked exceptions. The computation is performed by invoking
* {@code AccessController.doPrivileged} on the
* {@code PrivilegedExceptionAction} object. This interface is
* used only for computations that throw checked exceptions;
* computations that do not throw
* checked exceptions should use {@code PrivilegedAction} instead.
*
* @see AccessController
* @see AccessController#doPrivileged(PrivilegedExceptionAction)
* @see AccessController#doPrivileged(PrivilegedExceptionAction,
* AccessControlContext)
* @see PrivilegedAction
*/
public interface PrivilegedExceptionAction
* A static set of permissions can be bound to a ProtectionDomain when it is
* constructed; such permissions are granted to the domain regardless of the
* Policy in force. However, to support dynamic security policies, a
* ProtectionDomain can also be constructed such that it is dynamically
* mapped to a set of permissions by the current Policy whenever a permission
* is checked.
*
*
* @author Li Gong
* @author Roland Schemers
* @author Gary Ellison
*/
public class ProtectionDomain {
private static class JavaSecurityAccessImpl implements JavaSecurityAccess {
private JavaSecurityAccessImpl() {
}
@Override
public
* This constructor is typically used by
* {@link SecureClassLoader ClassLoaders}
* and {@link DomainCombiner DomainCombiners} which delegate to
* {@code Policy} to actively associate the permissions granted to
* this domain. This constructor affords the
* Policy provider the opportunity to augment the supplied
* PermissionCollection to reflect policy changes.
*
*
* @param codesource the CodeSource associated with this domain
* @param permissions the permissions granted to this domain
* @param classloader the ClassLoader associated with this domain
* @param principals the array of Principals associated with this
* domain. The contents of the array are copied to protect against
* subsequent modification.
* @see Policy#refresh
* @see Policy#getPermissions(ProtectionDomain)
* @since 1.4
*/
public ProtectionDomain(CodeSource codesource,
PermissionCollection permissions,
ClassLoader classloader,
Principal[] principals) {
this.codesource = codesource;
if (permissions != null) {
this.permissions = permissions;
this.permissions.setReadOnly();
if (permissions instanceof Permissions &&
((Permissions)permissions).allPermission != null) {
hasAllPerm = true;
}
}
this.classloader = classloader;
this.principals = (principals != null ? principals.clone():
new Principal[0]);
staticPermissions = false;
}
/**
* Returns the CodeSource of this domain.
* @return the CodeSource of this domain which may be null.
* @since 1.2
*/
public final CodeSource getCodeSource() {
return this.codesource;
}
/**
* Returns the ClassLoader of this domain.
* @return the ClassLoader of this domain which may be null.
*
* @since 1.4
*/
public final ClassLoader getClassLoader() {
return this.classloader;
}
/**
* Returns an array of principals for this domain.
* @return a non-null array of principals for this domain.
* Returns a new array each time this method is called.
*
* @since 1.4
*/
public final Principal[] getPrincipals() {
return this.principals.clone();
}
/**
* Returns the static permissions granted to this domain.
*
* @return the static set of permissions for this domain which may be null.
* @see Policy#refresh
* @see Policy#getPermissions(ProtectionDomain)
*/
public final PermissionCollection getPermissions() {
return permissions;
}
/**
* Check and see if this ProtectionDomain implies the permissions
* expressed in the Permission object.
*
* The set of permissions evaluated is a function of whether the
* ProtectionDomain was constructed with a static set of permissions
* or it was bound to a dynamically mapped set of permissions.
*
* If the ProtectionDomain was constructed to a
* {@link #ProtectionDomain(CodeSource, PermissionCollection)
* statically bound} PermissionCollection then the permission will
* only be checked against the PermissionCollection supplied at
* construction.
*
* However, if the ProtectionDomain was constructed with
* the constructor variant which supports
* {@link #ProtectionDomain(CodeSource, PermissionCollection,
* ClassLoader, java.security.Principal[]) dynamically binding}
* permissions, then the permission will be checked against the
* combination of the PermissionCollection supplied at construction and
* the current Policy binding.
*
*
* @param permission the Permission object to check.
*
* @return true if "permission" is implicit to this ProtectionDomain.
*/
public boolean implies(Permission permission) {
if (hasAllPerm) {
// internal permission collection already has AllPermission -
// no need to go to policy
return true;
}
if (!staticPermissions &&
Policy.getPolicyNoCheck().implies(this, permission))
return true;
if (permissions != null)
return permissions.implies(permission);
return false;
}
// called by the VM -- do not remove
boolean impliesCreateAccessControlContext() {
return implies(SecurityConstants.CREATE_ACC_PERMISSION);
}
/**
* Convert a ProtectionDomain to a String.
*/
@Override public String toString() {
String pals = " Each provider has a name and a version number, and is configured
* in each runtime it is installed in.
*
* See The Provider Class
* in the "Java Cryptography Architecture API Specification & Reference"
* for information about how a particular type of provider, the
* cryptographic service provider, works and is installed. However,
* please note that a provider can be used to implement any security
* service in Java that uses a pluggable architecture with a choice
* of implementations that fit underneath.
*
* Some provider implementations may encounter unrecoverable internal
* errors during their operation, for example a failure to communicate with a
* security token. A {@link ProviderException} should be used to indicate
* such errors.
*
* The service type {@code Provider} is reserved for use by the
* security framework. Services of this type cannot be added, removed,
* or modified by applications.
* The following attributes are automatically placed in each Provider object:
* If a security manager is enabled, its {@code checkSecurityAccess}
* method is called with the string {@code "clearProviderProperties."+name}
* (where {@code name} is the provider name) to see if it's ok to clear
* this provider.
*
* @throws SecurityException
* if a security manager exists and its {@link
* java.lang.SecurityManager#checkSecurityAccess} method
* denies access to clear this provider
*
* @since 1.2
*/
@Override
public synchronized void clear() {
check("clearProviderProperties."+name);
if (debug != null) {
debug.println("Remove " + name + " provider properties");
}
implClear();
}
/**
* Reads a property list (key and element pairs) from the input stream.
*
* @param inStream the input stream.
* @exception IOException if an error occurred when reading from the
* input stream.
* @see java.util.Properties#load
*/
@Override
public synchronized void load(InputStream inStream) throws IOException {
check("putProviderProperty."+name);
if (debug != null) {
debug.println("Load " + name + " provider properties");
}
Properties tempProperties = new Properties();
tempProperties.load(inStream);
implPutAll(tempProperties);
}
/**
* Copies all of the mappings from the specified Map to this provider.
* These mappings will replace any properties that this provider had
* for any of the keys currently in the specified Map.
*
* @since 1.2
*/
@Override
public synchronized void putAll(Map,?> t) {
check("putProviderProperty."+name);
if (debug != null) {
debug.println("Put all " + name + " provider properties");
}
implPutAll(t);
}
/**
* Returns an unmodifiable Set view of the property entries contained
* in this Provider.
*
* @see java.util.Map.Entry
* @since 1.2
*/
@Override
public synchronized Set
*
*
*
*
* FilePermission perm = new FilePermission("/temp/testFile", "read");
* AccessController.checkPermission(perm);
*
*
*
* {@code
* for (int i = m; i > 0; i--) {
*
* if (caller i's domain does not have the permission)
* throw AccessControlException
*
* else if (caller i is marked as privileged) {
* if (a context was specified in the call to doPrivileged)
* context.checkPermission(permission)
* if (limited permissions were specified in the call to doPrivileged) {
* for (each limited permission) {
* if (the limited permission implies the requested permission)
* return;
* }
* } else
* return;
* }
* }
*
* // Next, check the context inherited when the thread was created.
* // Whenever a new thread is created, the AccessControlContext at
* // that time is stored and associated with the new thread, as the
* // "inherited" context.
*
* inheritedContext.checkPermission(permission);
* }
*
* {@code
* somemethod() {
* ...normal code here...
* AccessController.doPrivileged(new PrivilegedAction
*
* {@code
* somemethod() {
* ...normal code here...
* String user = AccessController.doPrivileged(
* new PrivilegedAction
*
* {@code
* somemethod() throws FileNotFoundException {
* ...normal code here...
* try {
* FileInputStream fis = AccessController.doPrivileged(
* new PrivilegedExceptionAction
*
*
*
* AccessControlContext acc = AccessController.getContext()
*
*
*
*
*
* acc.checkPermission(permission)
*
*
*
* {@code
* somemethod() {
* AccessController.doPrivileged(new PrivilegedAction
*
*
*
*
*
* These algorithms are described in the
* AlgorithmParameterGenerator section of the
* Java Cryptography Architecture Standard Algorithm Name Documentation.
* Consult the release documentation for your implementation to see if any
* other algorithms are supported.
*
* @author Jan Luehe
*
*
* @see AlgorithmParameters
* @see java.security.spec.AlgorithmParameterSpec
*
* @since 1.2
*/
public class AlgorithmParameterGenerator {
// The provider
private Provider provider;
// The provider implementation (delegate)
private AlgorithmParameterGeneratorSpi paramGenSpi;
// The algorithm
private String algorithm;
/**
* Creates an AlgorithmParameterGenerator object.
*
* @param paramGenSpi the delegate
* @param provider the provider
* @param algorithm the algorithm
*/
protected AlgorithmParameterGenerator
(AlgorithmParameterGeneratorSpi paramGenSpi, Provider provider,
String algorithm) {
this.paramGenSpi = paramGenSpi;
this.provider = provider;
this.algorithm = algorithm;
}
/**
* Returns the standard name of the algorithm this parameter
* generator is associated with.
*
* @return the string name of the algorithm.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/**
* Returns an AlgorithmParameterGenerator object for generating
* a set of parameters to be used with the specified algorithm.
*
*
*
* These algorithms are described in the
* AlgorithmParameters section of the
* Java Cryptography Architecture Standard Algorithm Name Documentation.
* Consult the release documentation for your implementation to see if any
* other algorithms are supported.
*
* @author Jan Luehe
*
*
* @see java.security.spec.AlgorithmParameterSpec
* @see java.security.spec.DSAParameterSpec
* @see KeyPairGenerator
*
* @since 1.2
*/
public class AlgorithmParameters {
// The provider
private Provider provider;
// The provider implementation (delegate)
private AlgorithmParametersSpi paramSpi;
// The algorithm
private String algorithm;
// Has this object been initialized?
private boolean initialized = false;
/**
* Creates an AlgorithmParameters object.
*
* @param paramSpi the delegate
* @param provider the provider
* @param algorithm the algorithm
*/
protected AlgorithmParameters(AlgorithmParametersSpi paramSpi,
Provider provider, String algorithm)
{
this.paramSpi = paramSpi;
this.provider = provider;
this.algorithm = algorithm;
}
/**
* Returns the name of the algorithm associated with this parameter object.
*
* @return the algorithm name.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/**
* Returns a parameter object for the specified algorithm.
*
*
*
*
* @param p the permission to check against.
*
* @return true if the passed permission is equal to or
* implied by this permission, false otherwise.
*/
public boolean implies(Permission p) {
if ((p == null) || (p.getClass() != getClass()))
return false;
BasicPermission that = (BasicPermission) p;
if (this.wildcard) {
if (that.wildcard) {
// one wildcard can imply another
return that.path.startsWith(path);
} else {
// make sure ap.path is longer so a.b.* doesn't imply a.b
return (that.path.length() > this.path.length()) &&
that.path.startsWith(this.path);
}
} else {
if (that.wildcard) {
// a non-wildcard can't imply a wildcard
return false;
}
else {
return this.path.equals(that.path);
}
}
}
/**
* Checks two BasicPermission objects for equality.
* Checks that obj's class is the same as this object's class
* and has the same name as this object.
*
*
*
*
*
* http:
* http://*.sun.com/classes/*
* http://java.sun.com/classes/-
* http://java.sun.com/classes/foo.jar
*
*
* Note that if this CodeSource has a null location and a null
* certificate chain, then it implies every other CodeSource.
*
* @param codesource CodeSource to compare against.
*
* @return true if the specified codesource is implied by this codesource,
* false if not.
*/
public boolean implies(CodeSource codesource)
{
if (codesource == null)
return false;
return matchCerts(codesource, false) && matchLocation(codesource);
}
/**
* Returns true if all the certs in this
* CodeSource are also in that.
*
* @param that the CodeSource to check against.
* @param strict If true then a strict equality match is performed.
* Otherwise a subset match is performed.
*/
private boolean matchCerts(CodeSource that, boolean strict)
{
boolean match;
// match any key
if (certs == null && signers == null) {
if (strict) {
return (that.certs == null && that.signers == null);
} else {
return true;
}
// both have signers
} else if (signers != null && that.signers != null) {
if (strict && signers.length != that.signers.length) {
return false;
}
for (int i = 0; i < signers.length; i++) {
match = false;
for (int j = 0; j < that.signers.length; j++) {
if (signers[i].equals(that.signers[j])) {
match = true;
break;
}
}
if (!match) return false;
}
return true;
// both have certs
} else if (certs != null && that.certs != null) {
if (strict && certs.length != that.certs.length) {
return false;
}
for (int i = 0; i < certs.length; i++) {
match = false;
for (int j = 0; j < that.certs.length; j++) {
if (certs[i].equals(that.certs[j])) {
match = true;
break;
}
}
if (!match) return false;
}
return true;
}
return false;
}
/**
* Returns true if two CodeSource's have the "same" location.
*
* @param that CodeSource to compare against
*/
private boolean matchLocation(CodeSource that) {
if (location == null)
return true;
if ((that == null) || (that.location == null))
return false;
if (location.equals(that.location))
return true;
if (!location.getProtocol().equalsIgnoreCase(that.location.getProtocol()))
return false;
int thisPort = location.getPort();
if (thisPort != -1) {
int thatPort = that.location.getPort();
int port = thatPort != -1 ? thatPort
: that.location.getDefaultPort();
if (thisPort != port)
return false;
}
if (location.getFile().endsWith("/-")) {
// Matches the directory and (recursively) all files
// and subdirectories contained in that directory.
// For example, "/a/b/-" implies anything that starts with
// "/a/b/"
String thisPath = location.getFile().substring(0,
location.getFile().length()-1);
if (!that.location.getFile().startsWith(thisPath))
return false;
} else if (location.getFile().endsWith("/*")) {
// Matches the directory and all the files contained in that
// directory.
// For example, "/a/b/*" implies anything that starts with
// "/a/b/" but has no further slashes
int last = that.location.getFile().lastIndexOf('/');
if (last == -1)
return false;
String thisPath = location.getFile().substring(0,
location.getFile().length()-1);
String thatPath = that.location.getFile().substring(0, last+1);
if (!thatPath.equals(thisPath))
return false;
} else {
// Exact matches only.
// For example, "/a/b" and "/a/b/" both imply "/a/b/"
if ((!that.location.getFile().equals(location.getFile()))
&& (!that.location.getFile().equals(location.getFile()+"/"))) {
return false;
}
}
if (location.getRef() != null
&& !location.getRef().equals(that.location.getRef())) {
return false;
}
String thisHost = location.getHost();
String thatHost = that.location.getHost();
if (thisHost != null) {
if (("".equals(thisHost) || "localhost".equals(thisHost)) &&
("".equals(thatHost) || "localhost".equals(thatHost))) {
// ok
} else if (!thisHost.equals(thatHost)) {
if (thatHost == null) {
return false;
}
if (this.sp == null) {
this.sp = new SocketPermission(thisHost, "resolve");
}
if (that.sp == null) {
that.sp = new SocketPermission(thatHost, "resolve");
}
if (!this.sp.implies(that.sp)) {
return false;
}
}
}
// everything matches
return true;
}
/**
* Returns a string describing this CodeSource, telling its
* URL and certificates.
*
* @return information about this CodeSource.
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append(this.location);
if (this.certs != null && this.certs.length > 0) {
for (int i = 0; i < this.certs.length; i++) {
sb.append( " " + this.certs[i]);
}
} else if (this.signers != null && this.signers.length > 0) {
for (int i = 0; i < this.signers.length; i++) {
sb.append( " " + this.signers[i]);
}
} else {
sb.append(" {@code
* domain
* where {@code domainName} and {@code keystoreName} are identifiers
* and {@code property} is a key/value pairing. The key and value are
* separated by an 'equals' symbol and the value is enclosed in double
* quotes. A property value may be either a printable string or a binary
* string of colon-separated pairs of hexadecimal digits. Multi-valued
* properties are represented as a comma-separated list of values,
* enclosed in square brackets.
* See {@link Arrays#toString(java.lang.Object[])}.
*
*
*
*
* domain app1 {
* keystore app1-truststore
* keystoreURI="file:///app1/etc/truststore.jks";
*
* keystore system-truststore
* keystoreURI="${java.home}/lib/security/cacerts";
*
* keystore app1-keystore
* keystoreType="PKCS12"
* keystoreURI="file:///app1/etc/keystore.p12";
* };
*
*
* @since 1.8
*/
public final class DomainLoadStoreParameter implements LoadStoreParameter {
private final URI configuration;
private final Map
*
*
*
* Keys are generally obtained through key generators, certificates,
* or various Identity classes used to manage keys.
* Keys may also be obtained from key specifications (transparent
* representations of the underlying key material) through the use of a key
* factory (see {@link KeyFactory}).
*
*
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
*
*
* For more information, see
* RFC 5280:
* Internet X.509 Public Key Infrastructure Certificate and CRL Profile.
*
*
* X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
* KeyFactory keyFactory = KeyFactory.getInstance("DSA");
* PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
* Signature sig = Signature.getInstance("DSA");
* sig.initVerify(bobPubKey);
* sig.update(data);
* sig.verify(signature);
*
*
*
*
* These algorithms are described in the
* KeyFactory section of the
* Java Cryptography Architecture Standard Algorithm Name Documentation.
* Consult the release documentation for your implementation to see if any
* other algorithms are supported.
*
* @author Jan Luehe
*
* @see Key
* @see PublicKey
* @see PrivateKey
* @see java.security.spec.KeySpec
* @see java.security.spec.DSAPublicKeySpec
* @see java.security.spec.X509EncodedKeySpec
*
* @since 1.2
*/
public class KeyFactory {
private static final Debug debug =
Debug.getInstance("jca", "KeyFactory");
// The algorithm associated with this key factory
private final String algorithm;
// The provider
private Provider provider;
// The provider implementation (delegate)
private volatile KeyFactorySpi spi;
// lock for mutex during provider selection
private final Object lock = new Object();
// remaining services to try in provider selection
// null once provider is selected
private Iterator
*
*
* @author Benjamin Renaud
*
* @see Key
* @see KeyException
*/
public class KeyManagementException extends KeyException {
private static final long serialVersionUID = 947674216157062695L;
/**
* Constructs a KeyManagementException with no detail message. A
* detail message is a String that describes this particular
* exception.
*/
public KeyManagementException() {
super();
}
/**
* Constructs a KeyManagementException with the specified detail
* message. A detail message is a String that describes this
* particular exception.
*
* @param msg the detail message.
*/
public KeyManagementException(String msg) {
super(msg);
}
/**
* Creates a {@code KeyManagementException} with the specified
* detail message and cause.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @since 1.5
*/
public KeyManagementException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a {@code KeyManagementException} with the specified cause
* and a detail message of {@code (cause==null ? null : cause.toString())}
* (which typically contains the class and detail message of
* {@code cause}).
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @since 1.5
*/
public KeyManagementException(Throwable cause) {
super(cause);
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 2686
Content-Disposition: inline; filename="KeyPair.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "6147a16aa59be2cab7a0a603c8ead27502f5a726"
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.util.*;
/**
* This class is a simple holder for a key pair (a public key and a
* private key). It does not enforce any security, and, when initialized,
* should be treated like a PrivateKey.
*
* @see PublicKey
* @see PrivateKey
*
* @author Benjamin Renaud
*/
public final class KeyPair implements java.io.Serializable {
private static final long serialVersionUID = -7565189502268009837L;
private PrivateKey privateKey;
private PublicKey publicKey;
/**
* Constructs a key pair from the given public key and private key.
*
*
*
*
*
*
* These algorithms are described in the
* KeyPairGenerator section of the
* Java Cryptography Architecture Standard Algorithm Name Documentation.
* Consult the release documentation for your implementation to see if any
* other algorithms are supported.
*
* @author Benjamin Renaud
*
* @see java.security.spec.AlgorithmParameterSpec
*/
public abstract class KeyPairGenerator extends KeyPairGeneratorSpi {
private static final Debug pdebug =
Debug.getInstance("provider", "Provider");
private static final boolean skipDebug =
Debug.isOn("engine=") && !Debug.isOn("keypairgenerator");
private final String algorithm;
// The provider
Provider provider;
/**
* Creates a KeyPairGenerator object for the specified algorithm.
*
* @param algorithm the standard string name of the algorithm.
* See the KeyPairGenerator section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*/
protected KeyPairGenerator(String algorithm) {
this.algorithm = algorithm;
}
/**
* Returns the standard name of the algorithm for this key pair generator.
* See the KeyPairGenerator section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*
* @return the standard string name of the algorithm.
*/
public String getAlgorithm() {
return this.algorithm;
}
private static KeyPairGenerator getInstance(Instance instance,
String algorithm) {
KeyPairGenerator kpg;
if (instance.impl instanceof KeyPairGenerator) {
kpg = (KeyPairGenerator)instance.impl;
} else {
KeyPairGeneratorSpi spi = (KeyPairGeneratorSpi)instance.impl;
kpg = new Delegate(spi, algorithm);
}
kpg.provider = instance.provider;
if (!skipDebug && pdebug != null) {
pdebug.println("KeyPairGenerator." + algorithm +
" algorithm from: " + kpg.provider.getName());
}
return kpg;
}
/**
* Returns a KeyPairGenerator object that generates public/private
* key pairs for the specified algorithm.
*
*
*
*
*
*
*
*
*
*
*
* KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
*
* The system will return a keystore implementation for the default type.
*
*
* KeyStore ks = KeyStore.getInstance("JKS");
*
* The system will return the most preferred implementation of the
* specified keystore type available in the environment.
* KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
*
* // get user password and file input stream
* char[] password = getPassword();
*
* try (FileInputStream fis = new FileInputStream("keyStoreName")) {
* ks.load(fis, password);
* }
*
*
* To create an empty keystore using the above {@code load} method,
* pass {@code null} as the {@code InputStream} argument.
*
*
* KeyStore.ProtectionParameter protParam =
* new KeyStore.PasswordProtection(password);
*
* // get my private key
* KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
* ks.getEntry("privateKeyAlias", protParam);
* PrivateKey myPrivateKey = pkEntry.getPrivateKey();
*
* // save my secret key
* javax.crypto.SecretKey mySecretKey;
* KeyStore.SecretKeyEntry skEntry =
* new KeyStore.SecretKeyEntry(mySecretKey);
* ks.setEntry("secretKeyAlias", skEntry, protParam);
*
* // store away the keystore
* try (FileOutputStream fos = new FileOutputStream("newKeyStoreName")) {
* ks.store(fos, password);
* }
*
*
* Note that although the same password may be used to
* load the keystore, to protect the private key entry,
* to protect the secret key entry, and to store the keystore
* (as is shown in the sample code above),
* different passwords or other protection parameters
* may also be used.
*
*
*
* This type is described in the
* KeyStore section of the
* Java Cryptography Architecture Standard Algorithm Name Documentation.
* Consult the release documentation for your implementation to see if any
* other types are supported.
*
* @author Jan Luehe
*
* @see java.security.PrivateKey
* @see javax.crypto.SecretKey
* @see java.security.cert.Certificate
*
* @since 1.2
*/
public class KeyStore {
private static final Debug pdebug =
Debug.getInstance("provider", "Provider");
private static final boolean skipDebug =
Debug.isOn("engine=") && !Debug.isOn("keystore");
/*
* Constant to lookup in the Security properties file to determine
* the default keystore type.
* In the Security properties file, the default keystore type is given as:
*
* keystore.type=jks
*
*/
private static final String KEYSTORE_TYPE = "keystore.type";
// The keystore type
private String type;
// The provider
private Provider provider;
// The provider implementation
private KeyStoreSpi keyStoreSpi;
// Has this keystore been initialized (loaded)?
private boolean initialized = false;
/**
* A marker interface for {@code KeyStore}
* {@link #load(KeyStore.LoadStoreParameter) load}
* and
* {@link #store(KeyStore.LoadStoreParameter) store}
* parameters.
*
* @since 1.5
*/
public static interface LoadStoreParameter {
/**
* Gets the parameter used to protect keystore data.
*
* @return the parameter used to protect keystore data, or null
*/
public ProtectionParameter getProtectionParameter();
}
/**
* A marker interface for keystore protection parameters.
*
* {@code
* MessageDigest md = MessageDigest.getInstance("SHA-256");
*
* try {
* md.update(toChapter1);
* MessageDigest tc1 = md.clone();
* byte[] toChapter1Digest = tc1.digest();
* md.update(toChapter2);
* ...etc.
* } catch (CloneNotSupportedException cnse) {
* throw new DigestException("couldn't make digest of partial content");
* }
* }
*
*
*
* These algorithms are described in the
* MessageDigest section of the
* Java Cryptography Architecture Standard Algorithm Name Documentation.
* Consult the release documentation for your implementation to see if any
* other algorithms are supported.
*
* @author Benjamin Renaud
*
* @see DigestInputStream
* @see DigestOutputStream
*/
public abstract class MessageDigest extends MessageDigestSpi {
private static final Debug pdebug =
Debug.getInstance("provider", "Provider");
private static final boolean skipDebug =
Debug.isOn("engine=") && !Debug.isOn("messagedigest");
private String algorithm;
// The state of this digest
private static final int INITIAL = 0;
private static final int IN_PROGRESS = 1;
private int state = INITIAL;
// The provider
private Provider provider;
/**
* Creates a message digest with the specified algorithm name.
*
* @param algorithm the standard name of the digest algorithm.
* See the MessageDigest section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* for information about standard algorithm names.
*/
protected MessageDigest(String algorithm) {
this.algorithm = algorithm;
}
/**
* Returns a MessageDigest object that implements the specified digest
* algorithm.
*
*
*
* Attribute ::= SEQUENCE {
* type AttributeType,
* values SET OF AttributeValue
* }
* AttributeType ::= OBJECT IDENTIFIER
* AttributeValue ::= ANY defined by type
*
*
*
* @param encoded the attribute's ASN.1 DER encoding. It is cloned
* to prevent subsequent modificaion.
*
* @exception NullPointerException if {@code encoded} is
* {@code null}
* @exception IllegalArgumentException if {@code encoded} is
* incorrectly formatted
*/
public PKCS12Attribute(byte[] encoded) {
if (encoded == null) {
throw new NullPointerException();
}
this.encoded = encoded.clone();
try {
parse(encoded);
} catch (IOException e) {
throw new IllegalArgumentException("Incorrect format: encoded", e);
}
}
/**
* Returns the attribute's ASN.1 Object Identifier represented as a
* list of dot-separated integers.
*
* @return the attribute's identifier
*/
@Override
public String getName() {
return name;
}
/**
* Returns the attribute's ASN.1 DER-encoded value as a string.
* An ASN.1 DER-encoded value is returned in one of the following
* {@code String} formats:
*
*
* Multi-valued attributes are represented as a comma-separated
* list of values, enclosed in square brackets. See
* {@link Arrays#toString(java.lang.Object[])}.
*
* @return the attribute value's string encoding
*/
@Override
public String getValue() {
return value;
}
/**
* Returns the attribute's ASN.1 DER encoding.
*
* @return a clone of the attribute's DER encoding
*/
public byte[] getEncoded() {
return encoded.clone();
}
/**
* Compares this {@code PKCS12Attribute} and a specified object for
* equality.
*
* @param obj the comparison object
*
* @return true if {@code obj} is a {@code PKCS12Attribute} and
* their DER encodings are equal.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof PKCS12Attribute)) {
return false;
}
return Arrays.equals(encoded, ((PKCS12Attribute) obj).getEncoded());
}
/**
* Returns the hashcode for this {@code PKCS12Attribute}.
* The hash code is computed from its DER encoding.
*
* @return the hash code
*/
@Override
public int hashCode() {
if (hashValue == -1) {
Arrays.hashCode(encoded);
}
return hashValue;
}
/**
* Returns a string representation of this {@code PKCS12Attribute}.
*
* @return a name/value pair separated by an 'equals' symbol
*/
@Override
public String toString() {
return (name + "=" + value);
}
private byte[] encode(ObjectIdentifier type, String[] values)
throws IOException {
DerOutputStream attribute = new DerOutputStream();
attribute.putOID(type);
DerOutputStream attrContent = new DerOutputStream();
for (String value : values) {
if (COLON_SEPARATED_HEX_PAIRS.matcher(value).matches()) {
byte[] bytes =
new BigInteger(value.replace(":", ""), 16).toByteArray();
if (bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
attrContent.putOctetString(bytes);
} else {
attrContent.putUTF8String(value);
}
}
attribute.write(DerValue.tag_Set, attrContent);
DerOutputStream attributeValue = new DerOutputStream();
attributeValue.write(DerValue.tag_Sequence, attribute);
return attributeValue.toByteArray();
}
private void parse(byte[] encoded) throws IOException {
DerInputStream attributeValue = new DerInputStream(encoded);
DerValue[] attrSeq = attributeValue.getSequence(2);
ObjectIdentifier type = attrSeq[0].getOID();
DerInputStream attrContent =
new DerInputStream(attrSeq[1].toByteArray());
DerValue[] attrValueSet = attrContent.getSet(1);
String[] values = new String[attrValueSet.length];
String printableString;
for (int i = 0; i < attrValueSet.length; i++) {
if (attrValueSet[i].tag == DerValue.tag_OctetString) {
values[i] = Debug.toString(attrValueSet[i].getOctetString());
} else if ((printableString = attrValueSet[i].getAsString())
!= null) {
values[i] = printableString;
} else if (attrValueSet[i].tag == DerValue.tag_ObjectId) {
values[i] = attrValueSet[i].getOID().toString();
} else if (attrValueSet[i].tag == DerValue.tag_GeneralizedTime) {
values[i] = attrValueSet[i].getGeneralizedTime().toString();
} else if (attrValueSet[i].tag == DerValue.tag_UtcTime) {
values[i] = attrValueSet[i].getUTCTime().toString();
} else if (attrValueSet[i].tag == DerValue.tag_Integer) {
values[i] = attrValueSet[i].getBigInteger().toString();
} else if (attrValueSet[i].tag == DerValue.tag_Boolean) {
values[i] = String.valueOf(attrValueSet[i].getBoolean());
} else {
values[i] = Debug.toString(attrValueSet[i].getDataBytes());
}
}
this.name = type.toString();
this.value = values.length == 1 ? values[0] : Arrays.toString(values);
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 8560
Content-Disposition: inline; filename="Permission.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "088f97c35a608deb8b27d53563e9f2d83d03a0e6"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
/**
* Abstract class for representing access to a system resource.
* All permissions have a name (whose interpretation depends on the subclass),
* as well as abstract functions for defining the semantics of the
* particular Permission subclass.
*
*
*
*
* @return a hash code value for this object.
*/
public abstract int hashCode();
/**
* Returns the name of this Permission.
* For example, in the case of a {@code java.io.FilePermission},
* the name will be a pathname.
*
* @return the name of this Permission.
*
*/
public final String getName() {
return name;
}
/**
* Returns the actions as a String. This is abstract
* so subclasses can defer creating a String representation until
* one is needed. Subclasses should always return actions in what they
* consider to be their
* canonical form. For example, two FilePermission objects created via
* the following:
*
*
* perm1 = new FilePermission(p1,"read,write");
* perm2 = new FilePermission(p2,"write,read");
*
*
* both return
* "read,write" when the {@code getActions} method is invoked.
*
* @return the actions of this Permission.
*
*/
public abstract String getActions();
/**
* Returns an empty PermissionCollection for a given Permission object, or null if
* one is not defined. Subclasses of class Permission should
* override this if they need to store their permissions in a particular
* PermissionCollection object in order to provide the correct semantics
* when the {@code PermissionCollection.implies} method is called.
* If null is returned,
* then the caller of this method is free to store permissions of this
* type in any PermissionCollection they choose (one that uses a Hashtable,
* one that uses a Vector, etc).
*
* @return a new PermissionCollection object for this type of Permission, or
* null if one is not defined.
*/
public PermissionCollection newPermissionCollection() {
return null;
}
/**
* Returns a string describing this Permission. The convention is to
* specify the class name, the permission name, and the actions in
* the following format: '("ClassName" "name" "actions")', or
* '("ClassName" "name")' if actions list is null or empty.
*
* @return information about this Permission.
*/
public String toString() {
String actions = getActions();
if ((actions == null) || (actions.length() == 0)) { // OPTIONAL
return "(\"" + getClass().getName() + "\" \"" + name + "\")";
} else {
return "(\"" + getClass().getName() + "\" \"" + name +
"\" \"" + actions + "\")";
}
}
}
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'
Content-Type: text/plain; charset=UTF-8
Content-Length: 7984
Content-Disposition: inline; filename="PermissionCollection.java"
Last-Modified: Wed, 10 Jul 2024 15:45:47 GMT
Expires: Wed, 10 Jul 2024 15:50:47 GMT
ETag: "3f13b9f93d52c5b97e312e4d1bef137f0d91cd7c"
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.
*/
package java.security;
import java.util.*;
/**
* Abstract class representing a collection of Permission objects.
*
*
*
*
*
* super.toString() (
* // enumerate all the Permission
* // objects and call toString() on them,
* // one per line..
* )
*
* {@code super.toString} is a call to the {@code toString}
* method of this
* object's superclass, which is Object. The result is
* this PermissionCollection's type name followed by this object's
* hashcode, thus enabling clients to differentiate different
* PermissionCollections object, even if they contain the same permissions.
*
* @return information about this PermissionCollection object,
* as described above.
*
*/
public String toString() {
Enumeration
*
*
*
*
*
*
* @author Benjamin Renaud
* @author Andreas Sterbenz
*/
public abstract class Provider extends Properties {
// Declare serialVersionUID to be compatible with JDK1.1
static final long serialVersionUID = -4298000515446427739L;
private static final sun.security.util.Debug debug =
sun.security.util.Debug.getInstance
("provider", "Provider");
/**
* The provider name.
*
* @serial
*/
private String name;
/**
* A description of the provider and its services.
*
* @serial
*/
private String info;
/**
* The provider version number.
*
* @serial
*/
private double version;
private transient SetName Value
* {@code Provider.id name}
* {@code String.valueOf(provider.getName())}
* {@code Provider.id version}
* {@code String.valueOf(provider.getVersion())}
* {@code Provider.id info}
{@code String.valueOf(provider.getInfo())}
* {@code Provider.id className}
* {@code provider.getClass().getName()}
*