+++ /dev/null
-package edu.stanford.ejalbert;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-/**
- * BrowserLauncher is a class that provides one static method, openURL, which opens the default
- * web browser for the current user of the system to the given URL. It may support other
- * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
- * tested and is not guaranteed to work.
- * <p>
- * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
- * that are not part of the standard JDK. What we're trying to do, though, is to take something
- * that's frequently desirable but inherently platform-specific -- opening a default browser --
- * and allow programmers (you, for example) to do so without worrying about dropping into native
- * code or doing anything else similarly evil.
- * <p>
- * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
- * modification or a need for additional libraries. All classes that are required on certain
- * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
- * found, will not cause this to do anything other than returning an error when opening the
- * browser.
- * <p>
- * There are certain system requirements for this class, as it's running through Runtime.exec(),
- * which is Java's way of making a native system call. Currently, this requires that a Macintosh
- * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
- * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
- * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
- * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
- * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
- * back from the inherently platform-sensitive concept of a default browser and simply attempts
- * to launch Netscape via a shell command.
- * <p>
- * This code is Copyright 1999-2001 by Eric Albert (ejalbert@cs.stanford.edu) and may be
- * redistributed or modified in any form without restrictions as long as the portion of this
- * comment from this paragraph through the end of the comment is not removed. The author
- * requests that he be notified of any application, applet, or other binary that makes use of
- * this code, but that's more out of curiosity than anything and is not required. This software
- * includes no warranty. The author is not repsonsible for any loss of data or functionality
- * or any adverse or unexpected effects of using this software.
- * <p>
- * Credits:
- * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
- * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
- * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
- *
- * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
- * @version 1.4b1 (Released June 20, 2001)
- */
-public class BrowserLauncher {
-
- /**
- * The Java virtual machine that we are running on. Actually, in most cases we only care
- * about the operating system, but some operating systems require us to switch on the VM. */
- private static int jvm;
-
- /** The browser for the system */
- private static Object browser;
-
- /**
- * Caches whether any classes, methods, and fields that are not part of the JDK and need to
- * be dynamically loaded at runtime loaded successfully.
- * <p>
- * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
- * IOException.
- */
- private static boolean loadedWithoutErrors;
-
- /** The com.apple.mrj.MRJFileUtils class */
- private static Class mrjFileUtilsClass;
-
- /** The com.apple.mrj.MRJOSType class */
- private static Class mrjOSTypeClass;
-
- /** The com.apple.MacOS.AEDesc class */
- private static Class aeDescClass;
-
- /** The <init>(int) method of com.apple.MacOS.AETarget */
- private static Constructor aeTargetConstructor;
-
- /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
- private static Constructor appleEventConstructor;
-
- /** The <init>(String) method of com.apple.MacOS.AEDesc */
- private static Constructor aeDescConstructor;
-
- /** The findFolder method of com.apple.mrj.MRJFileUtils */
- private static Method findFolder;
-
- /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
- private static Method getFileCreator;
-
- /** The getFileType method of com.apple.mrj.MRJFileUtils */
- private static Method getFileType;
-
- /** The openURL method of com.apple.mrj.MRJFileUtils */
- private static Method openURL;
-
- /** The makeOSType method of com.apple.MacOS.OSUtils */
- private static Method makeOSType;
-
- /** The putParameter method of com.apple.MacOS.AppleEvent */
- private static Method putParameter;
-
- /** The sendNoReply method of com.apple.MacOS.AppleEvent */
- private static Method sendNoReply;
-
- /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
- private static Object kSystemFolderType;
-
- /** The keyDirectObject AppleEvent parameter type */
- private static Integer keyDirectObject;
-
- /** The kAutoGenerateReturnID AppleEvent code */
- private static Integer kAutoGenerateReturnID;
-
- /** The kAnyTransactionID AppleEvent code */
- private static Integer kAnyTransactionID;
-
- /** The linkage object required for JDirect 3 on Mac OS X. */
- private static Object linkage;
-
- /** The framework to reference on Mac OS X */
- private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
-
- /** JVM constant for MRJ 2.0 */
- private static final int MRJ_2_0 = 0;
-
- /** JVM constant for MRJ 2.1 or later */
- private static final int MRJ_2_1 = 1;
-
- /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
- private static final int MRJ_3_0 = 3;
-
- /** JVM constant for MRJ 3.1 */
- private static final int MRJ_3_1 = 4;
-
- /** JVM constant for any Windows NT JVM */
- private static final int WINDOWS_NT = 5;
-
- /** JVM constant for any Windows 9x JVM */
- private static final int WINDOWS_9x = 6;
-
- /** JVM constant for any other platform */
- private static final int OTHER = -1;
-
- /**
- * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
- * systems from working properly.
- */
- private static final String FINDER_TYPE = "FNDR";
-
- /**
- * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
- * application.
- */
- private static final String FINDER_CREATOR = "MACS";
-
- /** The name for the AppleEvent type corresponding to a GetURL event. */
- private static final String GURL_EVENT = "GURL";
-
- /**
- * The first parameter that needs to be passed into Runtime.exec() to open the default web
- * browser on Windows.
- */
- private static final String FIRST_WINDOWS_PARAMETER = "/c";
-
- /** The second parameter for Runtime.exec() on Windows. */
- private static final String SECOND_WINDOWS_PARAMETER = "start";
-
- /**
- * The third parameter for Runtime.exec() on Windows. This is a "title"
- * parameter that the command line expects. Setting this parameter allows
- * URLs containing spaces to work.
- */
- private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
-
- /**
- * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
- * on many command-line systems.
- */
- private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
- private static final String NETSCAPE_OPEN_PARAMETER_START = "'openURL(";
- private static final String NETSCAPE_OPEN_PARAMETER_END = ")'";
-
- /**
- * The message from any exception thrown throughout the initialization process.
- */
- private static String errorMessage;
-
- /**
- * An initialization block that determines the operating system and loads the necessary
- * runtime data.
- */
- static {
- loadedWithoutErrors = true;
- String osName = System.getProperty("os.name");
- if (osName.startsWith("Mac OS")) {
- String mrjVersion = System.getProperty("mrj.version");
- String majorMRJVersion = mrjVersion.substring(0, 3);
- try {
- double version = Double.valueOf(majorMRJVersion).doubleValue();
- if (version == 2) {
- jvm = MRJ_2_0;
- } else if (version >= 2.1 && version < 3) {
- // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
- // works via Runtime.exec() and 2.2 supports that but has an openURL() method
- // as well that we currently ignore.
- jvm = MRJ_2_1;
- } else if (version == 3.0) {
- jvm = MRJ_3_0;
- } else if (version >= 3.1) {
- // Assume that all 3.1 and later versions of MRJ work the same.
- jvm = MRJ_3_1;
- } else {
- loadedWithoutErrors = false;
- errorMessage = "Unsupported MRJ version: " + version;
- }
- } catch (NumberFormatException nfe) {
- loadedWithoutErrors = false;
- errorMessage = "Invalid MRJ version: " + mrjVersion;
- }
- } else if (osName.startsWith("Windows")) {
- if (osName.indexOf("9") != -1) {
- jvm = WINDOWS_9x;
- } else {
- jvm = WINDOWS_NT;
- }
- } else {
- jvm = OTHER;
- }
-
- if (loadedWithoutErrors) { // if we haven't hit any errors yet
- loadedWithoutErrors = loadClasses();
- }
- }
-
- /**
- * This class should be never be instantiated; this just ensures so.
- */
- private BrowserLauncher() { }
-
- /**
- * Called by a static initializer to load any classes, fields, and methods required at runtime
- * to locate the user's web browser.
- * @return <code>true</code> if all intialization succeeded
- * <code>false</code> if any portion of the initialization failed
- */
- private static boolean loadClasses() {
- switch (jvm) {
- case MRJ_2_0:
- try {
- Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
- Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
- Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
- Class aeClass = Class.forName("com.apple.MacOS.ae");
- aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
-
- aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class });
- appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
- aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });
-
- makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class });
- putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass });
- sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { });
-
- Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
- keyDirectObject = (Integer) keyDirectObjectField.get(null);
- Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
- kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
- Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
- kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
- } catch (ClassNotFoundException cnfe) {
- errorMessage = cnfe.getMessage();
- return false;
- } catch (NoSuchMethodException nsme) {
- errorMessage = nsme.getMessage();
- return false;
- } catch (NoSuchFieldException nsfe) {
- errorMessage = nsfe.getMessage();
- return false;
- } catch (IllegalAccessException iae) {
- errorMessage = iae.getMessage();
- return false;
- }
- break;
- case MRJ_2_1:
- try {
- mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
- mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
- Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
- kSystemFolderType = systemFolderField.get(null);
- findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
- getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
- getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
- } catch (ClassNotFoundException cnfe) {
- errorMessage = cnfe.getMessage();
- return false;
- } catch (NoSuchFieldException nsfe) {
- errorMessage = nsfe.getMessage();
- return false;
- } catch (NoSuchMethodException nsme) {
- errorMessage = nsme.getMessage();
- return false;
- } catch (SecurityException se) {
- errorMessage = se.getMessage();
- return false;
- } catch (IllegalAccessException iae) {
- errorMessage = iae.getMessage();
- return false;
- }
- break;
- case MRJ_3_0:
- try {
- Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
- Constructor constructor = linker.getConstructor(new Class[]{ Class.class });
- linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
- } catch (ClassNotFoundException cnfe) {
- errorMessage = cnfe.getMessage();
- return false;
- } catch (NoSuchMethodException nsme) {
- errorMessage = nsme.getMessage();
- return false;
- } catch (InvocationTargetException ite) {
- errorMessage = ite.getMessage();
- return false;
- } catch (InstantiationException ie) {
- errorMessage = ie.getMessage();
- return false;
- } catch (IllegalAccessException iae) {
- errorMessage = iae.getMessage();
- return false;
- }
- break;
- case MRJ_3_1:
- try {
- mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
- openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
- } catch (ClassNotFoundException cnfe) {
- errorMessage = cnfe.getMessage();
- return false;
- } catch (NoSuchMethodException nsme) {
- errorMessage = nsme.getMessage();
- return false;
- }
- break;
- default:
- break;
- }
- return true;
- }
-
- /**
- * Attempts to locate the default web browser on the local system. Caches results so it
- * only locates the browser once for each use of this class per JVM instance.
- * @return The browser for the system. Note that this may not be what you would consider
- * to be a standard web browser; instead, it's the application that gets called to
- * open the default web browser. In some cases, this will be a non-String object
- * that provides the means of calling the default browser.
- */
- private static Object locateBrowser() {
- if (browser != null) {
- return browser;
- }
- switch (jvm) {
- case MRJ_2_0:
- try {
- Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
- Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
- Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
- Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
- // Don't set browser = appleEvent because then the next time we call
- // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
- // added the relevant parameter. Instead, regenerate the AppleEvent every time.
- // There's probably a way to do this better; if any has any ideas, please let
- // me know.
- return appleEvent;
- } catch (IllegalAccessException iae) {
- browser = null;
- errorMessage = iae.getMessage();
- return browser;
- } catch (InstantiationException ie) {
- browser = null;
- errorMessage = ie.getMessage();
- return browser;
- } catch (InvocationTargetException ite) {
- browser = null;
- errorMessage = ite.getMessage();
- return browser;
- }
- case MRJ_2_1:
- File systemFolder;
- try {
- systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
- } catch (IllegalArgumentException iare) {
- browser = null;
- errorMessage = iare.getMessage();
- return browser;
- } catch (IllegalAccessException iae) {
- browser = null;
- errorMessage = iae.getMessage();
- return browser;
- } catch (InvocationTargetException ite) {
- browser = null;
- errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
- return browser;
- }
- String[] systemFolderFiles = systemFolder.list();
- // Avoid a FilenameFilter because that can't be stopped mid-list
- for(int i = 0; i < systemFolderFiles.length; i++) {
- try {
- File file = new File(systemFolder, systemFolderFiles[i]);
- if (!file.isFile()) {
- continue;
- }
- // We're looking for a file with a creator code of 'MACS' and
- // a type of 'FNDR'. Only requiring the type results in non-Finder
- // applications being picked up on certain Mac OS 9 systems,
- // especially German ones, and sending a GURL event to those
- // applications results in a logout under Multiple Users.
- Object fileType = getFileType.invoke(null, new Object[] { file });
- if (FINDER_TYPE.equals(fileType.toString())) {
- Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
- if (FINDER_CREATOR.equals(fileCreator.toString())) {
- browser = file.toString(); // Actually the Finder, but that's OK
- return browser;
- }
- }
- } catch (IllegalArgumentException iare) {
- browser = browser;
- errorMessage = iare.getMessage();
- return null;
- } catch (IllegalAccessException iae) {
- browser = null;
- errorMessage = iae.getMessage();
- return browser;
- } catch (InvocationTargetException ite) {
- browser = null;
- errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
- return browser;
- }
- }
- browser = null;
- break;
- case MRJ_3_0:
- case MRJ_3_1:
- browser = ""; // Return something non-null
- break;
- case WINDOWS_NT:
- browser = "cmd.exe";
- break;
- case WINDOWS_9x:
- browser = "command.com";
- break;
- case OTHER:
- default:
- browser = "netscape";
- break;
- }
- return browser;
- }
-
- /**
- * Attempts to open the default web browser to the given URL.
- * @param url The URL to open
- * @throws IOException If the web browser could not be located or does not run
- */
- public static void openURL(String url) throws IOException {
- if (!loadedWithoutErrors) {
- throw new IOException("Exception in finding browser: " + errorMessage);
- }
- Object browser = locateBrowser();
- if (browser == null) {
- throw new IOException("Unable to locate browser: " + errorMessage);
- }
-
- switch (jvm) {
- case MRJ_2_0:
- Object aeDesc = null;
- try {
- aeDesc = aeDescConstructor.newInstance(new Object[] { url });
- putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
- sendNoReply.invoke(browser, new Object[] { });
- } catch (InvocationTargetException ite) {
- throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
- } catch (IllegalAccessException iae) {
- throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
- } catch (InstantiationException ie) {
- throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
- } finally {
- aeDesc = null; // Encourage it to get disposed if it was created
- browser = null; // Ditto
- }
- break;
- case MRJ_2_1:
- Runtime.getRuntime().exec(new String[] { (String) browser, url } );
- break;
- case MRJ_3_0:
- int[] instance = new int[1];
- int result = ICStart(instance, 0);
- if (result == 0) {
- int[] selectionStart = new int[] { 0 };
- byte[] urlBytes = url.getBytes();
- int[] selectionEnd = new int[] { urlBytes.length };
- result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
- urlBytes.length, selectionStart,
- selectionEnd);
- if (result == 0) {
- // Ignore the return value; the URL was launched successfully
- // regardless of what happens here.
- ICStop(instance);
- } else {
- throw new IOException("Unable to launch URL: " + result);
- }
- } else {
- throw new IOException("Unable to create an Internet Config instance: " + result);
- }
- break;
- case MRJ_3_1:
- try {
- openURL.invoke(null, new Object[] { url });
- } catch (InvocationTargetException ite) {
- throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
- } catch (IllegalAccessException iae) {
- throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
- }
- break;
- case WINDOWS_NT:
- case WINDOWS_9x:
- // Add quotes around the URL to allow ampersands and other special
- // characters to work.
- Process process = Runtime.getRuntime().exec(new String[] { (String) browser,
- FIRST_WINDOWS_PARAMETER,
- SECOND_WINDOWS_PARAMETER,
- THIRD_WINDOWS_PARAMETER,
- '"' + url + '"' });
- // This avoids a memory leak on some versions of Java on Windows.
- // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
- try {
- process.waitFor();
- process.exitValue();
- } catch (InterruptedException ie) {
- throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
- }
- break;
- case OTHER:
- // Assume that we're on Unix and that Netscape is installed
-
- // First, attempt to open the URL in a currently running session of Netscape
- process = Runtime.getRuntime().exec(new String[] { (String) browser,
- NETSCAPE_REMOTE_PARAMETER,
- NETSCAPE_OPEN_PARAMETER_START +
- url +
- NETSCAPE_OPEN_PARAMETER_END });
- try {
- int exitCode = process.waitFor();
- if (exitCode != 0) { // if Netscape was not open
- Runtime.getRuntime().exec(new String[] { (String) browser, url });
- }
- } catch (InterruptedException ie) {
- throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
- }
- break;
- default:
- // This should never occur, but if it does, we'll try the simplest thing possible
- Runtime.getRuntime().exec(new String[] { (String) browser, url });
- break;
- }
- }
-
- /**
- * Methods required for Mac OS X. The presence of native methods does not cause
- * any problems on other platforms.
- */
- /*
- private native static int ICStart(int[] instance, int signature);
- private native static int ICStop(int[] instance);
- private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
- int[] selectionStart, int[] selectionEnd);
- */
- private static int ICStart(int[] instance, int signature) { return 0; }
- private static int ICStop(int[] instance) { return 0; }
- private static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
- int[] selectionStart, int[] selectionEnd) { return 0; }
-}
+++ /dev/null
-/*
- * gnu/regexp/CharIndexed.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-package gnu.regexp;
-
-/**
- * Defines the interface used internally so that different types of source
- * text can be accessed in the same way. Built-in concrete classes provide
- * support for String, StringBuffer, InputStream and char[] types.
- * A class that is CharIndexed supports the notion of a cursor within a
- * block of text. The cursor must be able to be advanced via the move()
- * method. The charAt() method returns the character at the cursor position
- * plus a given offset.
- *
- * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- */
-public interface CharIndexed {
- /**
- * Defines a constant (0xFFFF was somewhat arbitrarily chosen)
- * that can be returned by the charAt() function indicating that
- * the specified index is out of range.
- */
- char OUT_OF_BOUNDS = '\uFFFF';
-
- /**
- * Returns the character at the given offset past the current cursor
- * position in the input. The index of the current position is zero.
- * It is possible for this method to be called with a negative index.
- * This happens when using the '^' operator in multiline matching mode
- * or the '\b' or '\<' word boundary operators. In any case, the lower
- * bound is currently fixed at -2 (for '^' with a two-character newline).
- *
- * @param index the offset position in the character field to examine
- * @return the character at the specified index, or the OUT_OF_BOUNDS
- * character defined by this interface.
- */
- char charAt(int index);
-
- /**
- * Shifts the input buffer by a given number of positions. Returns
- * true if the new cursor position is valid.
- */
- boolean move(int index);
-
- /**
- * Returns true if the most recent move() operation placed the cursor
- * position at a valid position in the input.
- */
- boolean isValid();
-}
+++ /dev/null
-/*
- * gnu/regexp/CharIndexedCharArray.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-package gnu.regexp;
-import java.io.Serializable;
-
-class CharIndexedCharArray implements CharIndexed, Serializable {
- private char[] s;
- private int anchor;
-
- CharIndexedCharArray(char[] str, int index) {
- s = str;
- anchor = index;
- }
-
- public char charAt(int index) {
- int pos = anchor + index;
- return ((pos < s.length) && (pos >= 0)) ? s[pos] : OUT_OF_BOUNDS;
- }
-
- public boolean isValid() {
- return (anchor < s.length);
- }
-
- public boolean move(int index) {
- return ((anchor += index) < s.length);
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/CharIndexedReader.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.io.InputStream;
-import java.io.BufferedInputStream;
-import java.io.IOException;
-
-// TODO: move(x) shouldn't rely on calling next() x times
-
-class CharIndexedInputStream implements CharIndexed {
- private static final int BUFFER_INCREMENT = 1024;
- private static final int UNKNOWN = Integer.MAX_VALUE; // value for end
-
- private BufferedInputStream br;
-
- // so that we don't try to reset() right away
- private int index = -1;
-
- private int bufsize = BUFFER_INCREMENT;
-
- private int end = UNKNOWN;
-
- private char cached = OUT_OF_BOUNDS;
-
- // Big enough for a \r\n pair
- // lookBehind[0] = most recent
- // lookBehind[1] = second most recent
- private char[] lookBehind = new char[] { OUT_OF_BOUNDS, OUT_OF_BOUNDS };
-
- CharIndexedInputStream(InputStream str, int index) {
- if (str instanceof BufferedInputStream) br = (BufferedInputStream) str;
- else br = new BufferedInputStream(str,BUFFER_INCREMENT);
- next();
- if (index > 0) move(index);
- }
-
- private boolean next() {
- if (end == 1) return false;
- end--; // closer to end
-
- try {
- if (index != -1) {
- br.reset();
- }
- int i = br.read();
- br.mark(bufsize);
- if (i == -1) {
- end = 1;
- cached = OUT_OF_BOUNDS;
- return false;
- }
- cached = (char) i;
- index = 1;
- } catch (IOException e) {
- e.printStackTrace();
- cached = OUT_OF_BOUNDS;
- return false;
- }
- return true;
- }
-
- public char charAt(int index) {
- if (index == 0) {
- return cached;
- } else if (index >= end) {
- return OUT_OF_BOUNDS;
- } else if (index == -1) {
- return lookBehind[0];
- } else if (index == -2) {
- return lookBehind[1];
- } else if (index < -2) {
- return OUT_OF_BOUNDS;
- } else if (index >= bufsize) {
- // Allocate more space in the buffer.
- try {
- while (bufsize <= index) bufsize += BUFFER_INCREMENT;
- br.reset();
- br.mark(bufsize);
- br.skip(index-1);
- } catch (IOException e) { }
- } else if (this.index != index) {
- try {
- br.reset();
- br.skip(index-1);
- } catch (IOException e) { }
- }
- char ch = OUT_OF_BOUNDS;
-
- try {
- int i = br.read();
- this.index = index+1; // this.index is index of next pos relative to charAt(0)
- if (i == -1) {
- // set flag that next should fail next time?
- end = index;
- return ch;
- }
- ch = (char) i;
- } catch (IOException ie) { }
-
- return ch;
- }
-
- public boolean move(int index) {
- // move read position [index] clicks from 'charAt(0)'
- boolean retval = true;
- while (retval && (index-- > 0)) retval = next();
- return retval;
- }
-
- public boolean isValid() {
- return (cached != OUT_OF_BOUNDS);
- }
-}
-
+++ /dev/null
-/*
- * gnu/regexp/CharIndexedReader.java
- * Copyright (C) 2001 Lee Sau Dan
- * Based on gnu.regexp.CharIndexedInputStream by Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.io.Reader;
-import java.io.BufferedReader;
-import java.io.IOException;
-
-// TODO: move(x) shouldn't rely on calling next() x times
-
-class CharIndexedReader implements CharIndexed {
- private static final int BUFFER_INCREMENT = 1024;
- private static final int UNKNOWN = Integer.MAX_VALUE; // value for end
-
- private final BufferedReader br;
- // so that we don't try to reset() right away
- private int index = -1;
-
- private int bufsize = BUFFER_INCREMENT;
-
- private int end = UNKNOWN;
-
- private char cached = OUT_OF_BOUNDS;
-
- // Big enough for a \r\n pair
- // lookBehind[0] = most recent
- // lookBehind[1] = second most recent
- private char[] lookBehind = new char[] { OUT_OF_BOUNDS, OUT_OF_BOUNDS };
-
- CharIndexedReader(Reader reader, int index) {
- if (reader instanceof BufferedReader) {
- br = (BufferedReader) reader;
- } else {
- br = new BufferedReader(reader,BUFFER_INCREMENT);
- }
- next();
- if (index > 0) move(index);
- }
-
- private boolean next() {
- lookBehind[1] = lookBehind[0];
- lookBehind[0] = cached;
-
- if (end == 1) {
- cached = OUT_OF_BOUNDS;
- return false;
- }
- end--; // closer to end
-
- try {
- if (index != -1) {
- br.reset();
- }
- int i = br.read();
- br.mark(bufsize);
- if (i == -1) {
- end = 1;
- cached = OUT_OF_BOUNDS;
- return false;
- }
-
- // convert the byte read into a char
- cached = (char) i;
- index = 1;
- } catch (IOException e) {
- e.printStackTrace();
- cached = OUT_OF_BOUNDS;
- return false;
- }
- return true;
- }
-
- public char charAt(int index) {
- if (index == 0) {
- return cached;
- } else if (index >= end) {
- return OUT_OF_BOUNDS;
- } else if (index >= bufsize) {
- // Allocate more space in the buffer.
- try {
- while (bufsize <= index) bufsize += BUFFER_INCREMENT;
- br.reset();
- br.mark(bufsize);
- br.skip(index-1);
- } catch (IOException e) { }
- } else if (this.index != index) {
- try {
- br.reset();
- br.skip(index-1);
- } catch (IOException e) { }
- } else if (index == -1) {
- return lookBehind[0];
- } else if (index == -2) {
- return lookBehind[1];
- } else if (index < -2) {
- return OUT_OF_BOUNDS;
- }
-
- char ch = OUT_OF_BOUNDS;
-
- try {
- int i = br.read();
- this.index = index+1; // this.index is index of next pos relative to charAt(0)
- if (i == -1) {
- // set flag that next should fail next time?
- end = index;
- return ch;
- }
- ch = (char) i;
- } catch (IOException ie) { }
-
- return ch;
- }
-
- public boolean move(int index) {
- // move read position [index] clicks from 'charAt(0)'
- boolean retval = true;
- while (retval && (index-- > 0)) retval = next();
- return retval;
- }
-
- public boolean isValid() {
- return (cached != OUT_OF_BOUNDS);
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/CharIndexedString.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-package gnu.regexp;
-import java.io.Serializable;
-
-class CharIndexedString implements CharIndexed, Serializable {
- private String s;
- private int anchor;
- private int len;
-
- CharIndexedString(String str, int index) {
- s = str;
- len = s.length();
- anchor = index;
- }
-
- public char charAt(int index) {
- int pos = anchor + index;
- return ((pos < len) && (pos >= 0)) ? s.charAt(pos) : OUT_OF_BOUNDS;
- }
-
- public boolean isValid() {
- return (anchor < len);
- }
-
- public boolean move(int index) {
- return ((anchor += index) < len);
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/CharIndexedStringBuffer.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-package gnu.regexp;
-import java.io.Serializable;
-
-class CharIndexedStringBuffer implements CharIndexed, Serializable {
- private StringBuffer s;
- private int anchor;
-
- CharIndexedStringBuffer(StringBuffer str, int index) {
- s = str;
- anchor = index;
- }
-
- public char charAt(int index) {
- int pos = anchor + index;
- return ((pos < s.length()) && (pos >= 0)) ? s.charAt(pos) : OUT_OF_BOUNDS;
- }
-
- public boolean isValid() {
- return (anchor < s.length());
- }
-
- public boolean move(int index) {
- return ((anchor += index) < s.length());
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/RE.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.Serializable;
-import java.util.Vector;
-
-class IntPair implements Serializable {
- public int first, second;
-}
-
-class CharUnit implements Serializable {
- public char ch;
- public boolean bk;
-}
-
-/**
- * RE provides the user interface for compiling and matching regular
- * expressions.
- * <P>
- * A regular expression object (class RE) is compiled by constructing it
- * from a String, StringBuffer or character array, with optional
- * compilation flags (below)
- * and an optional syntax specification (see RESyntax; if not specified,
- * <code>RESyntax.RE_SYNTAX_PERL5</code> is used).
- * <P>
- * Various methods attempt to match input text against a compiled
- * regular expression. These methods are:
- * <LI><code>isMatch</code>: returns true if the input text in its entirety
- * matches the regular expression pattern.
- * <LI><code>getMatch</code>: returns the first match found in the input text,
- * or null if no match is found.
- * <LI><code>getAllMatches</code>: returns an array of all non-overlapping
- * matches found in the input text. If no matches are found, the array is
- * zero-length.
- * <LI><code>substitute</code>: substitute the first occurence of the pattern
- * in the input text with a replacement string (which may include
- * metacharacters $0-$9, see REMatch.substituteInto).
- * <LI><code>substituteAll</code>: same as above, but repeat for each match
- * before returning.
- * <LI><code>getMatchEnumeration</code>: returns an REMatchEnumeration object
- * that allows iteration over the matches (see REMatchEnumeration for some
- * reasons why you may want to do this instead of using <code>getAllMatches</code>.
- * <P>
- *
- * These methods all have similar argument lists. The input can be a
- * String, a character array, a StringBuffer, a Reader or an
- * InputStream of some sort. Note that when using a Reader or
- * InputStream, the stream read position cannot be guaranteed after
- * attempting a match (this is not a bug, but a consequence of the way
- * regular expressions work). Using an REMatchEnumeration can
- * eliminate most positioning problems.
- *
- * <P>
- *
- * The optional index argument specifies the offset from the beginning
- * of the text at which the search should start (see the descriptions
- * of some of the execution flags for how this can affect positional
- * pattern operators). For a Reader or InputStream, this means an
- * offset from the current read position, so subsequent calls with the
- * same index argument on a Reader or an InputStream will not
- * necessarily access the same position on the stream, whereas
- * repeated searches at a given index in a fixed string will return
- * consistent results.
- *
- * <P>
- * You can optionally affect the execution environment by using a
- * combination of execution flags (constants listed below).
- *
- * <P>
- * All operations on a regular expression are performed in a
- * thread-safe manner.
- *
- * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- * @version 1.1.4-dev, to be released
- */
-
-public class RE extends REToken {
- // This String will be returned by getVersion()
- private static final String VERSION = "1.1.4-dev";
-
- // The localized strings are kept in a separate file
- // Ibex LOCAL: we can't bundle property lists within the ibex executable on all platforms
- // private static ResourceBundle messages = PropertyResourceBundle.getBundle("gnu/regexp/MessagesBundle", Locale.getDefault());
-
- // These are, respectively, the first and last tokens in our linked list
- // If there is only one token, firstToken == lastToken
- private REToken firstToken, lastToken;
-
- // This is the number of subexpressions in this regular expression,
- // with a minimum value of zero. Returned by getNumSubs()
- private int numSubs;
-
- /** Minimum length, in characters, of any possible match. */
- private int minimumLength;
-
- /**
- * Compilation flag. Do not differentiate case. Subsequent
- * searches using this RE will be case insensitive.
- */
- public static final int REG_ICASE = 2;
-
- /**
- * Compilation flag. The match-any-character operator (dot)
- * will match a newline character. When set this overrides the syntax
- * bit RE_DOT_NEWLINE (see RESyntax for details). This is equivalent to
- * the "/s" operator in Perl.
- */
- public static final int REG_DOT_NEWLINE = 4;
-
- /**
- * Compilation flag. Use multiline mode. In this mode, the ^ and $
- * anchors will match based on newlines within the input. This is
- * equivalent to the "/m" operator in Perl.
- */
- public static final int REG_MULTILINE = 8;
-
- /**
- * Execution flag.
- * The match-beginning operator (^) will not match at the beginning
- * of the input string. Useful for matching on a substring when you
- * know the context of the input is such that position zero of the
- * input to the match test is not actually position zero of the text.
- * <P>
- * This example demonstrates the results of various ways of matching on
- * a substring.
- * <P>
- * <CODE>
- * String s = "food bar fool";<BR>
- * RE exp = new RE("^foo.");<BR>
- * REMatch m0 = exp.getMatch(s);<BR>
- * REMatch m1 = exp.getMatch(s.substring(8));<BR>
- * REMatch m2 = exp.getMatch(s.substring(8),0,RE.REG_NOTBOL); <BR>
- * REMatch m3 = exp.getMatch(s,8); <BR>
- * REMatch m4 = exp.getMatch(s,8,RE.REG_ANCHORINDEX); <BR>
- * <P>
- * // Results:<BR>
- * // m0 = "food"<BR>
- * // m1 = "fool"<BR>
- * // m2 = null<BR>
- * // m3 = null<BR>
- * // m4 = "fool"<BR>
- * </CODE>
- */
- public static final int REG_NOTBOL = 16;
-
- /**
- * Execution flag.
- * The match-end operator ($) does not match at the end
- * of the input string. Useful for matching on substrings.
- */
- public static final int REG_NOTEOL = 32;
-
- /**
- * Execution flag.
- * When a match method is invoked that starts matching at a non-zero
- * index into the input, treat the input as if it begins at the index
- * given. The effect of this flag is that the engine does not "see"
- * any text in the input before the given index. This is useful so
- * that the match-beginning operator (^) matches not at position 0
- * in the input string, but at the position the search started at
- * (based on the index input given to the getMatch function). See
- * the example under REG_NOTBOL. It also affects the use of the \<
- * and \b operators.
- */
- public static final int REG_ANCHORINDEX = 64;
-
- /**
- * Execution flag.
- * The substitute and substituteAll methods will not attempt to
- * interpolate occurrences of $1-$9 in the replacement text with
- * the corresponding subexpressions. For example, you may want to
- * replace all matches of "one dollar" with "$1".
- */
- public static final int REG_NO_INTERPOLATE = 128;
-
- /** Returns a string representing the version of the gnu.regexp package. */
- public static final String version() {
- return VERSION;
- }
-
- // Retrieves a message from the ResourceBundle
- // Ibex LOCAL: we can't bundle property lists within the ibex executable on all platforms
- // for simplicity, just lookup the errors this way.
- static final String getLocalizedMessage(String key) {
- if(key.equals("error.prefix")) return "At position {0} in regular expression pattern:";
- else if(key.equals("repeat.assertion")) return "repeated token is zero-width assertion";
- else if(key.equals("repeat.chained")) return "attempted to repeat a token that is already repeated";
- else if(key.equals("repeat.no.token")) return "quantifier (?*+{}) without preceding token";
- else if(key.equals("repeat.empty.token")) return "repeated token may be empty";
- else if(key.equals("unmatched.brace")) return "unmatched brace";
- else if(key.equals("unmatched.bracket")) return "unmatched bracket";
- else if(key.equals("unmatched.paren")) return "unmatched parenthesis";
- else if(key.equals("interval.no.end")) return "expected end of interval";
- else if(key.equals("class.no.end")) return "expected end of character class";
- else if(key.equals("subexpr.no.end")) return "expected end of subexpression";
- else if(key.equals("interval.order")) return "interval minimum is greater than maximum";
- else if(key.equals("interval.error")) return "interval is empty or contains illegal chracters";
- else if(key.equals("ends.with.backslash")) return "backslash at end of pattern";
- else if(key.equals("syntax.final")) return "Syntax has been declared final and cannot be modified";
- return "Unknown regexp error";
- //return messages.getString(key);
- }
-
- /**
- * Constructs a regular expression pattern buffer without any compilation
- * flags set, and using the default syntax (RESyntax.RE_SYNTAX_PERL5).
- *
- * @param pattern A regular expression pattern, in the form of a String,
- * StringBuffer or char[]. Other input types will be converted to
- * strings using the toString() method.
- * @exception REException The input pattern could not be parsed.
- * @exception NullPointerException The pattern was null.
- */
- public RE(Object pattern) throws REException {
- this(pattern,0,RESyntax.RE_SYNTAX_PERL5,0,0);
- }
-
- /**
- * Constructs a regular expression pattern buffer using the specified
- * compilation flags and the default syntax (RESyntax.RE_SYNTAX_PERL5).
- *
- * @param pattern A regular expression pattern, in the form of a String,
- * StringBuffer, or char[]. Other input types will be converted to
- * strings using the toString() method.
- * @param cflags The logical OR of any combination of the compilation flags listed above.
- * @exception REException The input pattern could not be parsed.
- * @exception NullPointerException The pattern was null.
- */
- public RE(Object pattern, int cflags) throws REException {
- this(pattern,cflags,RESyntax.RE_SYNTAX_PERL5,0,0);
- }
-
- /**
- * Constructs a regular expression pattern buffer using the specified
- * compilation flags and regular expression syntax.
- *
- * @param pattern A regular expression pattern, in the form of a String,
- * StringBuffer, or char[]. Other input types will be converted to
- * strings using the toString() method.
- * @param cflags The logical OR of any combination of the compilation flags listed above.
- * @param syntax The type of regular expression syntax to use.
- * @exception REException The input pattern could not be parsed.
- * @exception NullPointerException The pattern was null.
- */
- public RE(Object pattern, int cflags, RESyntax syntax) throws REException {
- this(pattern,cflags,syntax,0,0);
- }
-
- // internal constructor used for alternation
- private RE(REToken first, REToken last,int subs, int subIndex, int minLength) {
- super(subIndex);
- firstToken = first;
- lastToken = last;
- numSubs = subs;
- minimumLength = minLength;
- addToken(new RETokenEndSub(subIndex));
- }
-
- private RE(Object patternObj, int cflags, RESyntax syntax, int myIndex, int nextSub) throws REException {
- super(myIndex); // Subexpression index of this token.
- initialize(patternObj, cflags, syntax, myIndex, nextSub);
- }
-
- // For use by subclasses
- protected RE() { super(0); }
-
- // The meat of construction
- protected void initialize(Object patternObj, int cflags, RESyntax syntax, int myIndex, int nextSub) throws REException {
- char[] pattern;
- if (patternObj instanceof String) {
- pattern = ((String) patternObj).toCharArray();
- } else if (patternObj instanceof char[]) {
- pattern = (char[]) patternObj;
- } else if (patternObj instanceof StringBuffer) {
- pattern = new char [((StringBuffer) patternObj).length()];
- ((StringBuffer) patternObj).getChars(0,pattern.length,pattern,0);
- } else {
- pattern = patternObj.toString().toCharArray();
- }
-
- int pLength = pattern.length;
-
- numSubs = 0; // Number of subexpressions in this token.
- Vector branches = null;
-
- // linked list of tokens (sort of -- some closed loops can exist)
- firstToken = lastToken = null;
-
- // Precalculate these so we don't pay for the math every time we
- // need to access them.
- boolean insens = ((cflags & REG_ICASE) > 0);
-
- // Parse pattern into tokens. Does anyone know if it's more efficient
- // to use char[] than a String.charAt()? I'm assuming so.
-
- // index tracks the position in the char array
- int index = 0;
-
- // this will be the current parse character (pattern[index])
- CharUnit unit = new CharUnit();
-
- // This is used for {x,y} calculations
- IntPair minMax = new IntPair();
-
- // Buffer a token so we can create a TokenRepeated, etc.
- REToken currentToken = null;
- char ch;
-
- while (index < pLength) {
- // read the next character unit (including backslash escapes)
- index = getCharUnit(pattern,index,unit);
-
- // ALTERNATION OPERATOR
- // \| or | (if RE_NO_BK_VBAR) or newline (if RE_NEWLINE_ALT)
- // not available if RE_LIMITED_OPS is set
-
- // TODO: the '\n' literal here should be a test against REToken.newline,
- // which unfortunately may be more than a single character.
- if ( ( (unit.ch == '|' && (syntax.get(RESyntax.RE_NO_BK_VBAR) ^ unit.bk))
- || (syntax.get(RESyntax.RE_NEWLINE_ALT) && (unit.ch == '\n') && !unit.bk) )
- && !syntax.get(RESyntax.RE_LIMITED_OPS)) {
- // make everything up to here be a branch. create vector if nec.
- addToken(currentToken);
- RE theBranch = new RE(firstToken, lastToken, numSubs, subIndex, minimumLength);
- minimumLength = 0;
- if (branches == null) {
- branches = new Vector();
- }
- branches.addElement(theBranch);
- firstToken = lastToken = currentToken = null;
- }
-
- // INTERVAL OPERATOR:
- // {x} | {x,} | {x,y} (RE_INTERVALS && RE_NO_BK_BRACES)
- // \{x\} | \{x,\} | \{x,y\} (RE_INTERVALS && !RE_NO_BK_BRACES)
- //
- // OPEN QUESTION:
- // what is proper interpretation of '{' at start of string?
-
- else if ((unit.ch == '{') && syntax.get(RESyntax.RE_INTERVALS) && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ unit.bk)) {
- int newIndex = getMinMax(pattern,index,minMax,syntax);
- if (newIndex > index) {
- if (minMax.first > minMax.second)
- throw new REException(getLocalizedMessage("interval.order"),REException.REG_BADRPT,newIndex);
- if (currentToken == null)
- throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,newIndex);
- if (currentToken instanceof RETokenRepeated)
- throw new REException(getLocalizedMessage("repeat.chained"),REException.REG_BADRPT,newIndex);
- if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
- throw new REException(getLocalizedMessage("repeat.assertion"),REException.REG_BADRPT,newIndex);
- if ((currentToken.getMinimumLength() == 0) && (minMax.second == Integer.MAX_VALUE))
- throw new REException(getLocalizedMessage("repeat.empty.token"),REException.REG_BADRPT,newIndex);
- index = newIndex;
- currentToken = setRepeated(currentToken,minMax.first,minMax.second,index);
- }
- else {
- addToken(currentToken);
- currentToken = new RETokenChar(subIndex,unit.ch,insens);
- }
- }
-
- // LIST OPERATOR:
- // [...] | [^...]
-
- else if ((unit.ch == '[') && !unit.bk) {
- Vector options = new Vector();
- boolean negative = false;
- char lastChar = 0;
- if (index == pLength) throw new REException(getLocalizedMessage("unmatched.bracket"),REException.REG_EBRACK,index);
-
- // Check for initial caret, negation
- if ((ch = pattern[index]) == '^') {
- negative = true;
- if (++index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
- ch = pattern[index];
- }
-
- // Check for leading right bracket literal
- if (ch == ']') {
- lastChar = ch;
- if (++index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
- }
-
- while ((ch = pattern[index++]) != ']') {
- if ((ch == '-') && (lastChar != 0)) {
- if (index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
- if ((ch = pattern[index]) == ']') {
- options.addElement(new RETokenChar(subIndex,lastChar,insens));
- lastChar = '-';
- } else {
- options.addElement(new RETokenRange(subIndex,lastChar,ch,insens));
- lastChar = 0;
- index++;
- }
- } else if ((ch == '\\') && syntax.get(RESyntax.RE_BACKSLASH_ESCAPE_IN_LISTS)) {
- if (index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
- int posixID = -1;
- boolean negate = false;
- char asciiEsc = 0;
- if (("dswDSW".indexOf(pattern[index]) != -1) && syntax.get(RESyntax.RE_CHAR_CLASS_ESC_IN_LISTS)) {
- switch (pattern[index]) {
- case 'D':
- negate = true;
- case 'd':
- posixID = RETokenPOSIX.DIGIT;
- break;
- case 'S':
- negate = true;
- case 's':
- posixID = RETokenPOSIX.SPACE;
- break;
- case 'W':
- negate = true;
- case 'w':
- posixID = RETokenPOSIX.ALNUM;
- break;
- }
- }
- else if ("nrt".indexOf(pattern[index]) != -1) {
- switch (pattern[index]) {
- case 'n':
- asciiEsc = '\n';
- break;
- case 't':
- asciiEsc = '\t';
- break;
- case 'r':
- asciiEsc = '\r';
- break;
- }
- }
- if (lastChar != 0) options.addElement(new RETokenChar(subIndex,lastChar,insens));
-
- if (posixID != -1) {
- options.addElement(new RETokenPOSIX(subIndex,posixID,insens,negate));
- } else if (asciiEsc != 0) {
- lastChar = asciiEsc;
- } else {
- lastChar = pattern[index];
- }
- ++index;
- } else if ((ch == '[') && (syntax.get(RESyntax.RE_CHAR_CLASSES)) && (index < pLength) && (pattern[index] == ':')) {
- StringBuffer posixSet = new StringBuffer();
- index = getPosixSet(pattern,index+1,posixSet);
- int posixId = RETokenPOSIX.intValue(posixSet.toString());
- if (posixId != -1)
- options.addElement(new RETokenPOSIX(subIndex,posixId,insens,false));
- } else {
- if (lastChar != 0) options.addElement(new RETokenChar(subIndex,lastChar,insens));
- lastChar = ch;
- }
- if (index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
- } // while in list
- // Out of list, index is one past ']'
-
- if (lastChar != 0) options.addElement(new RETokenChar(subIndex,lastChar,insens));
-
- // Create a new RETokenOneOf
- addToken(currentToken);
- options.trimToSize();
- currentToken = new RETokenOneOf(subIndex,options,negative);
- }
-
- // SUBEXPRESSIONS
- // (...) | \(...\) depending on RE_NO_BK_PARENS
-
- else if ((unit.ch == '(') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ unit.bk)) {
- boolean pure = false;
- boolean comment = false;
- boolean lookAhead = false;
- boolean negativelh = false;
- if ((index+1 < pLength) && (pattern[index] == '?')) {
- switch (pattern[index+1]) {
- case '!':
- if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
- pure = true;
- negativelh = true;
- lookAhead = true;
- index += 2;
- }
- break;
- case '=':
- if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
- pure = true;
- lookAhead = true;
- index += 2;
- }
- break;
- case ':':
- if (syntax.get(RESyntax.RE_PURE_GROUPING)) {
- pure = true;
- index += 2;
- }
- break;
- case '#':
- if (syntax.get(RESyntax.RE_COMMENTS)) {
- comment = true;
- }
- break;
- default:
- throw new REException(getLocalizedMessage("repeat.no.token"), REException.REG_BADRPT, index);
- }
- }
-
- if (index >= pLength) {
- throw new REException(getLocalizedMessage("unmatched.paren"), REException.REG_ESUBREG,index);
- }
-
- // find end of subexpression
- int endIndex = index;
- int nextIndex = index;
- int nested = 0;
-
- while ( ((nextIndex = getCharUnit(pattern,endIndex,unit)) > 0)
- && !(nested == 0 && (unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ unit.bk)) )
- if ((endIndex = nextIndex) >= pLength)
- throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
- else if (unit.ch == '(' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ unit.bk))
- nested++;
- else if (unit.ch == ')' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ unit.bk))
- nested--;
-
- // endIndex is now position at a ')','\)'
- // nextIndex is end of string or position after ')' or '\)'
-
- if (comment) index = nextIndex;
- else { // not a comment
- // create RE subexpression as token.
- addToken(currentToken);
- if (!pure) {
- numSubs++;
- }
-
- int useIndex = (pure || lookAhead) ? 0 : nextSub + numSubs;
- currentToken = new RE(String.valueOf(pattern,index,endIndex-index).toCharArray(),cflags,syntax,useIndex,nextSub + numSubs);
- numSubs += ((RE) currentToken).getNumSubs();
-
- if (lookAhead) {
- currentToken = new RETokenLookAhead(currentToken,negativelh);
- }
-
- index = nextIndex;
- } // not a comment
- } // subexpression
-
- // UNMATCHED RIGHT PAREN
- // ) or \) throw exception if
- // !syntax.get(RESyntax.RE_UNMATCHED_RIGHT_PAREN_ORD)
- else if (!syntax.get(RESyntax.RE_UNMATCHED_RIGHT_PAREN_ORD) && ((unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ unit.bk))) {
- throw new REException(getLocalizedMessage("unmatched.paren"),REException.REG_EPAREN,index);
- }
-
- // START OF LINE OPERATOR
- // ^
-
- else if ((unit.ch == '^') && !unit.bk) {
- addToken(currentToken);
- currentToken = null;
- addToken(new RETokenStart(subIndex,((cflags & REG_MULTILINE) > 0) ? syntax.getLineSeparator() : null));
- }
-
- // END OF LINE OPERATOR
- // $
-
- else if ((unit.ch == '$') && !unit.bk) {
- addToken(currentToken);
- currentToken = null;
- addToken(new RETokenEnd(subIndex,((cflags & REG_MULTILINE) > 0) ? syntax.getLineSeparator() : null));
- }
-
- // MATCH-ANY-CHARACTER OPERATOR (except possibly newline and null)
- // .
-
- else if ((unit.ch == '.') && !unit.bk) {
- addToken(currentToken);
- currentToken = new RETokenAny(subIndex,syntax.get(RESyntax.RE_DOT_NEWLINE) || ((cflags & REG_DOT_NEWLINE) > 0),syntax.get(RESyntax.RE_DOT_NOT_NULL));
- }
-
- // ZERO-OR-MORE REPEAT OPERATOR
- // *
-
- else if ((unit.ch == '*') && !unit.bk) {
- if (currentToken == null)
- throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
- if (currentToken instanceof RETokenRepeated)
- throw new REException(getLocalizedMessage("repeat.chained"),REException.REG_BADRPT,index);
- if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
- throw new REException(getLocalizedMessage("repeat.assertion"),REException.REG_BADRPT,index);
- if (currentToken.getMinimumLength() == 0)
- throw new REException(getLocalizedMessage("repeat.empty.token"),REException.REG_BADRPT,index);
- currentToken = setRepeated(currentToken,0,Integer.MAX_VALUE,index);
- }
-
- // ONE-OR-MORE REPEAT OPERATOR
- // + | \+ depending on RE_BK_PLUS_QM
- // not available if RE_LIMITED_OPS is set
-
- else if ((unit.ch == '+') && !syntax.get(RESyntax.RE_LIMITED_OPS) && (!syntax.get(RESyntax.RE_BK_PLUS_QM) ^ unit.bk)) {
- if (currentToken == null)
- throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
- if (currentToken instanceof RETokenRepeated)
- throw new REException(getLocalizedMessage("repeat.chained"),REException.REG_BADRPT,index);
- if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
- throw new REException(getLocalizedMessage("repeat.assertion"),REException.REG_BADRPT,index);
- if (currentToken.getMinimumLength() == 0)
- throw new REException(getLocalizedMessage("repeat.empty.token"),REException.REG_BADRPT,index);
- currentToken = setRepeated(currentToken,1,Integer.MAX_VALUE,index);
- }
-
- // ZERO-OR-ONE REPEAT OPERATOR / STINGY MATCHING OPERATOR
- // ? | \? depending on RE_BK_PLUS_QM
- // not available if RE_LIMITED_OPS is set
- // stingy matching if RE_STINGY_OPS is set and it follows a quantifier
-
- else if ((unit.ch == '?') && !syntax.get(RESyntax.RE_LIMITED_OPS) && (!syntax.get(RESyntax.RE_BK_PLUS_QM) ^ unit.bk)) {
- if (currentToken == null) throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
-
- // Check for stingy matching on RETokenRepeated
- if (currentToken instanceof RETokenRepeated) {
- if (syntax.get(RESyntax.RE_STINGY_OPS) && !((RETokenRepeated)currentToken).isStingy())
- ((RETokenRepeated)currentToken).makeStingy();
- else
- throw new REException(getLocalizedMessage("repeat.chained"),REException.REG_BADRPT,index);
- }
- else if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
- throw new REException(getLocalizedMessage("repeat.assertion"),REException.REG_BADRPT,index);
- else
- currentToken = setRepeated(currentToken,0,1,index);
- }
-
- // BACKREFERENCE OPERATOR
- // \1 \2 ... \9
- // not available if RE_NO_BK_REFS is set
-
- else if (unit.bk && Character.isDigit(unit.ch) && !syntax.get(RESyntax.RE_NO_BK_REFS)) {
- addToken(currentToken);
- currentToken = new RETokenBackRef(subIndex,Character.digit(unit.ch,10),insens);
- }
-
- // START OF STRING OPERATOR
- // \A if RE_STRING_ANCHORS is set
-
- else if (unit.bk && (unit.ch == 'A') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
- addToken(currentToken);
- currentToken = new RETokenStart(subIndex,null);
- }
-
- // WORD BREAK OPERATOR
- // \b if ????
-
- else if (unit.bk && (unit.ch == 'b') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
- addToken(currentToken);
- currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN | RETokenWordBoundary.END, false);
- }
-
- // WORD BEGIN OPERATOR
- // \< if ????
- else if (unit.bk && (unit.ch == '<')) {
- addToken(currentToken);
- currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN, false);
- }
-
- // WORD END OPERATOR
- // \> if ????
- else if (unit.bk && (unit.ch == '>')) {
- addToken(currentToken);
- currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.END, false);
- }
-
- // NON-WORD BREAK OPERATOR
- // \B if ????
-
- else if (unit.bk && (unit.ch == 'B') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
- addToken(currentToken);
- currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN | RETokenWordBoundary.END, true);
- }
-
-
- // DIGIT OPERATOR
- // \d if RE_CHAR_CLASS_ESCAPES is set
-
- else if (unit.bk && (unit.ch == 'd') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
- addToken(currentToken);
- currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.DIGIT,insens,false);
- }
-
- // NON-DIGIT OPERATOR
- // \D
-
- else if (unit.bk && (unit.ch == 'D') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
- addToken(currentToken);
- currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.DIGIT,insens,true);
- }
-
- // NEWLINE ESCAPE
- // \n
-
- else if (unit.bk && (unit.ch == 'n')) {
- addToken(currentToken);
- currentToken = new RETokenChar(subIndex,'\n',false);
- }
-
- // RETURN ESCAPE
- // \r
-
- else if (unit.bk && (unit.ch == 'r')) {
- addToken(currentToken);
- currentToken = new RETokenChar(subIndex,'\r',false);
- }
-
- // WHITESPACE OPERATOR
- // \s if RE_CHAR_CLASS_ESCAPES is set
-
- else if (unit.bk && (unit.ch == 's') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
- addToken(currentToken);
- currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.SPACE,insens,false);
- }
-
- // NON-WHITESPACE OPERATOR
- // \S
-
- else if (unit.bk && (unit.ch == 'S') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
- addToken(currentToken);
- currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.SPACE,insens,true);
- }
-
- // TAB ESCAPE
- // \t
-
- else if (unit.bk && (unit.ch == 't')) {
- addToken(currentToken);
- currentToken = new RETokenChar(subIndex,'\t',false);
- }
-
- // ALPHANUMERIC OPERATOR
- // \w
-
- else if (unit.bk && (unit.ch == 'w') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
- addToken(currentToken);
- currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.ALNUM,insens,false);
- }
-
- // NON-ALPHANUMERIC OPERATOR
- // \W
-
- else if (unit.bk && (unit.ch == 'W') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
- addToken(currentToken);
- currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.ALNUM,insens,true);
- }
-
- // END OF STRING OPERATOR
- // \Z
-
- else if (unit.bk && (unit.ch == 'Z') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
- addToken(currentToken);
- currentToken = new RETokenEnd(subIndex,null);
- }
-
- // NON-SPECIAL CHARACTER (or escape to make literal)
- // c | \* for example
-
- else { // not a special character
- addToken(currentToken);
- currentToken = new RETokenChar(subIndex,unit.ch,insens);
- }
- } // end while
-
- // Add final buffered token and an EndSub marker
- addToken(currentToken);
-
- if (branches != null) {
- branches.addElement(new RE(firstToken,lastToken,numSubs,subIndex,minimumLength));
- branches.trimToSize(); // compact the Vector
- minimumLength = 0;
- firstToken = lastToken = null;
- addToken(new RETokenOneOf(subIndex,branches,false));
- }
- else addToken(new RETokenEndSub(subIndex));
-
- }
-
- private static int getCharUnit(char[] input, int index, CharUnit unit) throws REException {
- unit.ch = input[index++];
- if (unit.bk = (unit.ch == '\\'))
- if (index < input.length)
- unit.ch = input[index++];
- else throw new REException(getLocalizedMessage("ends.with.backslash"),REException.REG_ESCAPE,index);
- return index;
- }
-
- /**
- * Checks if the regular expression matches the input in its entirety.
- *
- * @param input The input text.
- */
- public boolean isMatch(Object input) {
- return isMatch(input,0,0);
- }
-
- /**
- * Checks if the input string, starting from index, is an exact match of
- * this regular expression.
- *
- * @param input The input text.
- * @param index The offset index at which the search should be begin.
- */
- public boolean isMatch(Object input,int index) {
- return isMatch(input,index,0);
- }
-
-
- /**
- * Checks if the input, starting from index and using the specified
- * execution flags, is an exact match of this regular expression.
- *
- * @param input The input text.
- * @param index The offset index at which the search should be begin.
- * @param eflags The logical OR of any execution flags above.
- */
- public boolean isMatch(Object input,int index,int eflags) {
- return isMatchImpl(makeCharIndexed(input,index),index,eflags);
- }
-
- private boolean isMatchImpl(CharIndexed input, int index, int eflags) {
- if (firstToken == null) // Trivial case
- return (input.charAt(0) == CharIndexed.OUT_OF_BOUNDS);
- REMatch m = new REMatch(numSubs, index, eflags);
- if (firstToken.match(input, m)) {
- while (m != null) {
- if (input.charAt(m.index) == CharIndexed.OUT_OF_BOUNDS) {
- return true;
- }
- m = m.next;
- }
- }
- return false;
- }
-
- /**
- * Returns the maximum number of subexpressions in this regular expression.
- * If the expression contains branches, the value returned will be the
- * maximum subexpressions in any of the branches.
- */
- public int getNumSubs() {
- return numSubs;
- }
-
- // Overrides REToken.setUncle
- void setUncle(REToken uncle) {
- if (lastToken != null) {
- lastToken.setUncle(uncle);
- } else super.setUncle(uncle); // to deal with empty subexpressions
- }
-
- // Overrides REToken.chain
-
- boolean chain(REToken next) {
- super.chain(next);
- setUncle(next);
- return true;
- }
-
- /**
- * Returns the minimum number of characters that could possibly
- * constitute a match of this regular expression.
- */
- public int getMinimumLength() {
- return minimumLength;
- }
-
- /**
- * Returns an array of all matches found in the input.
- *
- * If the regular expression allows the empty string to match, it will
- * substitute matches at all positions except the end of the input.
- *
- * @param input The input text.
- * @return a non-null (but possibly zero-length) array of matches
- */
- public REMatch[] getAllMatches(Object input) {
- return getAllMatches(input,0,0);
- }
-
- /**
- * Returns an array of all matches found in the input,
- * beginning at the specified index position.
- *
- * If the regular expression allows the empty string to match, it will
- * substitute matches at all positions except the end of the input.
- *
- * @param input The input text.
- * @param index The offset index at which the search should be begin.
- * @return a non-null (but possibly zero-length) array of matches
- */
- public REMatch[] getAllMatches(Object input, int index) {
- return getAllMatches(input,index,0);
- }
-
- /**
- * Returns an array of all matches found in the input string,
- * beginning at the specified index position and using the specified
- * execution flags.
- *
- * If the regular expression allows the empty string to match, it will
- * substitute matches at all positions except the end of the input.
- *
- * @param input The input text.
- * @param index The offset index at which the search should be begin.
- * @param eflags The logical OR of any execution flags above.
- * @return a non-null (but possibly zero-length) array of matches
- */
- public REMatch[] getAllMatches(Object input, int index, int eflags) {
- return getAllMatchesImpl(makeCharIndexed(input,index),index,eflags);
- }
-
- // this has been changed since 1.03 to be non-overlapping matches
- private REMatch[] getAllMatchesImpl(CharIndexed input, int index, int eflags) {
- Vector all = new Vector();
- REMatch m = null;
- while ((m = getMatchImpl(input,index,eflags,null)) != null) {
- all.addElement(m);
- index = m.getEndIndex();
- if (m.end[0] == 0) { // handle pathological case of zero-length match
- index++;
- input.move(1);
- } else {
- input.move(m.end[0]);
- }
- if (!input.isValid()) break;
- }
- REMatch[] mset = new REMatch[all.size()];
- all.copyInto(mset);
- return mset;
- }
-
- /* Implements abstract method REToken.match() */
- boolean match(CharIndexed input, REMatch mymatch) {
- if (firstToken == null) return next(input, mymatch);
-
- // Note the start of this subexpression
- mymatch.start[subIndex] = mymatch.index;
-
- return firstToken.match(input, mymatch);
- }
-
- /**
- * Returns the first match found in the input. If no match is found,
- * null is returned.
- *
- * @param input The input text.
- * @return An REMatch instance referencing the match, or null if none.
- */
- public REMatch getMatch(Object input) {
- return getMatch(input,0,0);
- }
-
- /**
- * Returns the first match found in the input, beginning
- * the search at the specified index. If no match is found,
- * returns null.
- *
- * @param input The input text.
- * @param index The offset within the text to begin looking for a match.
- * @return An REMatch instance referencing the match, or null if none.
- */
- public REMatch getMatch(Object input, int index) {
- return getMatch(input,index,0);
- }
-
- /**
- * Returns the first match found in the input, beginning
- * the search at the specified index, and using the specified
- * execution flags. If no match is found, returns null.
- *
- * @param input The input text.
- * @param index The offset index at which the search should be begin.
- * @param eflags The logical OR of any execution flags above.
- * @return An REMatch instance referencing the match, or null if none.
- */
- public REMatch getMatch(Object input, int index, int eflags) {
- return getMatch(input,index,eflags,null);
- }
-
- /**
- * Returns the first match found in the input, beginning the search
- * at the specified index, and using the specified execution flags.
- * If no match is found, returns null. If a StringBuffer is
- * provided and is non-null, the contents of the input text from the
- * index to the beginning of the match (or to the end of the input,
- * if there is no match) are appended to the StringBuffer.
- *
- * @param input The input text.
- * @param index The offset index at which the search should be begin.
- * @param eflags The logical OR of any execution flags above.
- * @param buffer The StringBuffer to save pre-match text in.
- * @return An REMatch instance referencing the match, or null if none. */
- public REMatch getMatch(Object input, int index, int eflags, StringBuffer buffer) {
- return getMatchImpl(makeCharIndexed(input,index),index,eflags,buffer);
- }
-
- REMatch getMatchImpl(CharIndexed input, int anchor, int eflags, StringBuffer buffer) {
- // Create a new REMatch to hold results
- REMatch mymatch = new REMatch(numSubs, anchor, eflags);
- do {
- // Optimization: check if anchor + minimumLength > length
- if (minimumLength == 0 || input.charAt(minimumLength-1) != CharIndexed.OUT_OF_BOUNDS) {
- if (match(input, mymatch)) {
- // Find longest match of them all to observe leftmost longest
- REMatch longest = mymatch;
- while ((mymatch = mymatch.next) != null) {
- if (mymatch.index > longest.index) {
- longest = mymatch;
- }
- }
-
- longest.end[0] = longest.index;
- longest.finish(input);
- return longest;
- }
- }
- mymatch.clear(++anchor);
- // Append character to buffer if needed
- if (buffer != null && input.charAt(0) != CharIndexed.OUT_OF_BOUNDS) {
- buffer.append(input.charAt(0));
- }
- } while (input.move(1));
-
- return null;
- }
-
- /**
- * Returns an REMatchEnumeration that can be used to iterate over the
- * matches found in the input text.
- *
- * @param input The input text.
- * @return A non-null REMatchEnumeration instance.
- */
- public REMatchEnumeration getMatchEnumeration(Object input) {
- return getMatchEnumeration(input,0,0);
- }
-
-
- /**
- * Returns an REMatchEnumeration that can be used to iterate over the
- * matches found in the input text.
- *
- * @param input The input text.
- * @param index The offset index at which the search should be begin.
- * @return A non-null REMatchEnumeration instance, with its input cursor
- * set to the index position specified.
- */
- public REMatchEnumeration getMatchEnumeration(Object input, int index) {
- return getMatchEnumeration(input,index,0);
- }
-
- /**
- * Returns an REMatchEnumeration that can be used to iterate over the
- * matches found in the input text.
- *
- * @param input The input text.
- * @param index The offset index at which the search should be begin.
- * @param eflags The logical OR of any execution flags above.
- * @return A non-null REMatchEnumeration instance, with its input cursor
- * set to the index position specified.
- */
- public REMatchEnumeration getMatchEnumeration(Object input, int index, int eflags) {
- return new REMatchEnumeration(this,makeCharIndexed(input,index),index,eflags);
- }
-
-
- /**
- * Substitutes the replacement text for the first match found in the input.
- *
- * @param input The input text.
- * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
- * @return A String interpolating the substituted text.
- * @see REMatch#substituteInto
- */
- public String substitute(Object input,String replace) {
- return substitute(input,replace,0,0);
- }
-
- /**
- * Substitutes the replacement text for the first match found in the input
- * beginning at the specified index position. Specifying an index
- * effectively causes the regular expression engine to throw away the
- * specified number of characters.
- *
- * @param input The input text.
- * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
- * @param index The offset index at which the search should be begin.
- * @return A String containing the substring of the input, starting
- * at the index position, and interpolating the substituted text.
- * @see REMatch#substituteInto
- */
- public String substitute(Object input,String replace,int index) {
- return substitute(input,replace,index,0);
- }
-
- /**
- * Substitutes the replacement text for the first match found in the input
- * string, beginning at the specified index position and using the
- * specified execution flags.
- *
- * @param input The input text.
- * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
- * @param index The offset index at which the search should be begin.
- * @param eflags The logical OR of any execution flags above.
- * @return A String containing the substring of the input, starting
- * at the index position, and interpolating the substituted text.
- * @see REMatch#substituteInto
- */
- public String substitute(Object input,String replace,int index,int eflags) {
- return substituteImpl(makeCharIndexed(input,index),replace,index,eflags);
- }
-
- private String substituteImpl(CharIndexed input,String replace,int index,int eflags) {
- StringBuffer buffer = new StringBuffer();
- REMatch m = getMatchImpl(input,index,eflags,buffer);
- if (m==null) return buffer.toString();
- buffer.append( ((eflags & REG_NO_INTERPOLATE) > 0) ?
- replace : m.substituteInto(replace) );
- if (input.move(m.end[0])) {
- do {
- buffer.append(input.charAt(0));
- } while (input.move(1));
- }
- return buffer.toString();
- }
-
- /**
- * Substitutes the replacement text for each non-overlapping match found
- * in the input text.
- *
- * @param input The input text.
- * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
- * @return A String interpolating the substituted text.
- * @see REMatch#substituteInto
- */
- public String substituteAll(Object input,String replace) {
- return substituteAll(input,replace,0,0);
- }
-
- /**
- * Substitutes the replacement text for each non-overlapping match found
- * in the input text, starting at the specified index.
- *
- * If the regular expression allows the empty string to match, it will
- * substitute matches at all positions except the end of the input.
- *
- * @param input The input text.
- * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
- * @param index The offset index at which the search should be begin.
- * @return A String containing the substring of the input, starting
- * at the index position, and interpolating the substituted text.
- * @see REMatch#substituteInto
- */
- public String substituteAll(Object input,String replace,int index) {
- return substituteAll(input,replace,index,0);
- }
-
- /**
- * Substitutes the replacement text for each non-overlapping match found
- * in the input text, starting at the specified index and using the
- * specified execution flags.
- *
- * @param input The input text.
- * @param replace The replacement text, which may contain $x metacharacters (see REMatch.substituteInto).
- * @param index The offset index at which the search should be begin.
- * @param eflags The logical OR of any execution flags above.
- * @return A String containing the substring of the input, starting
- * at the index position, and interpolating the substituted text.
- * @see REMatch#substituteInto
- */
- public String substituteAll(Object input,String replace,int index,int eflags) {
- return substituteAllImpl(makeCharIndexed(input,index),replace,index,eflags);
- }
-
- private String substituteAllImpl(CharIndexed input,String replace,int index,int eflags) {
- StringBuffer buffer = new StringBuffer();
- REMatch m;
- while ((m = getMatchImpl(input,index,eflags,buffer)) != null) {
- buffer.append( ((eflags & REG_NO_INTERPOLATE) > 0) ?
- replace : m.substituteInto(replace) );
- index = m.getEndIndex();
- if (m.end[0] == 0) {
- char ch = input.charAt(0);
- if (ch != CharIndexed.OUT_OF_BOUNDS)
- buffer.append(ch);
- input.move(1);
- } else {
- input.move(m.end[0]);
- }
-
- if (!input.isValid()) break;
- }
- return buffer.toString();
- }
-
- /* Helper function for constructor */
- private void addToken(REToken next) {
- if (next == null) return;
- minimumLength += next.getMinimumLength();
- if (firstToken == null) {
- lastToken = firstToken = next;
- } else {
- // if chain returns false, it "rejected" the token due to
- // an optimization, and next was combined with lastToken
- if (lastToken.chain(next)) {
- lastToken = next;
- }
- }
- }
-
- private static REToken setRepeated(REToken current, int min, int max, int index) throws REException {
- if (current == null) throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
- return new RETokenRepeated(current.subIndex,current,min,max);
- }
-
- private static int getPosixSet(char[] pattern,int index,StringBuffer buf) {
- // Precondition: pattern[index-1] == ':'
- // we will return pos of closing ']'.
- int i;
- for (i=index; i<(pattern.length-1); i++) {
- if ((pattern[i] == ':') && (pattern[i+1] == ']'))
- return i+2;
- buf.append(pattern[i]);
- }
- return index; // didn't match up
- }
-
- private int getMinMax(char[] input,int index,IntPair minMax,RESyntax syntax) throws REException {
- // Precondition: input[index-1] == '{', minMax != null
-
- boolean mustMatch = !syntax.get(RESyntax.RE_NO_BK_BRACES);
- int startIndex = index;
- if (index == input.length) {
- if (mustMatch)
- throw new REException(getLocalizedMessage("unmatched.brace"),REException.REG_EBRACE,index);
- else
- return startIndex;
- }
-
- int min,max=0;
- CharUnit unit = new CharUnit();
- StringBuffer buf = new StringBuffer();
-
- // Read string of digits
- do {
- index = getCharUnit(input,index,unit);
- if (Character.isDigit(unit.ch))
- buf.append(unit.ch);
- } while ((index != input.length) && Character.isDigit(unit.ch));
-
- // Check for {} tomfoolery
- if (buf.length() == 0) {
- if (mustMatch)
- throw new REException(getLocalizedMessage("interval.error"),REException.REG_EBRACE,index);
- else
- return startIndex;
- }
-
- min = Integer.parseInt(buf.toString());
-
- if ((unit.ch == '}') && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ unit.bk))
- max = min;
- else if (index == input.length)
- if (mustMatch)
- throw new REException(getLocalizedMessage("interval.no.end"),REException.REG_EBRACE,index);
- else
- return startIndex;
- else if ((unit.ch == ',') && !unit.bk) {
- buf = new StringBuffer();
- // Read string of digits
- while (((index = getCharUnit(input,index,unit)) != input.length) && Character.isDigit(unit.ch))
- buf.append(unit.ch);
-
- if (!((unit.ch == '}') && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ unit.bk)))
- if (mustMatch)
- throw new REException(getLocalizedMessage("interval.error"),REException.REG_EBRACE,index);
- else
- return startIndex;
-
- // This is the case of {x,}
- if (buf.length() == 0) max = Integer.MAX_VALUE;
- else max = Integer.parseInt(buf.toString());
- } else
- if (mustMatch)
- throw new REException(getLocalizedMessage("interval.error"),REException.REG_EBRACE,index);
- else
- return startIndex;
-
- // We know min and max now, and they are valid.
-
- minMax.first = min;
- minMax.second = max;
-
- // return the index following the '}'
- return index;
- }
-
- /**
- * Return a human readable form of the compiled regular expression,
- * useful for debugging.
- */
- public String toString() {
- StringBuffer sb = new StringBuffer();
- dump(sb);
- return sb.toString();
- }
-
- void dump(StringBuffer os) {
- os.append('(');
- if (subIndex == 0)
- os.append("?:");
- if (firstToken != null)
- firstToken.dumpAll(os);
- os.append(')');
- }
-
- // Cast input appropriately or throw exception
- private static CharIndexed makeCharIndexed(Object input, int index) {
- // We could let a String fall through to final input, but since
- // it's the most likely input type, we check it first.
- if (input instanceof String)
- return new CharIndexedString((String) input,index);
- else if (input instanceof char[])
- return new CharIndexedCharArray((char[]) input,index);
- else if (input instanceof StringBuffer)
- return new CharIndexedStringBuffer((StringBuffer) input,index);
- else if (input instanceof InputStream)
- return new CharIndexedInputStream((InputStream) input,index);
- else if (input instanceof Reader)
- return new CharIndexedReader((Reader) input, index);
- else if (input instanceof CharIndexed)
- return (CharIndexed) input; // do we lose index info?
- else
- return new CharIndexedString(input.toString(), index);
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/REException.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-import java.text.MessageFormat;
-
-/**
- * This is the regular expression exception class. An exception of this type
- * defines the three attributes:
- * <OL>
- * <LI> A descriptive message of the error.
- * <LI> An integral type code equivalent to one of the statically
- * defined symbols listed below.
- * <LI> The approximate position in the input string where the error
- * occurred.
- * </OL>
- *
- * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- */
-
-public class REException extends Exception {
- private int type;
- private int pos;
-
- // Error conditions from GNU regcomp(3) manual
-
- /**
- * Error flag.
- * Invalid use of repetition operators such as using
- * `*' as the first character.
- */
- public static final int REG_BADRPT = 1;
-
- /**
- * Error flag.
- * Invalid use of back reference operator.
- */
- public static final int REG_BADBR = 2;
-
- /**
- * Error flag.
- * Un-matched brace interval operators.
- */
- public static final int REG_EBRACE = 3;
-
- /**
- * Error flag.
- * Un-matched bracket list operators.
- */
- public static final int REG_EBRACK = 4;
-
- /**
- * Error flag.
- * Invalid use of the range operator, eg. the ending
- * point of the range occurs prior to the starting
- * point.
- */
- public static final int REG_ERANGE = 5;
-
- /**
- * Error flag.
- * Unknown character class name. <B>Not implemented</B>.
- */
- public static final int REG_ECTYPE = 6;
-
- /**
- * Error flag.
- * Un-matched parenthesis group operators.
- */
- public static final int REG_EPAREN = 7;
-
- /**
- * Error flag.
- * Invalid back reference to a subexpression.
- */
- public static final int REG_ESUBREG = 8;
-
- /**
- * Error flag.
- * Non specific error. <B>Not implemented</B>.
- */
- public static final int REG_EEND = 9;
-
- /**
- * Error flag.
- * Invalid escape sequence. <B>Not implemented</B>.
- */
- public static final int REG_ESCAPE = 10;
-
- /**
- * Error flag.
- * Invalid use of pattern operators such as group or list.
- */
- public static final int REG_BADPAT = 11;
-
- /**
- * Error flag.
- * Compiled regular expression requires a pattern
- * buffer larger than 64Kb. <B>Not implemented</B>.
- */
- public static final int REG_ESIZE = 12;
-
- /**
- * Error flag.
- * The regex routines ran out of memory. <B>Not implemented</B>.
- */
- public static final int REG_ESPACE = 13;
-
- REException(String msg, int type, int position) {
- super(msg);
- this.type = type;
- this.pos = position;
- }
-
- /**
- * Returns the type of the exception, one of the constants listed above.
- */
-
- public int getType() {
- return type;
- }
-
- /**
- * Returns the position, relative to the string or character array being
- * compiled, where the error occurred. This position is generally the point
- * where the error was detected, not necessarily the starting index of
- * a bad subexpression.
- */
- public int getPosition() {
- return pos;
- }
-
- /**
- * Reports the descriptive message associated with this exception
- * as well as its index position in the string or character array
- * being compiled.
- */
- public String getMessage() {
- Object[] args = {new Integer(pos)};
- StringBuffer sb = new StringBuffer();
- String prefix = RE.getLocalizedMessage("error.prefix");
- sb.append(MessageFormat.format(prefix, args));
- sb.append('\n');
- sb.append(super.getMessage());
- return sb.toString();
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/REFilterInputStream.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.io.FilterInputStream;
-import java.io.InputStream;
-
-/**
- * Replaces instances of a given RE found within an InputStream
- * with replacement text. The replacements are interpolated into the
- * stream when a match is found.
- *
- * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- * @deprecated This class cannot properly handle all character
- * encodings. For proper handling, use the REFilterReader
- * class instead.
- */
-
-public class REFilterInputStream extends FilterInputStream {
-
- private RE expr;
- private String replace;
- private String buffer;
- private int bufpos;
- private int offset;
- private CharIndexedInputStream stream;
-
- /**
- * Creates an REFilterInputStream. When reading from this stream,
- * occurrences of patterns matching the supplied regular expression
- * will be replaced with the supplied replacement text (the
- * metacharacters $0 through $9 may be used to refer to the full
- * match or subexpression matches).
- *
- * @param stream The InputStream to be filtered.
- * @param expr The regular expression to search for.
- * @param replace The text pattern to replace matches with.
- */
- public REFilterInputStream(InputStream stream, RE expr, String replace) {
- super(stream);
- this.stream = new CharIndexedInputStream(stream,0);
- this.expr = expr;
- this.replace = replace;
- }
-
- /**
- * Reads the next byte from the stream per the general contract of
- * InputStream.read(). Returns -1 on error or end of stream.
- */
- public int read() {
- // If we have buffered replace data, use it.
- if ((buffer != null) && (bufpos < buffer.length())) {
- return (int) buffer.charAt(bufpos++);
- }
-
- // check if input is at a valid position
- if (!stream.isValid()) return -1;
-
- REMatch mymatch = new REMatch(expr.getNumSubs(),offset,0);
- if (expr.match(stream, mymatch)) {
- mymatch.end[0] = mymatch.index;
- mymatch.finish(stream);
- stream.move(mymatch.toString().length());
- offset += mymatch.toString().length();
- buffer = mymatch.substituteInto(replace);
- bufpos = 1;
-
- // This is prone to infinite loops if replace string turns out empty.
- if (buffer.length() > 0) {
- return buffer.charAt(0);
- }
- }
- char ch = stream.charAt(0);
- if (ch == CharIndexed.OUT_OF_BOUNDS) return -1;
- stream.move(1);
- offset++;
- return ch;
- }
-
- /**
- * Returns false. REFilterInputStream does not support mark() and
- * reset() methods.
- */
- public boolean markSupported() {
- return false;
- }
-
- /** Reads from the stream into the provided array. */
- public int read(byte[] b, int off, int len) {
- int i;
- int ok = 0;
- while (len-- > 0) {
- i = read();
- if (i == -1) return (ok == 0) ? -1 : ok;
- b[off++] = (byte) i;
- ok++;
- }
- return ok;
- }
-
- /** Reads from the stream into the provided array. */
- public int read(byte[] b) {
- return read(b,0,b.length);
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/REFilterReader.java
- * Copyright (C) 2001 Lee Sau Dan
- * Based on gnu.regexp.REFilterInputStream by Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.io.FilterReader;
-import java.io.Reader;
-
-/**
- * Replaces instances of a given RE with replacement text.
- *
- * @author <A HREF="http://www.csis.hku.hk/~sdlee/">Lee Sau Dan</A>
- * @since gnu.regexp 1.1.0
- */
-
-public class REFilterReader extends FilterReader {
-
- private RE expr;
- private String replace;
- private String buffer;
- private int bufpos;
- private int offset;
- private CharIndexedReader stream;
-
- /**
- * Creates an REFilterReader. When reading from this stream,
- * occurrences of patterns matching the supplied regular expression
- * will be replaced with the supplied replacement text (the
- * metacharacters $0 through $9 may be used to refer to the full
- * match or subexpression matches.
- *
- * @param stream The Reader to be filtered.
- * @param expr The regular expression to search for.
- * @param replace The text pattern to replace matches with.
- */
- public REFilterReader(Reader stream, RE expr, String replace) {
- super(stream);
- this.stream = new CharIndexedReader(stream,0);
- this.expr = expr;
- this.replace = replace;
- }
-
- /**
- * Reads the next character from the stream per the general contract of
- * Reader.read(). Returns -1 on error or end of stream.
- */
- public int read() {
- // If we have buffered replace data, use it.
- if ((buffer != null) && (bufpos < buffer.length())) {
- return (int) buffer.charAt(bufpos++);
- }
-
- // check if input is at a valid position
- if (!stream.isValid()) return -1;
-
- REMatch mymatch = new REMatch(expr.getNumSubs(),offset,0);
- if (expr.match(stream,mymatch)) {
- mymatch.end[0] = mymatch.index;
- mymatch.finish(stream);
- stream.move(mymatch.toString().length());
- offset += mymatch.toString().length();
- buffer = mymatch.substituteInto(replace);
- bufpos = 1;
-
- if (buffer.length() > 0) {
- return buffer.charAt(0);
- }
- }
- char ch = stream.charAt(0);
- if (ch == CharIndexed.OUT_OF_BOUNDS) return -1;
- stream.move(1);
- offset++;
- return ch;
- }
-
- /**
- * Returns false. REFilterReader does not support mark() and
- * reset() methods.
- */
- public boolean markSupported() {
- return false;
- }
-
- /** Reads from the stream into the provided array. */
- public int read(char[] b, int off, int len) {
- int i;
- int ok = 0;
- while (len-- > 0) {
- i = read();
- if (i == -1) return (ok == 0) ? -1 : ok;
- b[off++] = (char) i;
- ok++;
- }
- return ok;
- }
-
- /** Reads from the stream into the provided array. */
- public int read(char[] b) {
- return read(b,0,b.length);
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/REMatch.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.io.Serializable;
-
-/**
- * An instance of this class represents a match
- * completed by a gnu.regexp matching function. It can be used
- * to obtain relevant information about the location of a match
- * or submatch.
- *
- * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- */
-public final class REMatch implements Serializable, Cloneable {
- private String matchedText;
-
- // These variables are package scope for fast access within the engine
- int eflags; // execution flags this match was made using
-
- // Offset in source text where match was tried. This is zero-based;
- // the actual position in the source text is given by (offset + anchor).
- int offset;
-
- // Anchor position refers to the index into the source input
- // at which the matching operation began.
- // This is also useful for the ANCHORINDEX option.
- int anchor;
-
- // Package scope; used by RE.
- int index; // used while matching to mark current match position in input
- int[] start; // start positions (relative to offset) for each (sub)exp.
- int[] end; // end positions for the same
- REMatch next; // other possibility (to avoid having to use arrays)
-
- public Object clone() {
- try {
- REMatch copy = (REMatch) super.clone();
- copy.next = null;
-
- copy.start = (int[]) start.clone();
- copy.end = (int[]) end.clone();
-
- return copy;
- } catch (CloneNotSupportedException e) {
- throw new Error(); // doesn't happen
- }
- }
-
- void assignFrom(REMatch other) {
- start = other.start;
- end = other.end;
- index = other.index;
- // need to deep clone?
- next = other.next;
- }
-
- REMatch(int subs, int anchor, int eflags) {
- start = new int[subs+1];
- end = new int[subs+1];
- this.anchor = anchor;
- this.eflags = eflags;
- clear(anchor);
- }
-
- void finish(CharIndexed text) {
- start[0] = 0;
- StringBuffer sb = new StringBuffer();
- int i;
- for (i = 0; i < end[0]; i++)
- sb.append(text.charAt(i));
- matchedText = sb.toString();
- for (i = 0; i < start.length; i++) {
- // If any subexpressions didn't terminate, they don't count
- // TODO check if this code ever gets hit
- if ((start[i] == -1) ^ (end[i] == -1)) {
- start[i] = -1;
- end[i] = -1;
- }
- }
- next = null; // cut off alternates
- }
-
- /** Clears the current match and moves the offset to the new index. */
- void clear(int index) {
- offset = index;
- this.index = 0;
- for (int i = 0; i < start.length; i++) {
- start[i] = end[i] = -1;
- }
- next = null; // cut off alternates
- }
-
- /**
- * Returns the string matching the pattern. This makes it convenient
- * to write code like the following:
- * <P>
- * <code>
- * REMatch myMatch = myExpression.getMatch(myString);<br>
- * if (myMatch != null) System.out.println("Regexp found: "+myMatch);
- * </code>
- */
- public String toString() {
- return matchedText;
- }
-
- /**
- * Returns the index within the input text where the match in its entirety
- * began.
- */
- public int getStartIndex() {
- return offset + start[0];
- }
-
- /**
- * Returns the index within the input string where the match in
- * its entirety ends. The return value is the next position after
- * the end of the string; therefore, a match created by the
- * following call:
- *
- * <P>
- * <code>REMatch myMatch = myExpression.getMatch(myString);</code>
- * <P>
- * can be viewed (given that myMatch is not null) by creating
- * <P>
- * <code>String theMatch = myString.substring(myMatch.getStartIndex(),
- * myMatch.getEndIndex());</code>
- * <P>
- * But you can save yourself that work, since the <code>toString()</code>
- * method (above) does exactly that for you.
- */
- public int getEndIndex() {
- return offset + end[0];
- }
-
- /**
- * Returns the string matching the given subexpression. The subexpressions
- * are indexed starting with one, not zero. That is, the subexpression
- * identified by the first set of parentheses in a regular expression
- * could be retrieved from an REMatch by calling match.toString(1).
- *
- * @param sub Index of the subexpression.
- */
- public String toString(int sub) {
- if ((sub >= start.length) || (start[sub] == -1)) return "";
- return (matchedText.substring(start[sub],end[sub]));
- }
-
- /**
- * Returns the index within the input string used to generate this match
- * where subexpression number <i>sub</i> begins, or <code>-1</code> if
- * the subexpression does not exist. The initial position is zero.
- *
- * @param sub Subexpression index
- * @deprecated Use getStartIndex(int) instead.
- */
- public int getSubStartIndex(int sub) {
- if (sub >= start.length) return -1;
- int x = start[sub];
- return (x == -1) ? x : offset + x;
- }
-
- /**
- * Returns the index within the input string used to generate this match
- * where subexpression number <i>sub</i> begins, or <code>-1</code> if
- * the subexpression does not exist. The initial position is zero.
- *
- * @param sub Subexpression index
- * @since gnu.regexp 1.1.0
- */
- public int getStartIndex(int sub) {
- if (sub >= start.length) return -1;
- int x = start[sub];
- return (x == -1) ? x : offset + x;
- }
-
- /**
- * Returns the index within the input string used to generate this match
- * where subexpression number <i>sub</i> ends, or <code>-1</code> if
- * the subexpression does not exist. The initial position is zero.
- *
- * @param sub Subexpression index
- * @deprecated Use getEndIndex(int) instead
- */
- public int getSubEndIndex(int sub) {
- if (sub >= start.length) return -1;
- int x = end[sub];
- return (x == -1) ? x : offset + x;
- }
-
- /**
- * Returns the index within the input string used to generate this match
- * where subexpression number <i>sub</i> ends, or <code>-1</code> if
- * the subexpression does not exist. The initial position is zero.
- *
- * @param sub Subexpression index
- */
- public int getEndIndex(int sub) {
- if (sub >= start.length) return -1;
- int x = end[sub];
- return (x == -1) ? x : offset + x;
- }
-
- /**
- * Substitute the results of this match to create a new string.
- * This is patterned after PERL, so the tokens to watch out for are
- * <code>$0</code> through <code>$9</code>. <code>$0</code> matches
- * the full substring matched; <code>$<i>n</i></code> matches
- * subexpression number <i>n</i>.
- *
- * @param input A string consisting of literals and <code>$<i>n</i></code> tokens.
- */
- public String substituteInto(String input) {
- // a la Perl, $0 is whole thing, $1 - $9 are subexpressions
- StringBuffer output = new StringBuffer();
- int pos;
- for (pos = 0; pos < input.length()-1; pos++) {
- if ((input.charAt(pos) == '$') && (Character.isDigit(input.charAt(pos+1)))) {
- int val = Character.digit(input.charAt(++pos),10);
- if (val < start.length) {
- output.append(toString(val));
- }
- } else output.append(input.charAt(pos));
- }
- if (pos < input.length()) output.append(input.charAt(pos));
- return output.toString();
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/REMatchEnumeration.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-package gnu.regexp;
-import java.io.Serializable;
-import java.util.Enumeration;
-import java.util.NoSuchElementException;
-
-/**
- * An REMatchEnumeration enumerates regular expression matches over a
- * given input text. You obtain a reference to an enumeration using
- * the <code>getMatchEnumeration()</code> methods on an instance of
- * RE.
- *
- * <P>
- *
- * REMatchEnumeration does lazy computation; that is, it will not
- * search for a match until it needs to. If you'd rather just get all
- * the matches at once in a big array, use the
- * <code>getAllMatches()</code> methods on RE. However, using an
- * enumeration can help speed performance when the entire text does
- * not need to be searched immediately.
- *
- * <P>
- *
- * The enumerated type is especially useful when searching on a Reader
- * or InputStream, because the InputStream read position cannot be
- * guaranteed after calling <code>getMatch()</code> (see the
- * description of that method for an explanation of why). Enumeration
- * also saves a lot of overhead required when calling
- * <code>getMatch()</code> multiple times.
- *
- * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- */
-public class REMatchEnumeration implements Enumeration, Serializable {
- private static final int YES = 1;
- private static final int MAYBE = 0;
- private static final int NO = -1;
-
- private int more;
- private REMatch match;
- private RE expr;
- private CharIndexed input;
- private int eflags;
- private int index;
-
- // Package scope constructor is used by RE.getMatchEnumeration()
- REMatchEnumeration(RE expr, CharIndexed input, int index, int eflags) {
- more = MAYBE;
- this.expr = expr;
- this.input = input;
- this.index = index;
- this.eflags = eflags;
- }
-
- /** Returns true if there are more matches in the input text. */
- public boolean hasMoreElements() {
- return hasMoreMatches(null);
- }
-
- /** Returns true if there are more matches in the input text. */
- public boolean hasMoreMatches() {
- return hasMoreMatches(null);
- }
-
- /** Returns true if there are more matches in the input text.
- * Saves the text leading up to the match (or to the end of the input)
- * in the specified buffer.
- */
- public boolean hasMoreMatches(StringBuffer buffer) {
- if (more == MAYBE) {
- match = expr.getMatchImpl(input,index,eflags,buffer);
- if (match != null) {
- input.move((match.end[0] > 0) ? match.end[0] : 1);
-
- index = (match.end[0] > 0) ? match.end[0] + match.offset : index + 1;
- more = YES;
- } else more = NO;
- }
- return (more == YES);
- }
-
- /** Returns the next match in the input text. */
- public Object nextElement() throws NoSuchElementException {
- return nextMatch();
- }
-
- /**
- * Returns the next match in the input text. This method is provided
- * for convenience to avoid having to explicitly cast the return value
- * to class REMatch.
- */
- public REMatch nextMatch() throws NoSuchElementException {
- if (hasMoreElements()) {
- more = (input.isValid()) ? MAYBE : NO;
- return match;
- }
- throw new NoSuchElementException();
- }
-}
-
+++ /dev/null
-/*
- * gnu/regexp/RESyntax.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.io.Serializable;
-import java.util.BitSet;
-
-/**
- * An RESyntax specifies the way a regular expression will be compiled.
- * This class provides a number of predefined useful constants for
- * emulating popular regular expression syntaxes. Additionally the
- * user may construct his or her own syntax, using any combination of the
- * syntax bit constants. The syntax is an optional argument to any of the
- * matching methods on class RE.
- *
- * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- */
-
-public final class RESyntax implements Serializable {
- static final String DEFAULT_LINE_SEPARATOR = System.getProperty("line.separator");
-
- private static final String SYNTAX_IS_FINAL = RE.getLocalizedMessage("syntax.final");
-
- private BitSet bits;
-
- // true for the constant defined syntaxes
- private boolean isFinal = false;
-
- private String lineSeparator = DEFAULT_LINE_SEPARATOR;
-
- // Values for constants are bit indexes
-
- /**
- * Syntax bit. Backslash is an escape character in lists.
- */
- public static final int RE_BACKSLASH_ESCAPE_IN_LISTS = 0;
-
- /**
- * Syntax bit. Use \? instead of ? and \+ instead of +.
- */
- public static final int RE_BK_PLUS_QM = 1;
-
- /**
- * Syntax bit. POSIX character classes ([:...:]) in lists are allowed.
- */
- public static final int RE_CHAR_CLASSES = 2;
-
- /**
- * Syntax bit. ^ and $ are special everywhere.
- * <B>Not implemented.</B>
- */
- public static final int RE_CONTEXT_INDEP_ANCHORS = 3;
-
- /**
- * Syntax bit. Repetition operators are only special in valid positions.
- * <B>Not implemented.</B>
- */
- public static final int RE_CONTEXT_INDEP_OPS = 4;
-
- /**
- * Syntax bit. Repetition and alternation operators are invalid
- * at start and end of pattern and other places.
- * <B>Not implemented</B>.
- */
- public static final int RE_CONTEXT_INVALID_OPS = 5;
-
- /**
- * Syntax bit. Match-any-character operator (.) matches a newline.
- */
- public static final int RE_DOT_NEWLINE = 6;
-
- /**
- * Syntax bit. Match-any-character operator (.) does not match a null.
- */
- public static final int RE_DOT_NOT_NULL = 7;
-
- /**
- * Syntax bit. Intervals ({x}, {x,}, {x,y}) are allowed.
- */
- public static final int RE_INTERVALS = 8;
-
- /**
- * Syntax bit. No alternation (|), match one-or-more (+), or
- * match zero-or-one (?) operators.
- */
- public static final int RE_LIMITED_OPS = 9;
-
- /**
- * Syntax bit. Newline is an alternation operator.
- */
- public static final int RE_NEWLINE_ALT = 10; // impl.
-
- /**
- * Syntax bit. Intervals use { } instead of \{ \}
- */
- public static final int RE_NO_BK_BRACES = 11;
-
- /**
- * Syntax bit. Grouping uses ( ) instead of \( \).
- */
- public static final int RE_NO_BK_PARENS = 12;
-
- /**
- * Syntax bit. Backreferences not allowed.
- */
- public static final int RE_NO_BK_REFS = 13;
-
- /**
- * Syntax bit. Alternation uses | instead of \|
- */
- public static final int RE_NO_BK_VBAR = 14;
-
- /**
- * Syntax bit. <B>Not implemented</B>.
- */
- public static final int RE_NO_EMPTY_RANGES = 15;
-
- /**
- * Syntax bit. An unmatched right parenthesis (')' or '\)', depending
- * on RE_NO_BK_PARENS) will throw an exception when compiling.
- */
- public static final int RE_UNMATCHED_RIGHT_PAREN_ORD = 16;
-
- /**
- * Syntax bit. <B>Not implemented.</B>
- */
- public static final int RE_HAT_LISTS_NOT_NEWLINE = 17;
-
- /**
- * Syntax bit. Stingy matching is allowed (+?, *?, ??, {x,y}?).
- */
- public static final int RE_STINGY_OPS = 18;
-
- /**
- * Syntax bit. Allow character class escapes (\d, \D, \s, \S, \w, \W).
- */
- public static final int RE_CHAR_CLASS_ESCAPES = 19;
-
- /**
- * Syntax bit. Allow use of (?:xxx) grouping (subexpression is not saved).
- */
- public static final int RE_PURE_GROUPING = 20;
-
- /**
- * Syntax bit. Allow use of (?=xxx) and (?!xxx) apply the subexpression
- * to the text following the current position without consuming that text.
- */
- public static final int RE_LOOKAHEAD = 21;
-
- /**
- * Syntax bit. Allow beginning- and end-of-string anchors (\A, \Z).
- */
- public static final int RE_STRING_ANCHORS = 22;
-
- /**
- * Syntax bit. Allow embedded comments, (?#comment), as in Perl5.
- */
- public static final int RE_COMMENTS = 23;
-
- /**
- * Syntax bit. Allow character class escapes within lists, as in Perl5.
- */
- public static final int RE_CHAR_CLASS_ESC_IN_LISTS = 24;
-
- private static final int BIT_TOTAL = 25;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in the awk utility.
- */
- public static final RESyntax RE_SYNTAX_AWK;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in the ed utility.
- */
- public static final RESyntax RE_SYNTAX_ED;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in the egrep utility.
- */
- public static final RESyntax RE_SYNTAX_EGREP;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in the GNU Emacs editor.
- */
- public static final RESyntax RE_SYNTAX_EMACS;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in the grep utility.
- */
- public static final RESyntax RE_SYNTAX_GREP;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in the POSIX awk specification.
- */
- public static final RESyntax RE_SYNTAX_POSIX_AWK;
-
- /**
- * Predefined syntax.
- * Emulates POSIX basic regular expression support.
- */
- public static final RESyntax RE_SYNTAX_POSIX_BASIC;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in the POSIX egrep specification.
- */
- public static final RESyntax RE_SYNTAX_POSIX_EGREP;
-
- /**
- * Predefined syntax.
- * Emulates POSIX extended regular expression support.
- */
- public static final RESyntax RE_SYNTAX_POSIX_EXTENDED;
-
- /**
- * Predefined syntax.
- * Emulates POSIX basic minimal regular expressions.
- */
- public static final RESyntax RE_SYNTAX_POSIX_MINIMAL_BASIC;
-
- /**
- * Predefined syntax.
- * Emulates POSIX extended minimal regular expressions.
- */
- public static final RESyntax RE_SYNTAX_POSIX_MINIMAL_EXTENDED;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in the sed utility.
- */
- public static final RESyntax RE_SYNTAX_SED;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in Larry Wall's perl, version 4,
- */
- public static final RESyntax RE_SYNTAX_PERL4;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in Larry Wall's perl, version 4,
- * using single line mode (/s modifier).
- */
- public static final RESyntax RE_SYNTAX_PERL4_S; // single line mode (/s)
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in Larry Wall's perl, version 5.
- */
- public static final RESyntax RE_SYNTAX_PERL5;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in Larry Wall's perl, version 5,
- * using single line mode (/s modifier).
- */
- public static final RESyntax RE_SYNTAX_PERL5_S;
-
- static {
- // Define syntaxes
-
- RE_SYNTAX_EMACS = new RESyntax().makeFinal();
-
- RESyntax RE_SYNTAX_POSIX_COMMON = new RESyntax()
- .set(RE_CHAR_CLASSES)
- .set(RE_DOT_NEWLINE)
- .set(RE_DOT_NOT_NULL)
- .set(RE_INTERVALS)
- .set(RE_NO_EMPTY_RANGES)
- .makeFinal();
-
- RE_SYNTAX_POSIX_BASIC = new RESyntax(RE_SYNTAX_POSIX_COMMON)
- .set(RE_BK_PLUS_QM)
- .makeFinal();
-
- RE_SYNTAX_POSIX_EXTENDED = new RESyntax(RE_SYNTAX_POSIX_COMMON)
- .set(RE_CONTEXT_INDEP_ANCHORS)
- .set(RE_CONTEXT_INDEP_OPS)
- .set(RE_NO_BK_BRACES)
- .set(RE_NO_BK_PARENS)
- .set(RE_NO_BK_VBAR)
- .set(RE_UNMATCHED_RIGHT_PAREN_ORD)
- .makeFinal();
-
- RE_SYNTAX_AWK = new RESyntax()
- .set(RE_BACKSLASH_ESCAPE_IN_LISTS)
- .set(RE_DOT_NOT_NULL)
- .set(RE_NO_BK_PARENS)
- .set(RE_NO_BK_REFS)
- .set(RE_NO_BK_VBAR)
- .set(RE_NO_EMPTY_RANGES)
- .set(RE_UNMATCHED_RIGHT_PAREN_ORD)
- .makeFinal();
-
- RE_SYNTAX_POSIX_AWK = new RESyntax(RE_SYNTAX_POSIX_EXTENDED)
- .set(RE_BACKSLASH_ESCAPE_IN_LISTS)
- .makeFinal();
-
- RE_SYNTAX_GREP = new RESyntax()
- .set(RE_BK_PLUS_QM)
- .set(RE_CHAR_CLASSES)
- .set(RE_HAT_LISTS_NOT_NEWLINE)
- .set(RE_INTERVALS)
- .set(RE_NEWLINE_ALT)
- .makeFinal();
-
- RE_SYNTAX_EGREP = new RESyntax()
- .set(RE_CHAR_CLASSES)
- .set(RE_CONTEXT_INDEP_ANCHORS)
- .set(RE_CONTEXT_INDEP_OPS)
- .set(RE_HAT_LISTS_NOT_NEWLINE)
- .set(RE_NEWLINE_ALT)
- .set(RE_NO_BK_PARENS)
- .set(RE_NO_BK_VBAR)
- .makeFinal();
-
- RE_SYNTAX_POSIX_EGREP = new RESyntax(RE_SYNTAX_EGREP)
- .set(RE_INTERVALS)
- .set(RE_NO_BK_BRACES)
- .makeFinal();
-
- /* P1003.2/D11.2, section 4.20.7.1, lines 5078ff. */
-
- RE_SYNTAX_ED = new RESyntax(RE_SYNTAX_POSIX_BASIC)
- .makeFinal();
-
- RE_SYNTAX_SED = new RESyntax(RE_SYNTAX_POSIX_BASIC)
- .makeFinal();
-
- RE_SYNTAX_POSIX_MINIMAL_BASIC = new RESyntax(RE_SYNTAX_POSIX_COMMON)
- .set(RE_LIMITED_OPS)
- .makeFinal();
-
- /* Differs from RE_SYNTAX_POSIX_EXTENDED in that RE_CONTEXT_INVALID_OPS
- replaces RE_CONTEXT_INDEP_OPS and RE_NO_BK_REFS is added. */
-
- RE_SYNTAX_POSIX_MINIMAL_EXTENDED = new RESyntax(RE_SYNTAX_POSIX_COMMON)
- .set(RE_CONTEXT_INDEP_ANCHORS)
- .set(RE_CONTEXT_INVALID_OPS)
- .set(RE_NO_BK_BRACES)
- .set(RE_NO_BK_PARENS)
- .set(RE_NO_BK_REFS)
- .set(RE_NO_BK_VBAR)
- .set(RE_UNMATCHED_RIGHT_PAREN_ORD)
- .makeFinal();
-
- /* There is no official Perl spec, but here's a "best guess" */
-
- RE_SYNTAX_PERL4 = new RESyntax()
- .set(RE_BACKSLASH_ESCAPE_IN_LISTS)
- .set(RE_CONTEXT_INDEP_ANCHORS)
- .set(RE_CONTEXT_INDEP_OPS) // except for '{', apparently
- .set(RE_INTERVALS)
- .set(RE_NO_BK_BRACES)
- .set(RE_NO_BK_PARENS)
- .set(RE_NO_BK_VBAR)
- .set(RE_NO_EMPTY_RANGES)
- .set(RE_CHAR_CLASS_ESCAPES) // \d,\D,\w,\W,\s,\S
- .makeFinal();
-
- RE_SYNTAX_PERL4_S = new RESyntax(RE_SYNTAX_PERL4)
- .set(RE_DOT_NEWLINE)
- .makeFinal();
-
- RE_SYNTAX_PERL5 = new RESyntax(RE_SYNTAX_PERL4)
- .set(RE_PURE_GROUPING) // (?:)
- .set(RE_STINGY_OPS) // *?,??,+?,{}?
- .set(RE_LOOKAHEAD) // (?=)(?!)
- .set(RE_STRING_ANCHORS) // \A,\Z
- .set(RE_CHAR_CLASS_ESC_IN_LISTS)// \d,\D,\w,\W,\s,\S within []
- .set(RE_COMMENTS) // (?#)
- .makeFinal();
-
- RE_SYNTAX_PERL5_S = new RESyntax(RE_SYNTAX_PERL5)
- .set(RE_DOT_NEWLINE)
- .makeFinal();
- }
-
- /**
- * Construct a new syntax object with all bits turned off.
- * This is equivalent to RE_SYNTAX_EMACS.
- */
- public RESyntax() {
- bits = new BitSet(BIT_TOTAL);
- }
-
- /**
- * Called internally when constructing predefined syntaxes
- * so their interpretation cannot vary. Conceivably useful
- * for your syntaxes as well. Causes IllegalAccessError to
- * be thrown if any attempt to modify the syntax is made.
- *
- * @return this object for convenient chaining
- */
- public RESyntax makeFinal() {
- isFinal = true;
- return this;
- }
-
- /**
- * Construct a new syntax object with all bits set the same
- * as the other syntax.
- */
- public RESyntax(RESyntax other) {
- bits = (BitSet) other.bits.clone();
- }
-
- /**
- * Check if a given bit is set in this syntax.
- */
- public boolean get(int index) {
- return bits.get(index);
- }
-
- /**
- * Set a given bit in this syntax.
- *
- * @param index the constant (RESyntax.RE_xxx) bit to set.
- * @return a reference to this object for easy chaining.
- */
- public RESyntax set(int index) {
- if (isFinal) throw new IllegalAccessError(SYNTAX_IS_FINAL);
- bits.set(index);
- return this;
- }
-
- /**
- * Clear a given bit in this syntax.
- *
- * @param index the constant (RESyntax.RE_xxx) bit to clear.
- * @return a reference to this object for easy chaining.
- */
- public RESyntax clear(int index) {
- if (isFinal) throw new IllegalAccessError(SYNTAX_IS_FINAL);
- bits.clear(index);
- return this;
- }
-
- /**
- * Changes the line separator string for regular expressions
- * created using this RESyntax. The default separator is the
- * value returned by the system property "line.separator", which
- * should be correct when reading platform-specific files from a
- * filesystem. However, many programs may collect input from
- * sources where the line separator is differently specified (for
- * example, in the applet environment, the text box widget
- * interprets line breaks as single-character newlines,
- * regardless of the host platform.
- *
- * Note that setting the line separator to a character or
- * characters that have specific meaning within the current syntax
- * can cause unexpected chronosynclastic infundibula.
- *
- * @return this object for convenient chaining
- */
- public RESyntax setLineSeparator(String aSeparator) {
- if (isFinal) throw new IllegalAccessError(SYNTAX_IS_FINAL);
- lineSeparator = aSeparator;
- return this;
- }
-
- /**
- * Returns the currently active line separator string. The default
- * is the platform-dependent system property "line.separator".
- */
- public String getLineSeparator() {
- return lineSeparator;
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/REToken.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.io.Serializable;
-
-abstract class REToken implements Serializable {
-
- protected REToken next = null;
- protected REToken uncle = null;
- protected int subIndex;
-
- protected REToken(int subIndex) {
- this.subIndex = subIndex;
- }
-
- int getMinimumLength() {
- return 0;
- }
-
- void setUncle(REToken anUncle) {
- uncle = anUncle;
- }
-
- /** Returns true if the match succeeded, false if it failed. */
- abstract boolean match(CharIndexed input, REMatch mymatch);
-
- /** Returns true if the rest of the tokens match, false if they fail. */
- protected boolean next(CharIndexed input, REMatch mymatch) {
- if (next == null) {
- if (uncle == null) {
- return true;
- } else {
- return uncle.match(input, mymatch);
- }
- } else {
- return next.match(input, mymatch);
- }
- }
-
- boolean chain(REToken token) {
- next = token;
- return true; // Token was accepted
- }
-
- abstract void dump(StringBuffer os);
-
- void dumpAll(StringBuffer os) {
- dump(os);
- if (next != null) next.dumpAll(os);
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/RETokenAny.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-final class RETokenAny extends REToken {
- /** True if '.' can match a newline (RE_DOT_NEWLINE) */
- private boolean newline;
-
- /** True if '.' can't match a null (RE_DOT_NOT_NULL) */
- private boolean matchNull;
-
- RETokenAny(int subIndex, boolean newline, boolean matchNull) {
- super(subIndex);
- this.newline = newline;
- this.matchNull = matchNull;
- }
-
- int getMinimumLength() {
- return 1;
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- char ch = input.charAt(mymatch.index);
- if ((ch == CharIndexed.OUT_OF_BOUNDS)
- || (!newline && (ch == '\n'))
- || (matchNull && (ch == 0))) {
- return false;
- }
- ++mymatch.index;
- return next(input, mymatch);
- }
-
- void dump(StringBuffer os) {
- os.append('.');
- }
-}
-
+++ /dev/null
-/*
- * gnu/regexp/RETokenBackRef.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-final class RETokenBackRef extends REToken {
- private int num;
- private boolean insens;
-
- RETokenBackRef(int subIndex, int num, boolean insens) {
- super(subIndex);
- this.num = num;
- this.insens = insens;
- }
-
- // should implement getMinimumLength() -- any ideas?
-
- boolean match(CharIndexed input, REMatch mymatch) {
- int b,e;
- b = mymatch.start[num];
- e = mymatch.end[num];
- if ((b==-1)||(e==-1)) return false; // this shouldn't happen, but...
- for (int i=b; i<e; i++) {
- if (input.charAt(mymatch.index+i-b) != input.charAt(i)) {
- return false;
- }
- }
- mymatch.index += e-b;
- return next(input, mymatch);
- }
-
- void dump(StringBuffer os) {
- os.append('\\').append(num);
- }
-}
-
-
+++ /dev/null
-/*
- * gnu/regexp/RETokenChar.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-final class RETokenChar extends REToken {
- private char[] ch;
- private boolean insens;
-
- RETokenChar(int subIndex, char c, boolean ins) {
- super(subIndex);
- ch = new char [1];
- ch[0] = (insens = ins) ? Character.toLowerCase(c) : c;
- }
-
- int getMinimumLength() {
- return ch.length;
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- int z = ch.length;
- char c;
- for (int i=0; i<z; i++) {
- c = input.charAt(mymatch.index+i);
- if (( (insens) ? Character.toLowerCase(c) : c ) != ch[i]) {
- return false;
- }
- }
- mymatch.index += z;
-
- return next(input, mymatch);
- }
-
- // Overrides REToken.chain() to optimize for strings
- boolean chain(REToken next) {
- if (next instanceof RETokenChar) {
- RETokenChar cnext = (RETokenChar) next;
- // assume for now that next can only be one character
- int newsize = ch.length + cnext.ch.length;
-
- char[] chTemp = new char [newsize];
-
- System.arraycopy(ch,0,chTemp,0,ch.length);
- System.arraycopy(cnext.ch,0,chTemp,ch.length,cnext.ch.length);
-
- ch = chTemp;
- return false;
- } else return super.chain(next);
- }
-
- void dump(StringBuffer os) {
- os.append(ch);
- }
-}
-
-
+++ /dev/null
-/*
- * gnu/regexp/RETokenEnd.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-package gnu.regexp;
-
-final class RETokenEnd extends REToken {
- /**
- * Indicates whether this token should match on a line break.
- */
- private String newline;
-
- RETokenEnd(int subIndex,String newline) {
- super(subIndex);
- this.newline = newline;
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- char ch = input.charAt(mymatch.index);
- if (ch == CharIndexed.OUT_OF_BOUNDS)
- return ((mymatch.eflags & RE.REG_NOTEOL)>0) ?
- false : next(input, mymatch);
- if (newline != null) {
- char z;
- int i = 0; // position in newline
- do {
- z = newline.charAt(i);
- if (ch != z) return false;
- ++i;
- ch = input.charAt(mymatch.index + i);
- } while (i < newline.length());
-
- return next(input, mymatch);
- }
- return false;
- }
-
- void dump(StringBuffer os) {
- os.append('$');
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/RETokenEndSub.java
- * Copyright (C) 2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-final class RETokenEndSub extends REToken {
- RETokenEndSub(int subIndex) {
- super(subIndex);
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- mymatch.end[subIndex] = mymatch.index;
- return next(input, mymatch);
- }
-
- void dump(StringBuffer os) {
- // handled by RE
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/RETokenOneOf.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-package gnu.regexp;
-
-/**
- * @since gnu.regexp 1.1.3
- * @author Shashank Bapat
- */
-final class RETokenLookAhead extends REToken
-{
- REToken re;
- boolean negative;
-
- RETokenLookAhead(REToken re, boolean negative) throws REException {
- super(0);
- this.re = re;
- this.negative = negative;
- }
-
- boolean match(CharIndexed input, REMatch mymatch)
- {
- REMatch trymatch = (REMatch)mymatch.clone();
- REMatch trymatch1 = (REMatch)mymatch.clone();
- REMatch newMatch = null;
- if (re.match(input, trymatch)) {
- if (negative) return false;
- if (next(input, trymatch1))
- newMatch = trymatch1;
- }
-
- if (newMatch != null) {
- if (negative) return false;
- //else
- mymatch.assignFrom(newMatch);
- return true;
- }
- else { // no match
- if (negative)
- return next(input, mymatch);
- //else
- return false;
- }
- }
-
- void dump(StringBuffer os) {
- os.append("(?");
- os.append(negative ? '!' : '=');
- re.dumpAll(os);
- os.append(')');
- }
-}
-
+++ /dev/null
-/*
- * gnu/regexp/RETokenOneOf.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.util.Vector;
-
-final class RETokenOneOf extends REToken {
- private Vector options;
- private boolean negative;
-
- // This constructor is used for convenience when we know the set beforehand,
- // e.g. \d --> new RETokenOneOf("0123456789",false, ..)
- // \D --> new RETokenOneOf("0123456789",true, ..)
-
- RETokenOneOf(int subIndex, String optionsStr, boolean negative, boolean insens) {
- super(subIndex);
- options = new Vector();
- this.negative = negative;
- for (int i = 0; i < optionsStr.length(); i++)
- options.addElement(new RETokenChar(subIndex,optionsStr.charAt(i),insens));
- }
-
- RETokenOneOf(int subIndex, Vector options, boolean negative) {
- super(subIndex);
- this.options = options;
- this.negative = negative;
- }
-
- int getMinimumLength() {
- int min = Integer.MAX_VALUE;
- int x;
- for (int i=0; i < options.size(); i++) {
- if ((x = ((REToken) options.elementAt(i)).getMinimumLength()) < min)
- min = x;
- }
- return min;
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- if (negative && (input.charAt(mymatch.index) == CharIndexed.OUT_OF_BOUNDS))
- return false;
-
- REMatch newMatch = null;
- REMatch last = null;
- REToken tk;
- boolean isMatch;
- for (int i=0; i < options.size(); i++) {
- tk = (REToken) options.elementAt(i);
- REMatch tryMatch = (REMatch) mymatch.clone();
- if (tk.match(input, tryMatch)) { // match was successful
- if (negative) return false;
-
- if (next(input, tryMatch)) {
- // Add tryMatch to list of possibilities.
- if (last == null) {
- newMatch = tryMatch;
- last = tryMatch;
- } else {
- last.next = tryMatch;
- last = tryMatch;
- }
- } // next succeeds
- } // is a match
- } // try next option
-
- if (newMatch != null) {
- if (negative) {
- return false;
- } else {
- // set contents of mymatch equal to newMatch
-
- // try each one that matched
- mymatch.assignFrom(newMatch);
- return true;
- }
- } else {
- if (negative) {
- ++mymatch.index;
- return next(input, mymatch);
- } else {
- return false;
- }
- }
-
- // index+1 works for [^abc] lists, not for generic lookahead (--> index)
- }
-
- void dump(StringBuffer os) {
- os.append(negative ? "[^" : "(?:");
- for (int i = 0; i < options.size(); i++) {
- if (!negative && (i > 0)) os.append('|');
- ((REToken) options.elementAt(i)).dumpAll(os);
- }
- os.append(negative ? ']' : ')');
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/RETokenPOSIX.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-final class RETokenPOSIX extends REToken {
- int type;
- boolean insens;
- boolean negated;
-
- static final int ALNUM = 0;
- static final int ALPHA = 1;
- static final int BLANK = 2;
- static final int CNTRL = 3;
- static final int DIGIT = 4;
- static final int GRAPH = 5;
- static final int LOWER = 6;
- static final int PRINT = 7;
- static final int PUNCT = 8;
- static final int SPACE = 9;
- static final int UPPER = 10;
- static final int XDIGIT = 11;
-
- // Array indices correspond to constants defined above.
- static final String[] s_nameTable = {
- "alnum", "alpha", "blank", "cntrl", "digit", "graph", "lower",
- "print", "punct", "space", "upper", "xdigit"
- };
-
- // The RE constructor uses this to look up the constant for a string
- static int intValue(String key) {
- for (int i = 0; i < s_nameTable.length; i++) {
- if (s_nameTable[i].equals(key)) return i;
- }
- return -1;
- }
-
- RETokenPOSIX(int subIndex, int type, boolean insens, boolean negated) {
- super(subIndex);
- this.type = type;
- this.insens = insens;
- this.negated = negated;
- }
-
- int getMinimumLength() {
- return 1;
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- char ch = input.charAt(mymatch.index);
- if (ch == CharIndexed.OUT_OF_BOUNDS)
- return false;
-
- boolean retval = false;
- switch (type) {
- case ALNUM:
- // Note that there is some debate over whether '_' should be included
- retval = Character.isLetterOrDigit(ch) || (ch == '_');
- break;
- case ALPHA:
- retval = Character.isLetter(ch);
- break;
- case BLANK:
- retval = ((ch == ' ') || (ch == '\t'));
- break;
- case CNTRL:
- retval = Character.isISOControl(ch);
- break;
- case DIGIT:
- retval = Character.isDigit(ch);
- break;
- case GRAPH:
- retval = (!(Character.isWhitespace(ch) || Character.isISOControl(ch)));
- break;
- case LOWER:
- retval = ((insens && Character.isLetter(ch)) || Character.isLowerCase(ch));
- break;
- case PRINT:
- retval = (!(Character.isWhitespace(ch) || Character.isISOControl(ch)))
- || (ch == ' ');
- break;
- case PUNCT:
- // This feels sloppy, especially for non-U.S. locales.
- retval = ("`~!@#$%^&*()-_=+[]{}\\|;:'\"/?,.<>".indexOf(ch)!=-1);
- break;
- case SPACE:
- retval = Character.isWhitespace(ch);
- break;
- case UPPER:
- retval = ((insens && Character.isLetter(ch)) || Character.isUpperCase(ch));
- break;
- case XDIGIT:
- retval = (Character.isDigit(ch) || ("abcdefABCDEF".indexOf(ch)!=-1));
- break;
- }
-
- if (negated) retval = !retval;
- if (retval) {
- ++mymatch.index;
- return next(input, mymatch);
- }
- else return false;
- }
-
- void dump(StringBuffer os) {
- if (negated) os.append('^');
- os.append("[:" + s_nameTable[type] + ":]");
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/RETokenRange.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-final class RETokenRange extends REToken {
- private char lo, hi;
- private boolean insens;
-
- RETokenRange(int subIndex, char lo, char hi, boolean ins) {
- super(subIndex);
- this.lo = (insens = ins) ? Character.toLowerCase(lo) : lo;
- this.hi = ins ? Character.toLowerCase(hi) : hi;
- }
-
- int getMinimumLength() {
- return 1;
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- char c = input.charAt(mymatch.index);
- if (c == CharIndexed.OUT_OF_BOUNDS) return false;
- if (insens) c = Character.toLowerCase(c);
- if ((c >= lo) && (c <= hi)) {
- ++mymatch.index;
- return next(input, mymatch);
- }
- return false;
- }
-
- void dump(StringBuffer os) {
- os.append(lo).append('-').append(hi);
- }
-}
-
+++ /dev/null
-/*
- * gnu/regexp/RETokenRepeated.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-import java.util.Vector;
-
-final class RETokenRepeated extends REToken {
- private REToken token;
- private int min,max;
- private boolean stingy;
-
- RETokenRepeated(int subIndex, REToken token, int min, int max) {
- super(subIndex);
- this.token = token;
- this.min = min;
- this.max = max;
- }
-
- /** Sets the minimal matching mode to true. */
- void makeStingy() {
- stingy = true;
- }
-
- /** Queries if this token has minimal matching enabled. */
- boolean isStingy() {
- return stingy;
- }
-
- /**
- * The minimum length of a repeated token is the minimum length
- * of the token multiplied by the minimum number of times it must
- * match.
- */
- int getMinimumLength() {
- return (min * token.getMinimumLength());
- }
-
- // We do need to save every possible point, but the number of clone()
- // invocations here is really a killer for performance on non-stingy
- // repeat operators. I'm open to suggestions...
-
- // Hypothetical question: can you have a RE that matches 1 times,
- // 3 times, 5 times, but not 2 times or 4 times? Does having
- // the subexpression back-reference operator allow that?
-
- boolean match(CharIndexed input, REMatch mymatch) {
- // number of times we've matched so far
- int numRepeats = 0;
-
- // Possible positions for the next repeat to match at
- REMatch newMatch = mymatch;
- REMatch last = null;
- REMatch current;
-
- // Add the '0-repeats' index
- // positions.elementAt(z) == position [] in input after <<z>> matches
- Vector positions = new Vector();
- positions.addElement(newMatch);
-
- // Declare variables used in loop
- REMatch doables;
- REMatch doablesLast;
- REMatch recurrent;
-
- do {
- // Check for stingy match for each possibility.
- if (stingy && (numRepeats >= min)) {
- REMatch result = matchRest(input, newMatch);
- if (result != null) {
- mymatch.assignFrom(result);
- return true;
- }
- }
-
- doables = null;
- doablesLast = null;
-
- // try next repeat at all possible positions
- for (current = newMatch; current != null; current = current.next) {
- recurrent = (REMatch) current.clone();
- if (token.match(input, recurrent)) {
- // add all items in current to doables array
- if (doables == null) {
- doables = recurrent;
- doablesLast = recurrent;
- } else {
- // Order these from longest to shortest
- // Start by assuming longest (more repeats)
- doablesLast.next = recurrent;
- }
- // Find new doablesLast
- while (doablesLast.next != null) {
- doablesLast = doablesLast.next;
- }
- }
- }
- // if none of the possibilities worked out, break out of do/while
- if (doables == null) break;
-
- // reassign where the next repeat can match
- newMatch = doables;
-
- // increment how many repeats we've successfully found
- ++numRepeats;
-
- positions.addElement(newMatch);
- } while (numRepeats < max);
-
- // If there aren't enough repeats, then fail
- if (numRepeats < min) return false;
-
- // We're greedy, but ease off until a true match is found
- int posIndex = positions.size();
-
- // At this point we've either got too many or just the right amount.
- // See if this numRepeats works with the rest of the regexp.
- REMatch allResults = null;
- REMatch allResultsLast = null;
-
- REMatch results = null;
- while (--posIndex >= min) {
- newMatch = (REMatch) positions.elementAt(posIndex);
- results = matchRest(input, newMatch);
- if (results != null) {
- if (allResults == null) {
- allResults = results;
- allResultsLast = results;
- } else {
- // Order these from longest to shortest
- // Start by assuming longest (more repeats)
- allResultsLast.next = results;
- }
- // Find new doablesLast
- while (allResultsLast.next != null) {
- allResultsLast = allResultsLast.next;
- }
- }
- // else did not match rest of the tokens, try again on smaller sample
- }
- if (allResults != null) {
- mymatch.assignFrom(allResults); // does this get all?
- return true;
- }
- // If we fall out, no matches.
- return false;
- }
-
- private REMatch matchRest(CharIndexed input, final REMatch newMatch) {
- REMatch current, single;
- REMatch doneIndex = null;
- REMatch doneIndexLast = null;
- // Test all possible matches for this number of repeats
- for (current = newMatch; current != null; current = current.next) {
- // clone() separates a single match from the chain
- single = (REMatch) current.clone();
- if (next(input, single)) {
- // chain results to doneIndex
- if (doneIndex == null) {
- doneIndex = single;
- doneIndexLast = single;
- } else {
- doneIndexLast.next = single;
- }
- // Find new doneIndexLast
- while (doneIndexLast.next != null) {
- doneIndexLast = doneIndexLast.next;
- }
- }
- }
- return doneIndex;
- }
-
- void dump(StringBuffer os) {
- os.append("(?:");
- token.dumpAll(os);
- os.append(')');
- if ((max == Integer.MAX_VALUE) && (min <= 1))
- os.append( (min == 0) ? '*' : '+' );
- else if ((min == 0) && (max == 1))
- os.append('?');
- else {
- os.append('{').append(min);
- if (max > min) {
- os.append(',');
- if (max != Integer.MAX_VALUE) os.append(max);
- }
- os.append('}');
- }
- if (stingy) os.append('?');
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/RETokenStart.java
- * Copyright (C) 1998-2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-class RETokenStart extends REToken {
- private String newline; // matches after a newline
-
- RETokenStart(int subIndex, String newline) {
- super(subIndex);
- this.newline = newline;
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- // charAt(index-n) may be unknown on a Reader/InputStream. FIXME
- // Match after a newline if in multiline mode
-
- if (newline != null) {
- int len = newline.length();
- if (mymatch.offset >= len) {
- boolean found = true;
- char z;
- int i = 0; // position in REToken.newline
- char ch = input.charAt(mymatch.index - len);
- do {
- z = newline.charAt(i);
- if (ch != z) {
- found = false;
- break;
- }
- ++i;
- ch = input.charAt(mymatch.index - len + i);
- } while (i < len);
-
- if (found) return next(input, mymatch);
- }
- }
-
- // Don't match at all if REG_NOTBOL is set.
- if ((mymatch.eflags & RE.REG_NOTBOL) > 0) return false;
-
- if ((mymatch.eflags & RE.REG_ANCHORINDEX) > 0)
- return (mymatch.anchor == mymatch.offset) ?
- next(input, mymatch) : false;
- else
- return ((mymatch.index == 0) && (mymatch.offset == 0)) ?
- next(input, mymatch) : false;
- }
-
- void dump(StringBuffer os) {
- os.append('^');
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/RETokenWordBoundary.java
- * Copyright (C) 2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-/**
- * Represents a combination lookahead/lookbehind for POSIX [:alnum:].
- */
-final class RETokenWordBoundary extends REToken {
- private boolean negated;
- private int where;
- static final int BEGIN = 1;
- static final int END = 2;
-
- RETokenWordBoundary(int subIndex, int where, boolean negated) {
- super(subIndex);
- this.where = where;
- this.negated = negated;
- }
-
- boolean match(CharIndexed input, REMatch mymatch) {
- // Word boundary means input[index-1] was a word character
- // and input[index] is not, or input[index] is a word character
- // and input[index-1] was not
- // In the string "one two three", these positions match:
- // |o|n|e| |t|w|o| |t|h|r|e|e|
- // ^ ^ ^ ^ ^ ^
- boolean after = false; // is current character a letter or digit?
- boolean before = false; // is previous character a letter or digit?
- char ch;
-
- // TODO: Also check REG_ANCHORINDEX vs. anchor
- if (((mymatch.eflags & RE.REG_ANCHORINDEX) != RE.REG_ANCHORINDEX)
- || (mymatch.offset + mymatch.index > mymatch.anchor)) {
- if ((ch = input.charAt(mymatch.index - 1)) != CharIndexed.OUT_OF_BOUNDS) {
- before = Character.isLetterOrDigit(ch) || (ch == '_');
- }
- }
-
- if ((ch = input.charAt(mymatch.index)) != CharIndexed.OUT_OF_BOUNDS) {
- after = Character.isLetterOrDigit(ch) || (ch == '_');
- }
-
- // if (before) and (!after), we're at end (\>)
- // if (after) and (!before), we're at beginning (\<)
- boolean doNext = false;
-
- if ((where & BEGIN) == BEGIN) {
- doNext = after && !before;
- }
- if ((where & END) == END) {
- doNext ^= before && !after;
- }
-
- if (negated) doNext = !doNext;
-
- return (doNext ? next(input, mymatch) : false);
- }
-
- void dump(StringBuffer os) {
- if (where == (BEGIN | END)) {
- os.append( negated ? "\\B" : "\\b" );
- } else if (where == BEGIN) {
- os.append("\\<");
- } else {
- os.append("\\>");
- }
- }
-}
+++ /dev/null
-/*
- * gnu/regexp/UncheckedRE.java
- * Copyright (C) 2001 Wes Biggs
- *
- * This library is free software; you can redistribute it and/or modify
- * it under the terms of the GNU Lesser General Public License as published
- * by the Free Software Foundation; either version 2.1 of the License, or
- * (at your option) any later version.
- *
- * This library 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 Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-package gnu.regexp;
-
-/**
- * UncheckedRE is a subclass of RE that allows programmers an easier means
- * of programmatically precompiling regular expressions. It is constructed
- * and used in exactly the same manner as an instance of the RE class; the
- * only difference is that its constructors do not throw REException.
- * Instead, if a syntax error is encountered during construction, a
- * RuntimeException will be thrown.
- * <P>
- * Note that this makes UncheckedRE dangerous if constructed with
- * dynamic data. Do not use UncheckedRE unless you are completely sure
- * that all input being passed to it contains valid, well-formed
- * regular expressions for the syntax specified.
- *
- * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
- * @see gnu.regexp.RE
- * @since gnu.regexp 1.1.4
- */
-
-public final class UncheckedRE extends RE {
- /**
- * Constructs a regular expression pattern buffer without any compilation
- * flags set, and using the default syntax (RESyntax.RE_SYNTAX_PERL5).
- *
- * @param pattern A regular expression pattern, in the form of a String,
- * StringBuffer or char[]. Other input types will be converted to
- * strings using the toString() method.
- * @exception RuntimeException The input pattern could not be parsed.
- * @exception NullPointerException The pattern was null.
- */
- public UncheckedRE(Object pattern) {
- this(pattern,0,RESyntax.RE_SYNTAX_PERL5);
- }
-
- /**
- * Constructs a regular expression pattern buffer using the specified
- * compilation flags and the default syntax (RESyntax.RE_SYNTAX_PERL5).
- *
- * @param pattern A regular expression pattern, in the form of a String,
- * StringBuffer, or char[]. Other input types will be converted to
- * strings using the toString() method.
- * @param cflags The logical OR of any combination of the compilation flags in the RE class.
- * @exception RuntimeException The input pattern could not be parsed.
- * @exception NullPointerException The pattern was null.
- */
- public UncheckedRE(Object pattern, int cflags) {
- this(pattern,cflags,RESyntax.RE_SYNTAX_PERL5);
- }
-
- /**
- * Constructs a regular expression pattern buffer using the specified
- * compilation flags and regular expression syntax.
- *
- * @param pattern A regular expression pattern, in the form of a String,
- * StringBuffer, or char[]. Other input types will be converted to
- * strings using the toString() method.
- * @param cflags The logical OR of any combination of the compilation flags in the RE class.
- * @param syntax The type of regular expression syntax to use.
- * @exception RuntimeException The input pattern could not be parsed.
- * @exception NullPointerException The pattern was null.
- */
- public UncheckedRE(Object pattern, int cflags, RESyntax syntax) {
- try {
- initialize(pattern,cflags,syntax,0,0);
- } catch (REException e) {
- throw new RuntimeException(e.getMessage());
- }
- }
-}
-
-
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public abstract class ASN1OctetString
- extends DERObject
-{
- byte[] string;
-
- /**
- * return an Octet String from a tagged object.
- *
- * @param obj the tagged object holding the object we want.
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static ASN1OctetString getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * return an Octet String from the given object.
- *
- * @param obj the object we want converted.
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static ASN1OctetString getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof ASN1OctetString)
- {
- return (ASN1OctetString)obj;
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- if (obj instanceof ASN1Sequence)
- {
- Vector v = new Vector();
- Enumeration e = ((ASN1Sequence)obj).getObjects();
-
- while (e.hasMoreElements())
- {
- v.addElement(e.nextElement());
- }
-
- return new BERConstructedOctetString(v);
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * @param string the octets making up the octet string.
- */
- public ASN1OctetString(
- byte[] string)
- {
- this.string = string;
- }
-
- public ASN1OctetString(
- DEREncodable obj)
- {
- try
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
-
- dOut.writeObject(obj);
- dOut.close();
-
- this.string = bOut.toByteArray();
- }
- catch (IOException e)
- {
- throw new IllegalArgumentException("Error processing object : " + e.toString());
- }
- }
-
- public byte[] getOctets()
- {
- return string;
- }
-
- public int hashCode()
- {
- byte[] b = this.getOctets();
- int value = 0;
-
- for (int i = 0; i != b.length; i++)
- {
- value ^= (b[i] & 0xff) << (i % 4);
- }
-
- return value;
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof DEROctetString))
- {
- return false;
- }
-
- DEROctetString other = (DEROctetString)o;
-
- byte[] b1 = other.getOctets();
- byte[] b2 = this.getOctets();
-
- if (b1.length != b2.length)
- {
- return false;
- }
-
- for (int i = 0; i != b1.length; i++)
- {
- if (b1[i] != b2[i])
- {
- return false;
- }
- }
-
- return true;
- }
-
- abstract void encode(DEROutputStream out)
- throws IOException;
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-public class ASN1OutputStream
- extends DEROutputStream
-{
- public ASN1OutputStream(
- OutputStream os)
- {
- super(os);
- }
-
- public void writeObject(
- Object obj)
- throws IOException
- {
- if (obj == null)
- {
- writeNull();
- }
- else if (obj instanceof DERObject)
- {
- ((DERObject)obj).encode(this);
- }
- else if (obj instanceof DEREncodable)
- {
- ((DEREncodable)obj).getDERObject().encode(this);
- }
- else
- {
- throw new IOException("object not ASN1Encodable");
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public abstract class ASN1Sequence
- extends DERObject
-{
- private Vector seq = new Vector();
-
- /**
- * return an ASN1Sequence from the given object.
- *
- * @param obj the object we want converted.
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static ASN1Sequence getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof ASN1Sequence)
- {
- return (ASN1Sequence)obj;
- }
-
- throw new IllegalArgumentException("unknown object in getInstance");
- }
-
- /**
- * Return an ASN1 sequence from a tagged object. There is a special
- * case here, if an object appears to have been explicitly tagged on
- * reading but we were expecting it to be implictly tagged in the
- * normal course of events it indicates that we lost the surrounding
- * sequence - so we need to add it back (this will happen if the tagged
- * object is a sequence that contains other sequences). If you are
- * dealing with implicitly tagged sequences you really <b>should</b>
- * be using this method.
- *
- * @param obj the tagged object.
- * @param explicit true if the object is meant to be explicitly tagged,
- * false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static ASN1Sequence getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- if (explicit)
- {
- if (!obj.isExplicit())
- {
- throw new IllegalArgumentException("object implicit - explicit expected.");
- }
-
- return (ASN1Sequence)obj.getObject();
- }
- else
- {
- //
- // constructed object which appears to be explicitly tagged
- // when it should be implicit means we have to add the
- // surrounding sequence.
- //
- if (obj.isExplicit())
- {
- ASN1Sequence seq;
-
- if (obj instanceof BERTaggedObject)
- {
- seq = new BERConstructedSequence();
- }
- else
- {
- seq = new DERConstructedSequence();
- }
-
- seq.addObject(obj.getObject());
-
- return seq;
- }
- else
- {
- ASN1Sequence seq;
-
- if (obj.getObject() instanceof ASN1Sequence)
- {
- return (ASN1Sequence)obj.getObject();
- }
- }
- }
-
- throw new IllegalArgumentException(
- "unknown object in getInstanceFromTagged");
- }
-
- public Enumeration getObjects()
- {
- return seq.elements();
- }
-
- /**
- * return the object at the sequence postion indicated by index.
- *
- * @param the sequence number (starting at zero) of the object
- * @return the object at the sequence postion indicated by index.
- */
- public DEREncodable getObjectAt(
- int index)
- {
- return (DEREncodable)seq.elementAt(index);
- }
-
- /**
- * return the number of objects in this sequence.
- *
- * @return the number of objects in this sequence.
- */
- public int size()
- {
- return seq.size();
- }
-
- public int hashCode()
- {
- Enumeration e = this.getObjects();
- int hashCode = 0;
-
- while (e.hasMoreElements())
- {
- hashCode ^= e.nextElement().hashCode();
- }
-
- return hashCode;
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof ASN1Sequence))
- {
- return false;
- }
-
- ASN1Sequence other = (ASN1Sequence)o;
-
- if (this.size() != other.size())
- {
- return false;
- }
-
- Enumeration s1 = this.getObjects();
- Enumeration s2 = other.getObjects();
-
- while (s1.hasMoreElements())
- {
- if (!s1.nextElement().equals(s2.nextElement()))
- {
- return false;
- }
- }
-
- return true;
- }
-
- protected void addObject(
- DEREncodable obj)
- {
- seq.addElement(obj);
- }
-
- abstract void encode(DEROutputStream out)
- throws IOException;
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-abstract public class ASN1Set
- extends DERObject
-{
- protected Vector set = new Vector();
-
- /**
- * return an ASN1Set from the given object.
- *
- * @param obj the object we want converted.
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static ASN1Set getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof ASN1Set)
- {
- return (ASN1Set)obj;
- }
-
- throw new IllegalArgumentException("unknown object in getInstance");
- }
-
- /**
- * Return an ASN1 set from a tagged object. There is a special
- * case here, if an object appears to have been explicitly tagged on
- * reading but we were expecting it to be implictly tagged in the
- * normal course of events it indicates that we lost the surrounding
- * set - so we need to add it back (this will happen if the tagged
- * object is a sequence that contains other sequences). If you are
- * dealing with implicitly tagged sets you really <b>should</b>
- * be using this method.
- *
- * @param obj the tagged object.
- * @param explicit true if the object is meant to be explicitly tagged
- * false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static ASN1Set getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- if (explicit)
- {
- if (!obj.isExplicit())
- {
- throw new IllegalArgumentException("object implicit - explicit expected.");
- }
-
- return (ASN1Set)obj.getObject();
- }
- else
- {
- //
- // constructed object which appears to be explicitly tagged
- // and it's really implicit means we have to add the
- // surrounding sequence.
- //
- if (obj.isExplicit())
- {
- ASN1Set set = new DERSet(obj.getObject());
-
- return set;
- }
- else
- {
- //
- // in this case the parser returns a sequence, convert it
- // into a set.
- //
- DEREncodableVector v = new DEREncodableVector();
-
- if (obj.getObject() instanceof ASN1Sequence)
- {
- ASN1Sequence s = (ASN1Sequence)obj.getObject();
- Enumeration e = s.getObjects();
-
- while (e.hasMoreElements())
- {
- v.add((DEREncodable)e.nextElement());
- }
-
- return new DERSet(v);
- }
- }
- }
-
- throw new IllegalArgumentException(
- "unknown object in getInstanceFromTagged");
- }
-
- public ASN1Set()
- {
- }
-
- public Enumeration getObjects()
- {
- return set.elements();
- }
-
- /**
- * return the object at the set postion indicated by index.
- *
- * @param the set number (starting at zero) of the object
- * @return the object at the set postion indicated by index.
- */
- public DEREncodable getObjectAt(
- int index)
- {
- return (DEREncodable)set.elementAt(index);
- }
-
- /**
- * return the number of objects in this set.
- *
- * @return the number of objects in this set.
- */
- public int size()
- {
- return set.size();
- }
-
- public int hashCode()
- {
- Enumeration e = this.getObjects();
- int hashCode = 0;
-
- while (e.hasMoreElements())
- {
- hashCode ^= e.nextElement().hashCode();
- }
-
- return hashCode;
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof ASN1Set))
- {
- return false;
- }
-
- ASN1Set other = (ASN1Set)o;
-
- if (this.size() != other.size())
- {
- return false;
- }
-
- Enumeration s1 = this.getObjects();
- Enumeration s2 = other.getObjects();
-
- while (s1.hasMoreElements())
- {
- if (!s1.nextElement().equals(s2.nextElement()))
- {
- return false;
- }
- }
-
- return true;
- }
-
- protected void addObject(
- DEREncodable obj)
- {
- set.addElement(obj);
- }
-
- abstract void encode(DEROutputStream out)
- throws IOException;
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * ASN.1 TaggedObject - in ASN.1 nottation this is any object proceeded by
- * a [n] where n is some number - these are assume to follow the construction
- * rules (as with sequences).
- */
-public abstract class ASN1TaggedObject
- extends DERObject
-{
- int tagNo;
- boolean empty = false;
- boolean explicit = true;
- DEREncodable obj = null;
-
- /**
- * @param tagNo the tag number for this object.
- * @param obj the tagged object.
- */
- public ASN1TaggedObject(
- int tagNo,
- DEREncodable obj)
- {
- this.explicit = true;
- this.tagNo = tagNo;
- this.obj = obj;
- }
-
- /**
- * @param explicit true if the object is explicitly tagged.
- * @param tagNo the tag number for this object.
- * @param obj the tagged object.
- */
- public ASN1TaggedObject(
- boolean explicit,
- int tagNo,
- DEREncodable obj)
- {
- this.explicit = explicit;
- this.tagNo = tagNo;
- this.obj = obj;
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof ASN1TaggedObject))
- {
- return false;
- }
-
- ASN1TaggedObject other = (ASN1TaggedObject)o;
-
- if(tagNo != other.tagNo || empty != other.empty || explicit != other.explicit)
- {
- return false;
- }
-
- if(obj == null)
- {
- if(other.obj != null)
- {
- return false;
- }
- }
- else
- {
- if(!(obj.equals(other.obj)))
- {
- return false;
- }
- }
-
- return true;
- }
-
- public int getTagNo()
- {
- return tagNo;
- }
-
- /**
- * return whether or not the object may be explicitly tagged.
- * <p>
- * Note: if the object has been read from an input stream, the only
- * time you can be sure if isExplicit is returning the true state of
- * affairs is if it returns false. An implicitly tagged object may appear
- * to be explicitly tagged, so you need to understand the context under
- * which the reading was done as well, see getObject below.
- */
- public boolean isExplicit()
- {
- return explicit;
- }
-
- public boolean isEmpty()
- {
- return empty;
- }
-
- /**
- * return whatever was following the tag.
- * <p>
- * Note: tagged objects are generally context dependent if you're
- * trying to extract a tagged object you should be going via the
- * appropriate getInstance method.
- */
- public DERObject getObject()
- {
- if (obj != null)
- {
- return obj.getDERObject();
- }
-
- return null;
- }
-
- abstract void encode(DEROutputStream out)
- throws IOException;
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public class BERConstructedOctetString
- extends DEROctetString
-{
- /**
- * convert a vector of octet strings into a single byte string
- */
- static private byte[] toBytes(
- Vector octs)
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
-
- for (int i = 0; i != octs.size(); i++)
- {
- DEROctetString o = (DEROctetString)octs.elementAt(i);
-
- try
- {
- bOut.write(o.getOctets());
- }
- catch (IOException e)
- {
- throw new RuntimeException("exception converting octets " + e.toString());
- }
- }
-
- return bOut.toByteArray();
- }
-
- private Vector octs;
-
- /**
- * @param string the octets making up the octet string.
- */
- public BERConstructedOctetString(
- byte[] string)
- {
- super(string);
- }
-
- public BERConstructedOctetString(
- Vector octs)
- {
- super(toBytes(octs));
-
- this.octs = octs;
- }
-
- public BERConstructedOctetString(
- DERObject obj)
- {
- super(obj);
- }
-
- public BERConstructedOctetString(
- DEREncodable obj)
- {
- super(obj.getDERObject());
- }
-
- public byte[] getOctets()
- {
- return string;
- }
-
- /**
- * return the DER octets that make up this string.
- */
- public Enumeration getObjects()
- {
- if (octs == null)
- {
- octs = generateOcts();
- }
-
- return octs.elements();
- }
-
- private Vector generateOcts()
- {
- int start = 0;
- int end = 0;
- Vector vec = new Vector();
-
- while ((end + 1) < string.length)
- {
- if (string[end] == 0 && string[end + 1] == 0)
- {
- byte[] nStr = new byte[end - start + 1];
-
- for (int i = 0; i != nStr.length; i++)
- {
- nStr[i] = string[start + i];
- }
-
- vec.addElement(new DEROctetString(nStr));
- start = end + 1;
- }
- end++;
- }
-
- byte[] nStr = new byte[string.length - start];
- for (int i = 0; i != nStr.length; i++)
- {
- nStr[i] = string[start + i];
- }
-
- vec.addElement(new DEROctetString(nStr));
-
- return vec;
- }
-
- public void encode(
- DEROutputStream out)
- throws IOException
- {
- if (out instanceof ASN1OutputStream || out instanceof BEROutputStream)
- {
- out.write(CONSTRUCTED | OCTET_STRING);
-
- out.write(0x80);
-
- if (octs == null)
- {
- octs = generateOcts();
- }
-
- for (int i = 0; i != octs.size(); i++)
- {
- out.writeObject(octs.elementAt(i));
- }
-
- out.write(0x00);
- out.write(0x00);
- }
- else
- {
- super.encode(out);
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public class BERConstructedSequence
- extends DERConstructedSequence
-{
- /*
- */
- void encode(
- DEROutputStream out)
- throws IOException
- {
- if (out instanceof ASN1OutputStream || out instanceof BEROutputStream)
- {
- out.write(SEQUENCE | CONSTRUCTED);
- out.write(0x80);
-
- Enumeration e = getObjects();
- while (e.hasMoreElements())
- {
- out.writeObject(e.nextElement());
- }
-
- out.write(0x00);
- out.write(0x00);
- }
- else
- {
- super.encode(out);
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public class BERInputStream
- extends DERInputStream
-{
- private DERObject END_OF_STREAM = new DERObject() {
- void encode(
- DEROutputStream out)
- throws IOException
- {
- throw new IOException("Eeek!");
- }
-
- };
- public BERInputStream(
- InputStream is)
- {
- super(is);
- }
-
- /**
- * read a string of bytes representing an indefinite length object.
- */
- private byte[] readIndefiniteLengthFully()
- throws IOException
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- int b, b1;
-
- b1 = read();
-
- while ((b = read()) >= 0)
- {
- if (b1 == 0 && b == 0)
- {
- break;
- }
-
- bOut.write(b1);
- b1 = b;
- }
-
- return bOut.toByteArray();
- }
-
- private BERConstructedOctetString buildConstructedOctetString()
- throws IOException
- {
- Vector octs = new Vector();
-
- for (;;)
- {
- DERObject o = readObject();
-
- if (o == END_OF_STREAM)
- {
- break;
- }
-
- octs.addElement(o);
- }
-
- return new BERConstructedOctetString(octs);
- }
-
- public DERObject readObject()
- throws IOException
- {
- int tag = read();
- if (tag == -1)
- {
- throw new EOFException();
- }
-
- int length = readLength();
-
- if (length < 0) // indefinite length method
- {
- switch (tag)
- {
- case NULL:
- return null;
- case SEQUENCE | CONSTRUCTED:
- BERConstructedSequence seq = new BERConstructedSequence();
-
- for (;;)
- {
- DERObject obj = readObject();
-
- if (obj == END_OF_STREAM)
- {
- break;
- }
-
- seq.addObject(obj);
- }
- return seq;
- case OCTET_STRING | CONSTRUCTED:
- return buildConstructedOctetString();
- case SET | CONSTRUCTED:
- DEREncodableVector v = new DEREncodableVector();
-
- for (;;)
- {
- DERObject obj = readObject();
-
- if (obj == END_OF_STREAM)
- {
- break;
- }
-
- v.add(obj);
- }
- return new BERSet(v);
- default:
- //
- // with tagged object tag number is bottom 5 bits
- //
- if ((tag & TAGGED) != 0)
- {
- if ((tag & 0x1f) == 0x1f)
- {
- throw new IOException("unsupported high tag encountered");
- }
-
- //
- // simple type - implicit... return an octet string
- //
- if ((tag & CONSTRUCTED) == 0)
- {
- byte[] bytes = readIndefiniteLengthFully();
-
- return new BERTaggedObject(false, tag & 0x1f, new DEROctetString(bytes));
- }
-
- //
- // either constructed or explicitly tagged
- //
- DERObject dObj = readObject();
-
- if (dObj == END_OF_STREAM) // empty tag!
- {
- return new DERTaggedObject(tag & 0x1f);
- }
-
- DERObject next = readObject();
-
- //
- // explicitly tagged (probably!) - if it isn't we'd have to
- // tell from the context
- //
- if (next == END_OF_STREAM)
- {
- return new BERTaggedObject(tag & 0x1f, dObj);
- }
-
- //
- // another implicit object, we'll create a sequence...
- //
- seq = new BERConstructedSequence();
-
- seq.addObject(dObj);
-
- do
- {
- seq.addObject(next);
- next = readObject();
- }
- while (next != END_OF_STREAM);
-
- return new BERTaggedObject(false, tag & 0x1f, seq);
- }
-
- throw new IOException("unknown BER object encountered");
- }
- }
- else
- {
- if (tag == 0 && length == 0) // end of contents marker.
- {
- return END_OF_STREAM;
- }
-
- byte[] bytes = new byte[length];
-
- readFully(bytes);
-
- return buildObject(tag, bytes);
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-public class BEROutputStream
- extends DEROutputStream
-{
- public BEROutputStream(
- OutputStream os)
- {
- super(os);
- }
-
- public void writeObject(
- Object obj)
- throws IOException
- {
- if (obj == null)
- {
- writeNull();
- }
- else if (obj instanceof DERObject)
- {
- ((DERObject)obj).encode(this);
- }
- else if (obj instanceof DEREncodable)
- {
- ((DEREncodable)obj).getDERObject().encode(this);
- }
- else
- {
- throw new IOException("object not BEREncodable");
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public class BERSet
- extends DERSet
-{
- /**
- * create an empty sequence
- */
- public BERSet()
- {
- }
-
- /**
- * create a set containing one object
- */
- public BERSet(
- DEREncodable obj)
- {
- super(obj);
- }
-
- /**
- * create a set containing a vector of objects.
- */
- public BERSet(
- DEREncodableVector v)
- {
- super(v);
- }
-
- /*
- */
- void encode(
- DEROutputStream out)
- throws IOException
- {
- if (out instanceof ASN1OutputStream || out instanceof BEROutputStream)
- {
- out.write(SET | CONSTRUCTED);
- out.write(0x80);
-
- Enumeration e = getObjects();
- while (e.hasMoreElements())
- {
- out.writeObject(e.nextElement());
- }
-
- out.write(0x00);
- out.write(0x00);
- }
- else
- {
- super.encode(out);
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-/**
- * BER TaggedObject - in ASN.1 nottation this is any object proceeded by
- * a [n] where n is some number - these are assume to follow the construction
- * rules (as with sequences).
- */
-public class BERTaggedObject
- extends DERTaggedObject
-{
- /**
- * @param tagNo the tag number for this object.
- * @param obj the tagged object.
- */
- public BERTaggedObject(
- int tagNo,
- DEREncodable obj)
- {
- super(tagNo, obj);
- }
-
- /**
- * @param explicit true if an explicitly tagged object.
- * @param tagNo the tag number for this object.
- * @param obj the tagged object.
- */
- public BERTaggedObject(
- boolean explicit,
- int tagNo,
- DEREncodable obj)
- {
- super(explicit, tagNo, obj);
- }
-
- /**
- * create an implicitly tagged object that contains a zero
- * length sequence.
- */
- public BERTaggedObject(
- int tagNo)
- {
- super(false, tagNo, new BERConstructedSequence());
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- if (out instanceof ASN1OutputStream || out instanceof BEROutputStream)
- {
- out.write(CONSTRUCTED | TAGGED | tagNo);
- out.write(0x80);
-
- if (!empty)
- {
- if (!explicit)
- {
- if (obj instanceof BERConstructedOctetString)
- {
- Enumeration e = ((BERConstructedOctetString)obj).getObjects();
-
- while (e.hasMoreElements())
- {
- out.writeObject(e.nextElement());
- }
- }
- else if (obj instanceof ASN1Sequence)
- {
- Enumeration e = ((ASN1Sequence)obj).getObjects();
-
- while (e.hasMoreElements())
- {
- out.writeObject(e.nextElement());
- }
- }
- else if (obj instanceof ASN1Set)
- {
- Enumeration e = ((ASN1Set)obj).getObjects();
-
- while (e.hasMoreElements())
- {
- out.writeObject(e.nextElement());
- }
- }
- else
- {
- throw new RuntimeException("not implemented: " + obj.getClass().getName());
- }
- }
- else
- {
- out.writeObject(obj);
- }
- }
-
- out.write(0x00);
- out.write(0x00);
- }
- else
- {
- super.encode(out);
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * DER BMPString object.
- */
-public class DERBMPString
- extends DERObject
- implements DERString
-{
- String string;
-
- /**
- * return a BMP String from the given object.
- *
- * @param obj the object we want converted.
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERBMPString getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERBMPString)
- {
- return (DERBMPString)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERBMPString(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return a BMP String from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERBMPString getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
-
- /**
- * basic constructor - byte encoded string.
- */
- public DERBMPString(
- byte[] string)
- {
- char[] cs = new char[string.length / 2];
-
- for (int i = 0; i != cs.length; i++)
- {
- cs[i] = (char)((string[2 * i] << 8) | (string[2 * i + 1] & 0xff));
- }
-
- this.string = new String(cs);
- }
-
- /**
- * basic constructor
- */
- public DERBMPString(
- String string)
- {
- this.string = string;
- }
-
- public String getString()
- {
- return string;
- }
-
- public int hashCode()
- {
- return this.getString().hashCode();
- }
-
- public boolean equals(
- Object o)
- {
- if (!(o instanceof DERBMPString))
- {
- return false;
- }
-
- DERPrintableString s = (DERPrintableString)o;
-
- return this.getString().equals(s.getString());
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- char[] c = string.toCharArray();
- byte[] b = new byte[c.length * 2];
-
- for (int i = 0; i != c.length; i++)
- {
- b[2 * i] = (byte)(c[i] >> 8);
- b[2 * i + 1] = (byte)c[i];
- }
-
- out.writeEncoded(BMP_STRING, b);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-public class DERBitString
- extends DERObject
-{
- protected byte[] data;
- protected int padBits;
-
- /**
- * return the correct number of pad bits for a bit string defined in
- * a 16 bit constant
- */
- static protected int getPadBits(
- int bitString)
- {
- int val;
-
- if (bitString == 0)
- {
- return 7;
- }
-
- if (bitString > 255)
- {
- val = ((bitString >> 8) & 0xFF);
- }
- else
- {
- val = (bitString & 0xFF);
- }
-
- int bits = 1;
-
- while (((val <<= 1) & 0xFF) != 0)
- {
- bits++;
- }
-
- return 8 - bits;
- }
-
- /**
- * return the correct number of bytes for a bit string defined in
- * a 16 bit constant
- */
- static protected byte[] getBytes(
- int bitString)
- {
- if (bitString > 255)
- {
- byte[] bytes = new byte[2];
-
- bytes[0] = (byte)(bitString & 0xFF);
- bytes[1] = (byte)((bitString >> 8) & 0xFF);
-
- return bytes;
- }
- else
- {
- byte[] bytes = new byte[1];
-
- bytes[0] = (byte)(bitString & 0xFF);
-
- return bytes;
- }
- }
-
- /**
- * return a Bit String from the passed in object
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERBitString getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERBitString)
- {
- return (DERBitString)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- byte[] bytes = ((ASN1OctetString)obj).getOctets();
- int padBits = bytes[0];
- byte[] data = new byte[bytes.length - 1];
-
- System.arraycopy(bytes, 1, data, 0, bytes.length - 1);
-
- return new DERBitString(data, padBits);
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return a Bit String from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERBitString getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- protected DERBitString(
- byte data,
- int padBits)
- {
- this.data = new byte[1];
- this.data[0] = data;
- this.padBits = padBits;
- }
-
- /**
- * @param data the octets making up the bit string.
- * @param padBits the number of extra bits at the end of the string.
- */
- public DERBitString(
- byte[] data,
- int padBits)
- {
- this.data = data;
- this.padBits = padBits;
- }
-
- public DERBitString(
- byte[] data)
- {
- this(data, 0);
- }
-
- public DERBitString(
- DEREncodable obj)
- {
- try
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
-
- dOut.writeObject(obj);
- dOut.close();
-
- this.data = bOut.toByteArray();
- this.padBits = 0;
- }
- catch (IOException e)
- {
- throw new IllegalArgumentException("Error processing object : " + e.toString());
- }
- }
-
- public byte[] getBytes()
- {
- return data;
- }
-
- public int getPadBits()
- {
- return padBits;
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- byte[] bytes = new byte[getBytes().length + 1];
-
- bytes[0] = (byte)getPadBits();
- System.arraycopy(getBytes(), 0, bytes, 1, bytes.length - 1);
-
- out.writeEncoded(BIT_STRING, bytes);
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof DERBitString))
- {
- return false;
- }
-
- DERBitString other = (DERBitString)o;
-
- if (data.length != other.data.length)
- {
- return false;
- }
-
- for (int i = 0; i != data.length; i++)
- {
- if (data[i] != other.data[i])
- {
- return false;
- }
- }
-
- return (padBits == other.padBits);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-public class DERBoolean
- extends DERObject
-{
- byte value;
-
- public static final DERBoolean FALSE = new DERBoolean(false);
- public static final DERBoolean TRUE = new DERBoolean(true);
-
- /**
- * return a boolean from the passed in object.
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERBoolean getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERBoolean)
- {
- return (DERBoolean)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERBoolean(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return a DERBoolean from the passed in boolean.
- */
- public static DERBoolean getInstance(
- boolean value)
- {
- return (value ? TRUE : FALSE);
- }
-
- /**
- * return a Boolean from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERBoolean getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- public DERBoolean(
- byte[] value)
- {
- this.value = value[0];
- }
-
- public DERBoolean(
- boolean value)
- {
- this.value = (value) ? (byte)0xff : (byte)0;
- }
-
- public boolean isTrue()
- {
- return (value != 0);
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- byte[] bytes = new byte[1];
-
- bytes[0] = value;
-
- out.writeEncoded(BOOLEAN, bytes);
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof DERBoolean))
- {
- return false;
- }
-
- return (value == ((DERBoolean)o).value);
- }
-
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public class DERConstructedSequence
- extends ASN1Sequence
-{
- public void addObject(
- DEREncodable obj)
- {
- super.addObject(obj);
- }
-
- public int getSize()
- {
- return size();
- }
-
- /*
- * A note on the implementation:
- * <p>
- * As DER requires the constructed, definite-length model to
- * be used for structured types, this varies slightly from the
- * ASN.1 descriptions given. Rather than just outputing SEQUENCE,
- * we also have to specify CONSTRUCTED, and the objects length.
- */
- void encode(
- DEROutputStream out)
- throws IOException
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
- Enumeration e = this.getObjects();
-
- while (e.hasMoreElements())
- {
- Object obj = e.nextElement();
-
- dOut.writeObject(obj);
- }
-
- dOut.close();
-
- byte[] bytes = bOut.toByteArray();
-
- out.writeEncoded(SEQUENCE | CONSTRUCTED, bytes);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public class DERConstructedSet
- extends ASN1Set
-{
- public DERConstructedSet()
- {
- }
-
- /**
- * @param obj - a single object that makes up the set.
- */
- public DERConstructedSet(
- DEREncodable obj)
- {
- this.addObject(obj);
- }
-
- /**
- * @param v - a vector of objects making up the set.
- */
- public DERConstructedSet(
- DEREncodableVector v)
- {
- for (int i = 0; i != v.size(); i++)
- {
- this.addObject(v.get(i));
- }
- }
-
- public void addObject(
- DEREncodable obj)
- {
- super.addObject(obj);
- }
-
- public int getSize()
- {
- return size();
- }
-
- /*
- * A note on the implementation:
- * <p>
- * As DER requires the constructed, definite-length model to
- * be used for structured types, this varies slightly from the
- * ASN.1 descriptions given. Rather than just outputing SET,
- * we also have to specify CONSTRUCTED, and the objects length.
- */
- void encode(
- DEROutputStream out)
- throws IOException
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
- Enumeration e = this.getObjects();
-
- while (e.hasMoreElements())
- {
- Object obj = e.nextElement();
-
- dOut.writeObject(obj);
- }
-
- dOut.close();
-
- byte[] bytes = bOut.toByteArray();
-
- out.writeEncoded(SET | CONSTRUCTED, bytes);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-public interface DEREncodable
-{
- public DERObject getDERObject();
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.util.Vector;
-
-/**
- * a general class for building up a vector of DER encodable objects
- */
-public class DEREncodableVector
-{
- private Vector v = new Vector();
-
- public void add(
- DEREncodable obj)
- {
- v.addElement(obj);
- }
-
- public DEREncodable get(
- int i)
- {
- return (DEREncodable)v.elementAt(i);
- }
-
- public int size()
- {
- return v.size();
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.math.BigInteger;
-
-public class DEREnumerated
- extends DERObject
-{
- byte[] bytes;
-
- /**
- * return an integer from the passed in object
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DEREnumerated getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DEREnumerated)
- {
- return (DEREnumerated)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DEREnumerated(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return an Enumerated from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DEREnumerated getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- public DEREnumerated(
- int value)
- {
- bytes = BigInteger.valueOf(value).toByteArray();
- }
-
- public DEREnumerated(
- BigInteger value)
- {
- bytes = value.toByteArray();
- }
-
- public DEREnumerated(
- byte[] bytes)
- {
- this.bytes = bytes;
- }
-
- public BigInteger getValue()
- {
- return new BigInteger(bytes);
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(ENUMERATED, bytes);
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof DEREnumerated))
- {
- return false;
- }
-
- DEREnumerated other = (DEREnumerated)o;
-
- if (bytes.length != other.bytes.length)
- {
- return false;
- }
-
- for (int i = 0; i != bytes.length; i++)
- {
- if (bytes[i] != other.bytes[i])
- {
- return false;
- }
- }
-
- return true;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.util.*;
-import java.io.*;
-import java.text.*;
-
-/**
- * Generalized time object.
- */
-public class DERGeneralizedTime
- extends DERObject
-{
- String time;
-
- /**
- * return a generalized time from the passed in object
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERGeneralizedTime getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERGeneralizedTime)
- {
- return (DERGeneralizedTime)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERGeneralizedTime(((ASN1OctetString)obj).getOctets());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return a Generalized Time object from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERGeneralizedTime getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * The correct format for this is YYYYMMDDHHMMSSZ, or without the Z
- * for local time, or Z+-HHMM on the end, for difference between local
- * time and UTC time.
- * <p>
- *
- * @param time the time string.
- */
- public DERGeneralizedTime(
- String time)
- {
- this.time = time;
- }
-
- /**
- * base constructer from a java.util.date object
- */
- public DERGeneralizedTime(
- Date time)
- {
- SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
-
- dateF.setTimeZone(new SimpleTimeZone(0,"Z"));
-
- this.time = dateF.format(time);
- }
-
- DERGeneralizedTime(
- byte[] bytes)
- {
- //
- // explicitly convert to characters
- //
- char[] dateC = new char[bytes.length];
-
- for (int i = 0; i != dateC.length; i++)
- {
- dateC[i] = (char)(bytes[i] & 0xff);
- }
-
- this.time = new String(dateC);
- }
-
- /**
- * return the time - always in the form of
- * YYYYMMDDhhmmssGMT(+hh:mm|-hh:mm).
- * <p>
- * Normally in a certificate we would expect "Z" rather than "GMT",
- * however adding the "GMT" means we can just use:
- * <pre>
- * dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
- * </pre>
- * To read in the time and get a date which is compatible with our local
- * time zone.
- */
- public String getTime()
- {
- //
- // standardise the format.
- //
- if (time.length() == 15)
- {
- return time.substring(0, 14) + "GMT+00:00";
- }
- else if (time.length() == 17)
- {
- return time.substring(0, 14) + "GMT" + time.substring(15, 17) + ":" + time.substring(17, 19);
- }
-
- return time;
- }
-
- private byte[] getOctets()
- {
- char[] cs = time.toCharArray();
- byte[] bs = new byte[cs.length];
-
- for (int i = 0; i != cs.length; i++)
- {
- bs[i] = (byte)cs[i];
- }
-
- return bs;
- }
-
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(GENERALIZED_TIME, this.getOctets());
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof DERGeneralizedTime))
- {
- return false;
- }
-
- return time.equals(((DERGeneralizedTime)o).time);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * DER IA5String object - this is an ascii string.
- */
-public class DERIA5String
- extends DERObject
- implements DERString
-{
- String string;
-
- /**
- * return a IA5 string from the passed in object
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERIA5String getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERIA5String)
- {
- return (DERIA5String)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERIA5String(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return an IA5 String from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERIA5String getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * basic constructor - with bytes.
- */
- public DERIA5String(
- byte[] string)
- {
- char[] cs = new char[string.length];
-
- for (int i = 0; i != cs.length; i++)
- {
- cs[i] = (char)(string[i] & 0xff);
- }
-
- this.string = new String(cs);
- }
-
- /**
- * basic constructor - with string.
- */
- public DERIA5String(
- String string)
- {
- this.string = string;
- }
-
- public String getString()
- {
- return string;
- }
-
- public byte[] getOctets()
- {
- char[] cs = string.toCharArray();
- byte[] bs = new byte[cs.length];
-
- for (int i = 0; i != cs.length; i++)
- {
- bs[i] = (byte)cs[i];
- }
-
- return bs;
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(IA5_STRING, this.getOctets());
- }
-
- public int hashCode()
- {
- return this.getString().hashCode();
- }
-
- public boolean equals(
- Object o)
- {
- if (!(o instanceof DERIA5String))
- {
- return false;
- }
-
- DERIA5String s = (DERIA5String)o;
-
- return this.getString().equals(s.getString());
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.FilterInputStream;
-
-import java.io.InputStream;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.EOFException;
-
-
-public class DERInputStream
- extends FilterInputStream implements DERTags
-{
- public DERInputStream(
- InputStream is)
- {
- super(is);
- }
-
- protected int readLength()
- throws IOException
- {
- int length = read();
- if (length < 0)
- {
- throw new IOException("EOF found when length expected");
- }
-
- if (length == 0x80)
- {
- return -1; // indefinite-length encoding
- }
-
- if (length > 127)
- {
- int size = length & 0x7f;
-
- length = 0;
- for (int i = 0; i < size; i++)
- {
- int next = read();
-
- if (next < 0)
- {
- throw new IOException("EOF found reading length");
- }
-
- length = (length << 8) + next;
- }
- }
-
- return length;
- }
-
- protected void readFully(
- byte[] bytes)
- throws IOException
- {
- int left = bytes.length;
-
- if (left == 0)
- {
- return;
- }
-
- while ((left -= read(bytes, bytes.length - left, left)) != 0)
- {
- ;
- }
- }
-
- /**
- * build an object given its tag and a byte stream to construct it
- * from.
- */
- protected DERObject buildObject(
- int tag,
- byte[] bytes)
- throws IOException
- {
- switch (tag)
- {
- case NULL:
- return null;
- case SEQUENCE | CONSTRUCTED:
- ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
- BERInputStream dIn = new BERInputStream(bIn);
- DERConstructedSequence seq = new DERConstructedSequence();
-
- try
- {
- for (;;)
- {
- DERObject obj = dIn.readObject();
-
- seq.addObject(obj);
- }
- }
- catch (EOFException ex)
- {
- return seq;
- }
- case SET | CONSTRUCTED:
- bIn = new ByteArrayInputStream(bytes);
- dIn = new BERInputStream(bIn);
-
- DEREncodableVector v = new DEREncodableVector();
-
- try
- {
- for (;;)
- {
- DERObject obj = dIn.readObject();
-
- v.add(obj);
- }
- }
- catch (EOFException ex)
- {
- return new DERConstructedSet(v);
- }
- case BOOLEAN:
- return new DERBoolean(bytes);
- case INTEGER:
- return new DERInteger(bytes);
- case ENUMERATED:
- return new DEREnumerated(bytes);
- case OBJECT_IDENTIFIER:
- return new DERObjectIdentifier(bytes);
- case BIT_STRING:
- int padBits = bytes[0];
- byte[] data = new byte[bytes.length - 1];
-
- System.arraycopy(bytes, 1, data, 0, bytes.length - 1);
-
- return new DERBitString(data, padBits);
- case UTF8_STRING:
- return new DERUTF8String(bytes);
- case PRINTABLE_STRING:
- return new DERPrintableString(bytes);
- case IA5_STRING:
- return new DERIA5String(bytes);
- case T61_STRING:
- return new DERT61String(bytes);
- case VISIBLE_STRING:
- return new DERVisibleString(bytes);
- case UNIVERSAL_STRING:
- return new DERUniversalString(bytes);
- case BMP_STRING:
- return new DERBMPString(bytes);
- case OCTET_STRING:
- return new DEROctetString(bytes);
- case UTC_TIME:
- return new DERUTCTime(bytes);
- case GENERALIZED_TIME:
- return new DERGeneralizedTime(bytes);
- default:
- //
- // with tagged object tag number is bottom 5 bits
- //
- if ((tag & TAGGED) != 0)
- {
- if ((tag & 0x1f) == 0x1f)
- {
- throw new IOException("unsupported high tag encountered");
- }
-
- if (bytes.length == 0) // empty tag!
- {
- return new DERTaggedObject(false, tag & 0x1f, new DERConstructedSequence());
- }
-
- //
- // simple type - implicit... return an octet string
- //
- if ((tag & CONSTRUCTED) == 0)
- {
- return new DERTaggedObject(false, tag & 0x1f, new DEROctetString(bytes));
- }
-
- bIn = new ByteArrayInputStream(bytes);
- dIn = new BERInputStream(bIn);
-
- DEREncodable dObj = dIn.readObject();
-
- //
- // explicitly tagged (probably!) - if it isn't we'd have to
- // tell from the context
- //
- if (dIn.available() == 0)
- {
- return new DERTaggedObject(tag & 0x1f, dObj);
- }
-
- //
- // another implicit object, we'll create a sequence...
- //
- seq = new DERConstructedSequence();
-
- seq.addObject(dObj);
-
- try
- {
- for (;;)
- {
- dObj = dIn.readObject();
-
- seq.addObject(dObj);
- }
- }
- catch (EOFException ex)
- {
- // ignore --
- }
-
- return new DERTaggedObject(false, tag & 0x1f, seq);
- }
-
- return new DERUnknownTag(tag, bytes);
- }
- }
-
- public DERObject readObject()
- throws IOException
- {
- int tag = read();
- if (tag == -1)
- {
- throw new EOFException();
- }
-
- int length = readLength();
- byte[] bytes = new byte[length];
-
- readFully(bytes);
-
- return buildObject(tag, bytes);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.math.BigInteger;
-
-public class DERInteger
- extends DERObject
-{
- byte[] bytes;
-
- /**
- * return an integer from the passed in object
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERInteger getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERInteger)
- {
- return (DERInteger)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERInteger(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return an Integer from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERInteger getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- public DERInteger(
- int value)
- {
- bytes = BigInteger.valueOf(value).toByteArray();
- }
-
- public DERInteger(
- BigInteger value)
- {
- bytes = value.toByteArray();
- }
-
- public DERInteger(
- byte[] bytes)
- {
- this.bytes = bytes;
- }
-
- public BigInteger getValue()
- {
- return new BigInteger(bytes);
- }
-
- /**
- * in some cases positive values get crammed into a space,
- * that's not quite big enough...
- */
- public BigInteger getPositiveValue()
- {
- return new BigInteger(1, bytes);
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(INTEGER, bytes);
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof DERInteger))
- {
- return false;
- }
-
- DERInteger other = (DERInteger)o;
-
- if (bytes.length != other.bytes.length)
- {
- return false;
- }
-
- for (int i = 0; i != bytes.length; i++)
- {
- if (bytes[i] != other.bytes[i])
- {
- return false;
- }
- }
-
- return true;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.IOException;
-
-public abstract class DERObject
- implements DERTags, DEREncodable
-{
- public DERObject getDERObject()
- {
- return this;
- }
-
- abstract void encode(DEROutputStream out)
- throws IOException;
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-public class DERObjectIdentifier
- extends DERObject
-{
- String identifier;
-
- /**
- * return an OID from the passed in object
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERObjectIdentifier getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERObjectIdentifier)
- {
- return (DERObjectIdentifier)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERObjectIdentifier(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return an Object Identifier from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERObjectIdentifier getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
-
- DERObjectIdentifier(
- byte[] bytes)
- {
- int head = bytes[0] & 0xff;
- StringBuffer objId = new StringBuffer();
- int value = 0;
- boolean first = true;
-
- for (int i = 0; i != bytes.length; i++)
- {
- int b = bytes[i] & 0xff;
-
- value = value * 128 + (b & 0x7f);
- if ((b & 0x80) == 0) // end of number reached
- {
- if (first)
- {
- switch (value / 40)
- {
- case 0:
- objId.append('0');
- break;
- case 1:
- objId.append('1');
- value -= 40;
- break;
- default:
- objId.append('2');
- value -= 80;
- }
- first = false;
- }
-
- objId.append('.');
- objId.append(Integer.toString(value));
- value = 0;
- }
- }
-
- this.identifier = objId.toString();
- }
-
- public DERObjectIdentifier(
- String identifier)
- {
- this.identifier = identifier;
- }
-
- public String getId()
- {
- return identifier;
- }
-
- private void writeField(
- OutputStream out,
- int fieldValue)
- throws IOException
- {
- if (fieldValue >= (1 << 7))
- {
- if (fieldValue >= (1 << 14))
- {
- if (fieldValue >= (1 << 21))
- {
- if (fieldValue >= (1 << 28))
- {
- out.write((fieldValue >> 28) | 0x80);
- }
- out.write((fieldValue >> 21) | 0x80);
- }
- out.write((fieldValue >> 14) | 0x80);
- }
- out.write((fieldValue >> 7) | 0x80);
- }
- out.write(fieldValue & 0x7f);
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- OIDTokenizer tok = new OIDTokenizer(identifier);
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
-
- writeField(bOut,
- Integer.parseInt(tok.nextToken()) * 40
- + Integer.parseInt(tok.nextToken()));
-
- while (tok.hasMoreTokens())
- {
- writeField(bOut, Integer.parseInt(tok.nextToken()));
- }
-
- dOut.close();
-
- byte[] bytes = bOut.toByteArray();
-
- out.writeEncoded(OBJECT_IDENTIFIER, bytes);
- }
-
- public int hashCode()
- {
- return identifier.hashCode();
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof DERObjectIdentifier))
- {
- return false;
- }
-
- return identifier.equals(((DERObjectIdentifier)o).identifier);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-public class DEROctetString
- extends ASN1OctetString
-{
- /**
- * @param string the octets making up the octet string.
- */
- public DEROctetString(
- byte[] string)
- {
- super(string);
- }
-
- public DEROctetString(
- DEREncodable obj)
- {
- super(obj);
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(OCTET_STRING, string);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.FilterOutputStream;
-
-import java.io.OutputStream;
-import java.io.IOException;
-
-public class DEROutputStream
- extends FilterOutputStream implements DERTags
-{
- public DEROutputStream(
- OutputStream os)
- {
- super(os);
- }
-
- private void writeLength(
- int length)
- throws IOException
- {
- if (length > 127)
- {
- int size = 1;
- int val = length;
-
- while ((val >>>= 8) != 0)
- {
- size++;
- }
-
- write((byte)(size | 0x80));
-
- for (int i = (size - 1) * 8; i >= 0; i -= 8)
- {
- write((byte)(length >> i));
- }
- }
- else
- {
- write((byte)length);
- }
- }
-
- void writeEncoded(
- int tag,
- byte[] bytes)
- throws IOException
- {
- write(tag);
- writeLength(bytes.length);
- write(bytes);
- }
-
- protected void writeNull()
- throws IOException
- {
- write(NULL);
- write(0x00);
- }
-
- public void writeObject(
- Object obj)
- throws IOException
- {
- if (obj == null)
- {
- writeNull();
- }
- else if (obj instanceof DERObject)
- {
- ((DERObject)obj).encode(this);
- }
- else if (obj instanceof DEREncodable)
- {
- ((DEREncodable)obj).getDERObject().encode(this);
- }
- else
- {
- throw new IOException("object not DEREncodable");
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * DER PrintableString object.
- */
-public class DERPrintableString
- extends DERObject
- implements DERString
-{
- String string;
-
- /**
- * return a printable string from the passed in object.
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERPrintableString getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERPrintableString)
- {
- return (DERPrintableString)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERPrintableString(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return a Printable String from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERPrintableString getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * basic constructor - byte encoded string.
- */
- public DERPrintableString(
- byte[] string)
- {
- char[] cs = new char[string.length];
-
- for (int i = 0; i != cs.length; i++)
- {
- cs[i] = (char)(string[i] & 0xff);
- }
-
- this.string = new String(cs);
- }
-
- /**
- * basic constructor
- */
- public DERPrintableString(
- String string)
- {
- this.string = string;
- }
-
- public String getString()
- {
- return string;
- }
-
- public byte[] getOctets()
- {
- char[] cs = string.toCharArray();
- byte[] bs = new byte[cs.length];
-
- for (int i = 0; i != cs.length; i++)
- {
- bs[i] = (byte)cs[i];
- }
-
- return bs;
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(PRINTABLE_STRING, this.getOctets());
- }
-
- public int hashCode()
- {
- return this.getString().hashCode();
- }
-
- public boolean equals(
- Object o)
- {
- if (!(o instanceof DERPrintableString))
- {
- return false;
- }
-
- DERPrintableString s = (DERPrintableString)o;
-
- return this.getString().equals(s.getString());
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-public class DERSequence
- extends ASN1Sequence
-{
- /**
- * create an empty sequence
- */
- public DERSequence()
- {
- }
-
- /**
- * create a sequence containing one object
- */
- public DERSequence(
- DEREncodable obj)
- {
- this.addObject(obj);
- }
-
- /**
- * create a sequence containing a vector of objects.
- */
- public DERSequence(
- DEREncodableVector v)
- {
- for (int i = 0; i != v.size(); i++)
- {
- this.addObject(v.get(i));
- }
- }
-
- /*
- * A note on the implementation:
- * <p>
- * As DER requires the constructed, definite-length model to
- * be used for structured types, this varies slightly from the
- * ASN.1 descriptions given. Rather than just outputing SEQUENCE,
- * we also have to specify CONSTRUCTED, and the objects length.
- */
- void encode(
- DEROutputStream out)
- throws IOException
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
- Enumeration e = this.getObjects();
-
- while (e.hasMoreElements())
- {
- Object obj = e.nextElement();
-
- dOut.writeObject(obj);
- }
-
- dOut.close();
-
- byte[] bytes = bOut.toByteArray();
-
- out.writeEncoded(SEQUENCE | CONSTRUCTED, bytes);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-import java.util.*;
-
-/**
- * A DER encoded set object
- */
-public class DERSet
- extends ASN1Set
-{
- /**
- * create an empty set
- */
- public DERSet()
- {
- }
-
- /**
- * @param obj - a single object that makes up the set.
- */
- public DERSet(
- DEREncodable obj)
- {
- this.addObject(obj);
- }
-
- /**
- * @param v - a vector of objects making up the set.
- */
- public DERSet(
- DEREncodableVector v)
- {
- for (int i = 0; i != v.size(); i++)
- {
- this.addObject(v.get(i));
- }
- }
-
- /*
- * A note on the implementation:
- * <p>
- * As DER requires the constructed, definite-length model to
- * be used for structured types, this varies slightly from the
- * ASN.1 descriptions given. Rather than just outputing SET,
- * we also have to specify CONSTRUCTED, and the objects length.
- */
- void encode(
- DEROutputStream out)
- throws IOException
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
- Enumeration e = this.getObjects();
-
- while (e.hasMoreElements())
- {
- Object obj = e.nextElement();
-
- dOut.writeObject(obj);
- }
-
- dOut.close();
-
- byte[] bytes = bOut.toByteArray();
-
- out.writeEncoded(SET | CONSTRUCTED, bytes);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-/**
- * basic interface for DER string objects.
- */
-public interface DERString
-{
- public String getString();
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * DER T61String (also the teletex string)
- */
-public class DERT61String
- extends DERObject
- implements DERString
-{
- String string;
-
- /**
- * return a T61 string from the passed in object.
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERT61String getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERT61String)
- {
- return (DERT61String)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERT61String(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return an T61 String from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERT61String getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * basic constructor - with bytes.
- */
- public DERT61String(
- byte[] string)
- {
- this.string = new String(string);
- }
-
- /**
- * basic constructor - with string.
- */
- public DERT61String(
- String string)
- {
- this.string = string;
- }
-
- public String getString()
- {
- return string;
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(T61_STRING, string.getBytes());
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof DERT61String))
- {
- return false;
- }
-
- return this.getString().equals(((DERT61String)o).getString());
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * DER TaggedObject - in ASN.1 nottation this is any object proceeded by
- * a [n] where n is some number - these are assume to follow the construction
- * rules (as with sequences).
- */
-public class DERTaggedObject
- extends ASN1TaggedObject
-{
- /**
- * @param tagNo the tag number for this object.
- * @param obj the tagged object.
- */
- public DERTaggedObject(
- int tagNo,
- DEREncodable obj)
- {
- super(tagNo, obj);
- }
-
- /**
- * @param explicit true if an explicitly tagged object.
- * @param tagNo the tag number for this object.
- * @param obj the tagged object.
- */
- public DERTaggedObject(
- boolean explicit,
- int tagNo,
- DEREncodable obj)
- {
- super(explicit, tagNo, obj);
- }
-
- /**
- * create an implicitly tagged object that contains a zero
- * length sequence.
- */
- public DERTaggedObject(
- int tagNo)
- {
- super(false, tagNo, new DERSequence());
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- if (!empty)
- {
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
-
- dOut.writeObject(obj);
- dOut.close();
-
- byte[] bytes = bOut.toByteArray();
-
- if (explicit)
- {
- out.writeEncoded(CONSTRUCTED | TAGGED | tagNo, bytes);
- }
- else
- {
- //
- // need to mark constructed types...
- //
- if ((bytes[0] & CONSTRUCTED) != 0)
- {
- bytes[0] = (byte)(CONSTRUCTED | TAGGED | tagNo);
- }
- else
- {
- bytes[0] = (byte)(TAGGED | tagNo);
- }
-
- out.write(bytes);
- }
- }
- else
- {
- out.writeEncoded(CONSTRUCTED | TAGGED | tagNo, new byte[0]);
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-public interface DERTags
-{
- public static final int BOOLEAN = 0x01;
- public static final int INTEGER = 0x02;
- public static final int BIT_STRING = 0x03;
- public static final int OCTET_STRING = 0x04;
- public static final int NULL = 0x05;
- public static final int OBJECT_IDENTIFIER = 0x06;
- public static final int EXTERNAL = 0x08;
- public static final int ENUMERATED = 0x0a;
- public static final int SEQUENCE = 0x10;
- public static final int SEQUENCE_OF = 0x10; // for completeness
- public static final int SET = 0x11;
- public static final int SET_OF = 0x11; // for completeness
- public static final int CONSTRUCTED = 0x20;
- public static final int TAGGED = 0x80;
-
- public static final int NUMERIC_STRING = 0x12;
- public static final int PRINTABLE_STRING = 0x13;
- public static final int T61_STRING = 0x14;
- public static final int VIDEOTEX_STRING = 0x15;
- public static final int IA5_STRING = 0x16;
- public static final int UTC_TIME = 0x17;
- public static final int GENERALIZED_TIME = 0x18;
- public static final int GRAPHIC_STRING = 0x19;
- public static final int VISIBLE_STRING = 0x1a;
- public static final int GENERAL_STRING = 0x1b;
- public static final int UNIVERSAL_STRING = 0x1c;
- public static final int BMP_STRING = 0x1e;
- public static final int UTF8_STRING = 0x0c;
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.util.*;
-import java.io.*;
-import java.text.*;
-
-/**
- * UTC time object.
- */
-public class DERUTCTime
- extends DERObject
-{
- String time;
-
- /**
- * return an UTC Time from the passed in object.
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERUTCTime getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERUTCTime)
- {
- return (DERUTCTime)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERUTCTime(((ASN1OctetString)obj).getOctets());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return an UTC Time from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERUTCTime getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * The correct format for this is YYMMDDHHMMSSZ (it used to be that seconds were
- * never encoded. When you're creating one of these objects from scratch, that's
- * what you want to use, otherwise we'll try to deal with whatever gets read from
- * the input stream... (this is why the input format is different from the getTime()
- * method output).
- * <p>
- *
- * @param time the time string.
- */
- public DERUTCTime(
- String time)
- {
- this.time = time;
- }
-
- /**
- * base constructer from a java.util.date object
- */
- public DERUTCTime(
- Date time)
- {
- SimpleDateFormat dateF = new SimpleDateFormat("yyMMddHHmmss'Z'");
-
- dateF.setTimeZone(new SimpleTimeZone(0,"Z"));
-
- this.time = dateF.format(time);
- }
-
- DERUTCTime(
- byte[] bytes)
- {
- //
- // explicitly convert to characters
- //
- char[] dateC = new char[bytes.length];
-
- for (int i = 0; i != dateC.length; i++)
- {
- dateC[i] = (char)(bytes[i] & 0xff);
- }
-
- this.time = new String(dateC);
- }
-
- /**
- * return the time - always in the form of
- * YYMMDDhhmmssGMT(+hh:mm|-hh:mm).
- * <p>
- * Normally in a certificate we would expect "Z" rather than "GMT",
- * however adding the "GMT" means we can just use:
- * <pre>
- * dateF = new SimpleDateFormat("yyMMddHHmmssz");
- * </pre>
- * To read in the time and get a date which is compatible with our local
- * time zone.
- * <p>
- * <b>Note:</b> In some cases, due to the local date processing, this
- * may lead to unexpected results. If you want to stick the normal
- * convention of 1950 to 2049 use the getAdjustedTime() method.
- */
- public String getTime()
- {
- //
- // standardise the format.
- //
- if (time.length() == 11)
- {
- return time.substring(0, 10) + "00GMT+00:00";
- }
- else if (time.length() == 13)
- {
- return time.substring(0, 12) + "GMT+00:00";
- }
- else if (time.length() == 17)
- {
- return time.substring(0, 12) + "GMT" + time.substring(12, 15) + ":" + time.substring(15, 17);
- }
-
- return time;
- }
-
- /**
- * return the time as an adjusted date with a 4 digit year. This goes
- * in the range of 1950 - 2049.
- */
- public String getAdjustedTime()
- {
- String d = this.getTime();
-
- if (d.charAt(0) < '5')
- {
- return "20" + d;
- }
- else
- {
- return "19" + d;
- }
- }
-
- private byte[] getOctets()
- {
- char[] cs = time.toCharArray();
- byte[] bs = new byte[cs.length];
-
- for (int i = 0; i != cs.length; i++)
- {
- bs[i] = (byte)cs[i];
- }
-
- return bs;
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(UTC_TIME, this.getOctets());
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof DERUTCTime))
- {
- return false;
- }
-
- return time.equals(((DERUTCTime)o).time);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * DER UTF8String object.
- */
-public class DERUTF8String
- extends DERObject
- implements DERString
-{
- String string;
-
- /**
- * return an UTF8 string from the passed in object.
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERUTF8String getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERUTF8String)
- {
- return (DERUTF8String)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERUTF8String(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return an UTF8 String from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERUTF8String getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * basic constructor - byte encoded string.
- */
- DERUTF8String(
- byte[] string)
- {
- int i = 0;
- int length = 0;
-
- while (i < string.length)
- {
- length++;
- if ((string[i] & 0xe0) == 0xe0)
- {
- i += 3;
- }
- else if ((string[i] & 0xc0) == 0xc0)
- {
- i += 2;
- }
- else
- {
- i += 1;
- }
- }
-
- char[] cs = new char[length];
-
- i = 0;
- length = 0;
-
- while (i < string.length)
- {
- char ch;
-
- if ((string[i] & 0xe0) == 0xe0)
- {
- ch = (char)(((string[i] & 0x1f) << 12)
- | ((string[i + 1] & 0x3f) << 6) | (string[i + 2] & 0x3f));
- i += 3;
- }
- else if ((string[i] & 0xc0) == 0xc0)
- {
- ch = (char)(((string[i] & 0x3f) << 6) | (string[i + 1] & 0x3f));
- i += 2;
- }
- else
- {
- ch = (char)(string[i] & 0xff);
- i += 1;
- }
-
- cs[length++] = ch;
- }
-
- this.string = new String(cs);
- }
-
- /**
- * basic constructor
- */
- public DERUTF8String(
- String string)
- {
- this.string = string;
- }
-
- public String getString()
- {
- return string;
- }
-
- public int hashCode()
- {
- return this.getString().hashCode();
- }
-
- public boolean equals(
- Object o)
- {
- if (!(o instanceof DERUTF8String))
- {
- return false;
- }
-
- DERUTF8String s = (DERUTF8String)o;
-
- return this.getString().equals(s.getString());
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- char[] c = string.toCharArray();
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
-
- for (int i = 0; i != c.length; i++)
- {
- char ch = c[i];
-
- if (ch < 0x0080)
- {
- bOut.write(ch);
- }
- else if (ch < 0x0800)
- {
- bOut.write(0xc0 | (ch >> 6));
- bOut.write(0x80 | (ch & 0x3f));
- }
- else
- {
- bOut.write(0xe0 | (ch >> 12));
- bOut.write(0x80 | ((ch >> 6) & 0x3F));
- bOut.write(0x80 | (ch & 0x3F));
- }
- }
-
- out.writeEncoded(UTF8_STRING, bOut.toByteArray());
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * DER UniversalString object.
- */
-public class DERUniversalString
- extends DERObject
- implements DERString
-{
- byte[] string;
- char[] table = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
-
- /**
- * return a Universal String from the passed in object.
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERUniversalString getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERUniversalString)
- {
- return (DERUniversalString)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERUniversalString(((ASN1OctetString)obj).getOctets());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return a Universal String from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERUniversalString getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * basic constructor - byte encoded string.
- */
- public DERUniversalString(
- byte[] string)
- {
- this.string = string;
- }
-
- /**
- * UniversalStrings have characters which are 4 bytes long - for the
- * moment we just return them in Hex...
- */
- public String getString()
- {
- StringBuffer buf = new StringBuffer();
-
- for (int i = 0; i != string.length; i++)
- {
- buf.append(table[(string[i] >>> 4) % 0xf]);
- buf.append(table[string[i] & 0xf]);
- }
-
- return buf.toString();
- }
-
- public byte[] getOctets()
- {
- return string;
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(UNIVERSAL_STRING, this.getOctets());
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof DERUniversalString))
- {
- return false;
- }
-
- return this.getString().equals(((DERUniversalString)o).getString());
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * We insert one of these when we find a tag we don't recognise.
- */
-public class DERUnknownTag
- extends DERObject
-{
- int tag;
- byte[] data;
-
- /**
- * @param tag the tag value.
- * @param data the octets making up the time.
- */
- public DERUnknownTag(
- int tag,
- byte[] data)
- {
- this.tag = tag;
- this.data = data;
- }
-
- public int getTag()
- {
- return tag;
- }
-
- public byte[] getData()
- {
- return data;
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(tag, data);
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof DERUnknownTag))
- {
- return false;
- }
-
- DERUnknownTag other = (DERUnknownTag)o;
-
- if(tag != other.tag)
- {
- return false;
- }
-
- if(data.length != other.data.length)
- {
- return false;
- }
-
- for(int i = 0; i < data.length; i++)
- {
- if(data[i] != other.data[i])
- {
- return false;
- }
- }
-
- return true;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-import java.io.*;
-
-/**
- * DER VisibleString object.
- */
-public class DERVisibleString
- extends DERObject
- implements DERString
-{
- String string;
-
- /**
- * return a Visible String from the passed in object.
- *
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static DERVisibleString getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof DERVisibleString)
- {
- return (DERVisibleString)obj;
- }
-
- if (obj instanceof ASN1OctetString)
- {
- return new DERVisibleString(((ASN1OctetString)obj).getOctets());
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * return a Visible String from a tagged object.
- *
- * @param obj the tagged object holding the object we want
- * @param explicit true if the object is meant to be explicitly
- * tagged false otherwise.
- * @exception IllegalArgumentException if the tagged object cannot
- * be converted.
- */
- public static DERVisibleString getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- /**
- * basic constructor - byte encoded string.
- */
- public DERVisibleString(
- byte[] string)
- {
- char[] cs = new char[string.length];
-
- for (int i = 0; i != cs.length; i++)
- {
- cs[i] = (char)(string[i] & 0xff);
- }
-
- this.string = new String(cs);
- }
-
- /**
- * basic constructor
- */
- public DERVisibleString(
- String string)
- {
- this.string = string;
- }
-
- public String getString()
- {
- return string;
- }
-
- public byte[] getOctets()
- {
- char[] cs = string.toCharArray();
- byte[] bs = new byte[cs.length];
-
- for (int i = 0; i != cs.length; i++)
- {
- bs[i] = (byte)cs[i];
- }
-
- return bs;
- }
-
- void encode(
- DEROutputStream out)
- throws IOException
- {
- out.writeEncoded(VISIBLE_STRING, this.getOctets());
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof DERVisibleString))
- {
- return false;
- }
-
- return this.getString().equals(((DERVisibleString)o).getString());
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1;
-
-/**
- * class for breaking up an OID into it's component tokens, ala
- * java.util.StringTokenizer. We need this class as some of the
- * lightweight Java environment don't support classes like
- * StringTokenizer.
- */
-public class OIDTokenizer
-{
- private String oid;
- private int index;
-
- public OIDTokenizer(
- String oid)
- {
- this.oid = oid;
- this.index = 0;
- }
-
- public boolean hasMoreTokens()
- {
- return (index != -1);
- }
-
- public String nextToken()
- {
- if (index == -1)
- {
- return null;
- }
-
- String token;
- int end = oid.indexOf('.', index);
-
- if (end == -1)
- {
- token = oid.substring(index);
- index = -1;
- return token;
- }
-
- token = oid.substring(index, end);
-
- index = end + 1;
- return token;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.cms;
-
-import org.bouncycastle.asn1.*;
-
-public class Attribute
- implements DEREncodable
-{
- private DERObjectIdentifier attrType;
- private ASN1Set attrValues;
-
- /**
- * return an Attribute object from the given object.
- *
- * @param o the object we want converted.
- * @exception IllegalArgumentException if the object cannot be converted.
- */
- public static Attribute getInstance(
- Object o)
- {
- if (o == null || o instanceof Attribute)
- {
- return (Attribute)o;
- }
-
- if (o instanceof ASN1Sequence)
- {
- return new Attribute((ASN1Sequence)o);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public Attribute(
- ASN1Sequence seq)
- {
- attrType = (DERObjectIdentifier)seq.getObjectAt(0);
- attrValues = (ASN1Set)seq.getObjectAt(1);
- }
-
- public Attribute(
- DERObjectIdentifier attrType,
- ASN1Set attrValues)
- {
- this.attrType = attrType;
- this.attrValues = attrValues;
- }
-
- public DERObjectIdentifier getAttrType()
- {
- return attrType;
- }
-
- public ASN1Set getAttrValues()
- {
- return attrValues;
- }
-
- /**
- * <pre>
- * Attribute ::= SEQUENCE {
- * attrType OBJECT IDENTIFIER,
- * attrValues SET OF AttributeValue
- * }
- * </pre>
- */
- public DERObject getDERObject()
- {
- DEREncodableVector v = new DEREncodableVector();
-
- v.add(attrType);
- v.add(attrValues);
-
- return new DERSequence(v);
- }
-}
+++ /dev/null
-// Decompiled by Jad v1.5.7f. Copyright 2000 Pavel Kouznetsov.
-// Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html
-// Decompiler options: packimports(3)
-// Source File Name: SignedAttributes.java
-
-package org.bouncycastle.asn1.cms;
-
-import java.util.Vector;
-import org.bouncycastle.asn1.*;
-
-// Referenced classes of package org.bouncycastle.asn1.cms:
-// Attribute
-
-public class SignedAttributes
- implements DEREncodable
-{
-
- public SignedAttributes(Vector vector)
- {
- setAttributes(vector);
- }
-
- public SignedAttributes(DERConstructedSet derconstructedset)
- {
- attributes = derconstructedset;
- }
-
- public SignedAttributes(SignedAttributes signedattributes)
- {
- attributes = signedattributes.attributes;
- }
-
- public static SignedAttributes getInstance(Object obj)
- {
- if(obj == null)
- return null;
- if(obj instanceof SignedAttributes)
- return (SignedAttributes)obj;
- if(obj instanceof DERConstructedSet)
- return new SignedAttributes((DERConstructedSet)obj);
- if(obj instanceof DERTaggedObject)
- return getInstance(((DERTaggedObject)obj).getObject());
- else
- throw new IllegalArgumentException("Invalid SignedAttributes");
- }
-
- public static SignedAttributes newInstance(Object obj)
- {
- if(obj == null)
- return null;
- if(obj instanceof SignedAttributes)
- return new SignedAttributes((SignedAttributes)obj);
- if(obj instanceof DERConstructedSet)
- return new SignedAttributes((DERConstructedSet)obj);
- if(obj instanceof DERTaggedObject)
- return getInstance(((DERTaggedObject)obj).getObject());
- else
- throw new IllegalArgumentException("Invalid SignedAttributes");
- }
-
- public Vector getAttributes()
- {
- int i = attributes.getSize();
- Vector vector = new Vector();
- for(int j = 0; j < i; j++)
- vector.addElement(Attribute.getInstance(attributes.getObjectAt(j)));
-
- return vector;
- }
-
- private void setAttributes(Vector vector)
- {
- int i = vector.size();
- attributes = new DERConstructedSet();
- for(int j = 0; j < i; j++)
- attributes.addObject(Attribute.getInstance(vector.elementAt(j)));
-
- }
-
- public DERObject getDERObject()
- {
- return attributes;
- }
-
- private DERConstructedSet attributes;
-}
+++ /dev/null
-package org.bouncycastle.asn1.pkcs;
-
-import org.bouncycastle.asn1.DERObjectIdentifier;
-
-public interface PKCSObjectIdentifiers
-{
- //
- // pkcs-1 OBJECT IDENTIFIER ::= {
- // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
- //
- static final String pkcs_1 = "1.2.840.113549.1.1";
- static final DERObjectIdentifier rsaEncryption = new DERObjectIdentifier(pkcs_1 + ".1");
- static final DERObjectIdentifier md2WithRSAEncryption = new DERObjectIdentifier(pkcs_1 + ".2");
- static final DERObjectIdentifier md4WithRSAEncryption = new DERObjectIdentifier(pkcs_1 + ".3");
- static final DERObjectIdentifier md5WithRSAEncryption = new DERObjectIdentifier(pkcs_1 + ".4");
- static final DERObjectIdentifier sha1WithRSAEncryption = new DERObjectIdentifier(pkcs_1 + ".5");
- static final DERObjectIdentifier srsaOAEPEncryptionSET = new DERObjectIdentifier(pkcs_1 + ".6");
- static final DERObjectIdentifier sha256WithRSAEncryption = new DERObjectIdentifier(pkcs_1 + ".11");
- static final DERObjectIdentifier sha384WithRSAEncryption = new DERObjectIdentifier(pkcs_1 + ".12");
- static final DERObjectIdentifier sha512WithRSAEncryption = new DERObjectIdentifier(pkcs_1 + ".13");
-
- //
- // pkcs-3 OBJECT IDENTIFIER ::= {
- // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 3 }
- //
- static final String pkcs_3 = "1.2.840.113549.1.3";
- static final DERObjectIdentifier dhKeyAgreement = new DERObjectIdentifier(pkcs_3 + ".1");
-
- //
- // pkcs-5 OBJECT IDENTIFIER ::= {
- // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 }
- //
- static final String pkcs_5 = "1.2.840.113549.1.5";
-
- static final DERObjectIdentifier id_PBES2 = new DERObjectIdentifier(pkcs_5 + ".13");
-
- static final DERObjectIdentifier id_PBKDF2 = new DERObjectIdentifier(pkcs_5 + ".12");
-
- //
- // encryptionAlgorithm OBJECT IDENTIFIER ::= {
- // iso(1) member-body(2) us(840) rsadsi(113549) 3 }
- //
- static final String encryptionAlgorithm = "1.2.840.113549.3";
-
- static final DERObjectIdentifier des_EDE3_CBC = new DERObjectIdentifier(encryptionAlgorithm + ".7");
- static final DERObjectIdentifier RC2_CBC = new DERObjectIdentifier(encryptionAlgorithm + ".2");
-
- //
- // object identifiers for digests
- //
-
- //
- // md2 OBJECT IDENTIFIER ::=
- // {iso(1) member-body(2) US(840) rsadsi(113549) digestAlgorithm(2) 2}
- //
- static final DERObjectIdentifier md2 = new DERObjectIdentifier("1.2.840.113549.2.2");
-
- //
- // md5 OBJECT IDENTIFIER ::=
- // {iso(1) member-body(2) US(840) rsadsi(113549) digestAlgorithm(2) 5}
- //
- static final DERObjectIdentifier md5 = new DERObjectIdentifier("1.2.840.113549.2.5");
-
- //
- // pkcs-7 OBJECT IDENTIFIER ::= {
- // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 7 }
- //
- static final String pkcs_7 = "1.2.840.113549.1.7";
- static final DERObjectIdentifier data = new DERObjectIdentifier(pkcs_7 + ".1");
- static final DERObjectIdentifier signedData = new DERObjectIdentifier(pkcs_7 + ".2");
- static final DERObjectIdentifier envelopedData = new DERObjectIdentifier(pkcs_7 + ".3");
- static final DERObjectIdentifier signedAndEnvelopedData = new DERObjectIdentifier(pkcs_7 + ".4");
- static final DERObjectIdentifier digestedData = new DERObjectIdentifier(pkcs_7 + ".5");
- static final DERObjectIdentifier encryptedData = new DERObjectIdentifier(pkcs_7 + ".6");
-
- //
- // pkcs-9 OBJECT IDENTIFIER ::= {
- // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 }
- //
- static final String pkcs_9 = "1.2.840.113549.1.9";
-
- static final DERObjectIdentifier pkcs_9_at_emailAddress = new DERObjectIdentifier(pkcs_9 + ".1");
- static final DERObjectIdentifier pkcs_9_at_unstructuredName = new DERObjectIdentifier(pkcs_9 + ".2");
- static final DERObjectIdentifier pkcs_9_at_contentType = new DERObjectIdentifier(pkcs_9 + ".3");
- static final DERObjectIdentifier pkcs_9_at_messageDigest = new DERObjectIdentifier(pkcs_9 + ".4");
- static final DERObjectIdentifier pkcs_9_at_signingTime = new DERObjectIdentifier(pkcs_9 + ".5");
- static final DERObjectIdentifier pkcs_9_at_counterSignature = new DERObjectIdentifier(pkcs_9 + ".6");
- static final DERObjectIdentifier pkcs_9_at_challengePassword = new DERObjectIdentifier(pkcs_9 + ".7");
- static final DERObjectIdentifier pkcs_9_at_unstructuredAddress = new DERObjectIdentifier(pkcs_9 + ".8");
- static final DERObjectIdentifier pkcs_9_at_extendedCertificateAttributes = new DERObjectIdentifier(pkcs_9 + ".9");
-
- static final DERObjectIdentifier pkcs_9_at_signingDescription = new DERObjectIdentifier(pkcs_9 + ".13");
- static final DERObjectIdentifier pkcs_9_at_extensionRequest = new DERObjectIdentifier(pkcs_9 + ".14");
- static final DERObjectIdentifier pkcs_9_at_smimeCapabilities = new DERObjectIdentifier(pkcs_9 + ".15");
-
- static final DERObjectIdentifier pkcs_9_at_friendlyName = new DERObjectIdentifier(pkcs_9 + ".20");
- static final DERObjectIdentifier pkcs_9_at_localKeyId = new DERObjectIdentifier(pkcs_9 + ".21");
-
- static final DERObjectIdentifier x509certType = new DERObjectIdentifier(pkcs_9 + ".22.1");
-
- //
- // SMIME capability sub oids.
- //
- static final DERObjectIdentifier preferSignedData = new DERObjectIdentifier(pkcs_9 + ".15.1");
- static final DERObjectIdentifier canNotDecryptAny = new DERObjectIdentifier(pkcs_9 + ".15.2");
- static final DERObjectIdentifier sMIMECapabilitiesVersions = new DERObjectIdentifier(pkcs_9 + ".15.3");
-
- //
- // other SMIME attributes
- //
-
- //
- // id-aa OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840)
- // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) attributes(2)}
- //
- static String id_aa = "1.2.840.113549.1.9.16.2";
-
- /*
- * id-aa-encrypKeyPref OBJECT IDENTIFIER ::= {id-aa 11}
- *
- */
- static DERObjectIdentifier id_aa_encrypKeyPref = new DERObjectIdentifier(id_aa + ".11");
-
- //
- // pkcs-12 OBJECT IDENTIFIER ::= {
- // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 }
- //
- static final String pkcs_12 = "1.2.840.113549.1.12";
- static final String bagtypes = pkcs_12 + ".10.1";
-
- static final DERObjectIdentifier keyBag = new DERObjectIdentifier(bagtypes + ".1");
- static final DERObjectIdentifier pkcs8ShroudedKeyBag = new DERObjectIdentifier(bagtypes + ".2");
- static final DERObjectIdentifier certBag = new DERObjectIdentifier(bagtypes + ".3");
- static final DERObjectIdentifier crlBag = new DERObjectIdentifier(bagtypes + ".4");
- static final DERObjectIdentifier secretBag = new DERObjectIdentifier(bagtypes + ".5");
- static final DERObjectIdentifier safeContentsBag = new DERObjectIdentifier(bagtypes + ".6");
-}
-
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.io.*;
-
-import org.bouncycastle.asn1.*;
-
-public class AlgorithmIdentifier
- implements DEREncodable
-{
- private DERObjectIdentifier objectId;
- private DEREncodable parameters;
- private boolean parametersDefined = false;
-
- public static AlgorithmIdentifier getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static AlgorithmIdentifier getInstance(
- Object obj)
- {
- if (obj instanceof AlgorithmIdentifier)
- {
- return (AlgorithmIdentifier)obj;
- }
-
- if (obj instanceof DERObjectIdentifier)
- {
- return new AlgorithmIdentifier((DERObjectIdentifier)obj);
- }
-
- if (obj instanceof String)
- {
- return new AlgorithmIdentifier((String)obj);
- }
-
- if (obj instanceof ASN1Sequence)
- {
- return new AlgorithmIdentifier((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public AlgorithmIdentifier(
- DERObjectIdentifier objectId)
- {
- this.objectId = objectId;
- }
-
- public AlgorithmIdentifier(
- String objectId)
- {
- this.objectId = new DERObjectIdentifier(objectId);
- }
-
- public AlgorithmIdentifier(
- DERObjectIdentifier objectId,
- DEREncodable parameters)
- {
- parametersDefined = true;
- this.objectId = objectId;
- this.parameters = parameters;
- }
-
- public AlgorithmIdentifier(
- ASN1Sequence seq)
- {
- objectId = (DERObjectIdentifier)seq.getObjectAt(0);
-
- if (seq.size() == 2)
- {
- parametersDefined = true;
- parameters = seq.getObjectAt(1);
- }
- else
- {
- parameters = null;
- }
- }
-
- public DERObjectIdentifier getObjectId()
- {
- return objectId;
- }
-
- public DEREncodable getParameters()
- {
- return parameters;
- }
-
- /**
- * <pre>
- * AlgorithmIdentifier ::= SEQUENCE {
- * algorithm OBJECT IDENTIFIER,
- * parameters ANY DEFINED BY algorithm OPTIONAL }
- * </pre>
- */
- public DERObject getDERObject()
- {
- DERConstructedSequence seq = new DERConstructedSequence();
-
- seq.addObject(objectId);
-
- if (parametersDefined)
- {
- seq.addObject(parameters);
- }
-
- return seq;
- }
-
- public boolean equals(
- Object o)
- {
- if ((o == null) || !(o instanceof AlgorithmIdentifier))
- {
- return false;
- }
-
- AlgorithmIdentifier other = (AlgorithmIdentifier)o;
-
- if (!this.getObjectId().equals(other.getObjectId()))
- {
- return false;
- }
-
- if (this.getParameters() == null && other.getParameters() == null)
- {
- return true;
- }
-
- if (this.getParameters() == null || other.getParameters() == null)
- {
- return false;
- }
-
- ByteArrayOutputStream b1Out = new ByteArrayOutputStream();
- ByteArrayOutputStream b2Out = new ByteArrayOutputStream();
- DEROutputStream d1Out = new DEROutputStream(b1Out);
- DEROutputStream d2Out = new DEROutputStream(b2Out);
-
- try
- {
- d1Out.writeObject(this.getParameters());
- d2Out.writeObject(other.getParameters());
-
- byte[] b1 = b1Out.toByteArray();
- byte[] b2 = b2Out.toByteArray();
-
- if (b1.length != b2.length)
- {
- return false;
- }
-
- for (int i = 0; i != b1.length; i++)
- {
- if (b1[i] != b2[i])
- {
- return false;
- }
- }
- }
- catch (Exception e)
- {
- return false;
- }
-
- return true;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.math.BigInteger;
-
-import java.util.Enumeration;
-
-import org.bouncycastle.crypto.Digest;
-import org.bouncycastle.crypto.digests.SHA1Digest;
-import org.bouncycastle.asn1.*;
-
-/**
- * <pre>
- * id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 }
- *
- * AuthorityKeyIdentifier ::= SEQUENCE {
- * keyIdentifier [0] IMPLICIT KeyIdentifier OPTIONAL,
- * authorityCertIssuer [1] IMPLICIT GeneralNames OPTIONAL,
- * authorityCertSerialNumber [2] IMPLICIT CertificateSerialNumber OPTIONAL }
- *
- * KeyIdentifier ::= OCTET STRING
- * </pre>
- *
- */
-public class AuthorityKeyIdentifier
- implements DEREncodable, DERTags
-{
- ASN1OctetString keyidentifier=null;
- GeneralNames certissuer=null;
- DERInteger certserno=null;
-
- public static AuthorityKeyIdentifier getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static AuthorityKeyIdentifier getInstance(
- Object obj)
- {
- if (obj instanceof AuthorityKeyIdentifier)
- {
- return (AuthorityKeyIdentifier)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new AuthorityKeyIdentifier((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public AuthorityKeyIdentifier(
- ASN1Sequence seq)
- {
- Enumeration e = seq.getObjects();
-
- while (e.hasMoreElements())
- {
- DERTaggedObject o = (DERTaggedObject)e.nextElement();
-
- switch (o.getTagNo())
- {
- case 0:
- this.keyidentifier = ASN1OctetString.getInstance(o, false);
- break;
- case 1:
- this.certissuer = GeneralNames.getInstance(o, false);
- break;
- case 2:
- this.certserno = DERInteger.getInstance(o, false);
- break;
- default:
- throw new IllegalArgumentException("illegal tag");
- }
- }
- }
-
- /**
- *
- * Calulates the keyidentifier using a SHA1 hash over the BIT STRING
- * from SubjectPublicKeyInfo as defined in RFC2459.
- *
- * Example of making a AuthorityKeyIdentifier:
- * <pre>
- * SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((DERConstructedSequence)new DERInputStream(
- * new ByteArrayInputStream(publicKey.getEncoded())).readObject());
- * AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
- * </pre>
- *
- **/
- public AuthorityKeyIdentifier(
- SubjectPublicKeyInfo spki)
- {
- Digest digest = new SHA1Digest();
- byte[] resBuf = new byte[digest.getDigestSize()];
-
- byte[] bytes = spki.getPublicKeyData().getBytes();
- digest.update(bytes, 0, bytes.length);
- digest.doFinal(resBuf, 0);
- this.keyidentifier = new DEROctetString(resBuf);
- }
-
- /**
- * create an AuthorityKeyIdentifier with the GeneralNames tag and
- * the serial number provided as well.
- */
- public AuthorityKeyIdentifier(
- SubjectPublicKeyInfo spki,
- GeneralNames name,
- BigInteger serialNumber)
- {
- Digest digest = new SHA1Digest();
- byte[] resBuf = new byte[digest.getDigestSize()];
-
- byte[] bytes = spki.getPublicKeyData().getBytes();
- digest.update(bytes, 0, bytes.length);
- digest.doFinal(resBuf, 0);
-
- this.keyidentifier = new DEROctetString(resBuf);
- this.certissuer = name;
- this.certserno = new DERInteger(serialNumber);
- }
-
- public byte[] getKeyIdentifier()
- {
- if (keyidentifier != null)
- {
- return keyidentifier.getOctets();
- }
-
- return null;
- }
-
- /**
- * <pre>
- * AuthorityKeyIdentifier ::= SEQUENCE {
- * keyIdentifier [0] IMPLICIT KeyIdentifier OPTIONAL,
- * authorityCertIssuer [1] IMPLICIT GeneralNames OPTIONAL,
- * authorityCertSerialNumber [2] IMPLICIT CertificateSerialNumber OPTIONAL }
- *
- * KeyIdentifier ::= OCTET STRING
- * </pre>
- */
- public DERObject getDERObject()
- {
- DERConstructedSequence seq = new DERConstructedSequence();
-
- if (keyidentifier != null)
- {
- seq.addObject(new DERTaggedObject(false, 0, keyidentifier));
- }
-
- if (certissuer != null)
- {
- seq.addObject(new DERTaggedObject(false, 1, certissuer));
- }
-
- if (certserno != null)
- {
- seq.addObject(new DERTaggedObject(false, 2, certserno));
- }
-
-
- return seq;
- }
-
- public String toString()
- {
- return ("AuthorityKeyIdentifier: KeyID(" + this.keyidentifier.getOctets() + ")");
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.math.BigInteger;
-
-import org.bouncycastle.asn1.*;
-
-public class BasicConstraints
- implements DEREncodable
-{
- DERBoolean cA = new DERBoolean(false);
- DERInteger pathLenConstraint = null;
-
- public static BasicConstraints getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static BasicConstraints getInstance(
- Object obj)
- {
- if (obj instanceof BasicConstraints)
- {
- return (BasicConstraints)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new BasicConstraints((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public BasicConstraints(
- ASN1Sequence seq)
- {
- if (seq.size() != 0)
- {
- this.cA = (DERBoolean)seq.getObjectAt(0);
- this.pathLenConstraint = (DERInteger)seq.getObjectAt(1);
- }
- }
-
- public BasicConstraints(
- boolean cA,
- int pathLenConstraint)
- {
- this.cA = new DERBoolean(cA);
- this.pathLenConstraint = new DERInteger(pathLenConstraint);
- }
-
- public BasicConstraints(
- boolean cA)
- {
- this.cA = new DERBoolean(cA);
- this.pathLenConstraint = null;
- }
-
- public boolean isCA()
- {
- return cA.isTrue();
- }
-
- public BigInteger getPathLenConstraint()
- {
- if (pathLenConstraint != null)
- {
- return pathLenConstraint.getValue();
- }
-
- return null;
- }
-
- /**
- * <pre>
- * BasicConstraints := SEQUENCE {
- * cA BOOLEAN DEFAULT FALSE,
- * pathLenConstraint INTEGER (0..MAX) OPTIONAL
- * }
- * </pre>
- */
- public DERObject getDERObject()
- {
- DERConstructedSequence seq = new DERConstructedSequence();
-
- seq.addObject(cA);
-
- if (pathLenConstraint != null)
- {
- seq.addObject(pathLenConstraint);
- }
-
- return seq;
- }
-
- public String toString()
- {
- return "BasicConstraints: isCa(" + this.isCA() + "), pathLenConstraint = " + pathLenConstraint.getValue();
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-public class CRLDistPoint
- implements DEREncodable
-{
- ASN1Sequence seq = null;
-
- public static CRLDistPoint getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static CRLDistPoint getInstance(
- Object obj)
- {
- if (obj instanceof CRLDistPoint)
- {
- return (CRLDistPoint)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new CRLDistPoint((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public CRLDistPoint(
- ASN1Sequence seq)
- {
- this.seq = seq;
- }
-
- public CRLDistPoint(
- DistributionPoint[] points)
- {
- DEREncodableVector v = new DEREncodableVector();
-
- for (int i = 0; i != points.length; i++)
- {
- v.add(points[i]);
- }
-
- seq = new DERSequence(v);
- }
-
- /**
- * <pre>
- * CRLDistPoint ::= SEQUENCE SIZE {1..MAX} OF DistributionPoint
- * </pre>
- */
- public DERObject getDERObject()
- {
- return seq;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.math.BigInteger;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * <pre>
- * CRLNumber::= INTEGER(0..MAX)
- * </pre>
- */
-public class CRLNumber
- extends DERInteger
-{
-
- public CRLNumber(
- BigInteger number)
- {
- super(number);
- }
-
- public BigInteger getCRLNumber()
- {
- return getPositiveValue();
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-public class CRLReason
- extends DEREnumerated
-{
- public static final int UNSPECIFIED = 0;
- public static final int KEY_COMPROMISE = 1;
- public static final int CA_COMPROMISE = 2;
- public static final int AFFILIATION_CHANGED = 3;
- public static final int SUPERSEDED = 4;
- public static final int CESSATION_OF_OPERATION = 5;
- public static final int CERTIFICATE_HOLD = 6;
- public static final int REMOVE_FROM_CRL = 8;
- public static final int PRIVILEGE_WITHDRAWN = 9;
- public static final int AA_COMPROMISE = 10;
-
- /**
- * <pre>
- * CRLReason ::= ENUMERATED {
- * unspecified (0),
- * keyCompromise (1),
- * cACompromise (2),
- * affiliationChanged (3),
- * superseded (4),
- * cessationOfOperation (5),
- * certificateHold (6),
- * removeFromCRL (8),
- * privilegeWithdrawn (9),
- * aACompromise (10)
- * }
- * </pre>
- */
- public CRLReason(
- int reason)
- {
- super(reason);
- }
-}
+++ /dev/null
-
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * PKIX RFC-2459
- *
- * The X.509 v2 CRL syntax is as follows. For signature calculation,
- * the data that is to be signed is ASN.1 DER encoded.
- *
- * <pre>
- * CertificateList ::= SEQUENCE {
- * tbsCertList TBSCertList,
- * signatureAlgorithm AlgorithmIdentifier,
- * signatureValue BIT STRING }
- * </pre>
- */
-public class CertificateList
- implements DEREncodable
-{
- TBSCertList tbsCertList;
- AlgorithmIdentifier sigAlgId;
- DERBitString sig;
-
- public static CertificateList getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static CertificateList getInstance(
- Object obj)
- {
- if (obj instanceof CertificateList)
- {
- return (CertificateList)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new CertificateList((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public CertificateList(
- ASN1Sequence seq)
- {
- tbsCertList = TBSCertList.getInstance(seq.getObjectAt(0));
- sigAlgId = AlgorithmIdentifier.getInstance(seq.getObjectAt(1));
- sig = (DERBitString)seq.getObjectAt(2);
- }
-
- public TBSCertList getTBSCertList()
- {
- return tbsCertList;
- }
-
- public TBSCertList.CRLEntry[] getRevokedCertificates()
- {
- return tbsCertList.getRevokedCertificates();
- }
-
- public AlgorithmIdentifier getSignatureAlgorithm()
- {
- return sigAlgId;
- }
-
- public DERBitString getSignature()
- {
- return sig;
- }
-
- public int getVersion()
- {
- return tbsCertList.getVersion();
- }
-
- public X509Name getIssuer()
- {
- return tbsCertList.getIssuer();
- }
-
- public Time getThisUpdate()
- {
- return tbsCertList.getThisUpdate();
- }
-
- public Time getNextUpdate()
- {
- return tbsCertList.getNextUpdate();
- }
-
- public DERObject getDERObject()
- {
- DERConstructedSequence seq = new DERConstructedSequence();
- seq.addObject(tbsCertList);
- seq.addObject(sigAlgId);
- seq.addObject(sig);
- return seq;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.math.BigInteger;
-import java.util.*;
-
-import org.bouncycastle.asn1.*;
-
-public class DSAParameter
- implements DEREncodable
-{
- DERInteger p, q, g;
-
- public static DSAParameter getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static DSAParameter getInstance(
- Object obj)
- {
- if(obj == null || obj instanceof DSAParameter)
- {
- return (DSAParameter)obj;
- }
-
- if(obj instanceof ASN1Sequence)
- {
- return new DSAParameter((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("Invalid DSAParameter: " + obj.getClass().getName());
- }
-
- public DSAParameter(
- BigInteger p,
- BigInteger q,
- BigInteger g)
- {
- this.p = new DERInteger(p);
- this.q = new DERInteger(q);
- this.g = new DERInteger(g);
- }
-
- public DSAParameter(
- ASN1Sequence seq)
- {
- Enumeration e = seq.getObjects();
-
- p = (DERInteger)e.nextElement();
- q = (DERInteger)e.nextElement();
- g = (DERInteger)e.nextElement();
- }
-
- public BigInteger getP()
- {
- return p.getPositiveValue();
- }
-
- public BigInteger getQ()
- {
- return q.getPositiveValue();
- }
-
- public BigInteger getG()
- {
- return g.getPositiveValue();
- }
-
- public DERObject getDERObject()
- {
- DEREncodableVector v = new DEREncodableVector();
-
- v.add(p);
- v.add(q);
- v.add(g);
-
- return new DERSequence(v);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.util.Enumeration;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * <pre>
- * DigestInfo::=SEQUENCE{
- * digestAlgorithm AlgorithmIdentifier,
- * digest OCTET STRING }
- * </pre>
- */
-public class DigestInfo
- implements DEREncodable
-{
- private byte[] digest;
- private AlgorithmIdentifier algId;
-
- public static DigestInfo getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static DigestInfo getInstance(
- Object obj)
- {
- if (obj instanceof DigestInfo)
- {
- return (DigestInfo)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new DigestInfo((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public DigestInfo(
- AlgorithmIdentifier algId,
- byte[] digest)
- {
- this.digest = digest;
- this.algId = algId;
- }
-
- public DigestInfo(
- ASN1Sequence obj)
- {
- Enumeration e = obj.getObjects();
-
- algId = AlgorithmIdentifier.getInstance(e.nextElement());
- digest = ((ASN1OctetString)e.nextElement()).getOctets();
- }
-
- public AlgorithmIdentifier getAlgorithmId()
- {
- return algId;
- }
-
- public byte[] getDigest()
- {
- return digest;
- }
-
- public DERObject getDERObject()
- {
- DEREncodableVector v = new DEREncodableVector();
-
- v.add(algId);
- v.add(new DEROctetString(digest));
-
- return new DERSequence(v);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-public class DistributionPoint
- implements DEREncodable
-{
- ASN1Sequence seq = null;
-
- public static DistributionPoint getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static DistributionPoint getInstance(
- Object obj)
- {
- if(obj == null || obj instanceof DistributionPoint)
- {
- return (DistributionPoint)obj;
- }
-
- if(obj instanceof ASN1Sequence)
- {
- return new DistributionPoint((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("Invalid DistributionPoint: " + obj.getClass().getName());
- }
-
- public DistributionPoint(
- ASN1Sequence seq)
- {
- this.seq = seq;
- }
-
- public DistributionPoint(
- DistributionPointName distributionPoint,
- ReasonFlags reasons,
- GeneralNames cRLIssuer)
- {
- DEREncodableVector v = new DEREncodableVector();
-
- if (distributionPoint != null)
- {
- v.add(new DERTaggedObject(0, distributionPoint));
- }
-
- if (reasons != null)
- {
- v.add(new DERTaggedObject(1, reasons));
- }
-
- if (cRLIssuer != null)
- {
- v.add(new DERTaggedObject(2, cRLIssuer));
- }
-
- seq = new DERSequence(v);
- }
-
- /**
- * <pre>
- * DistributionPoint ::= SEQUENCE {
- * distributionPoint [0] DistributionPointName OPTIONAL,
- * reasons [1] ReasonFlags OPTIONAL,
- * cRLIssuer [2] GeneralNames OPTIONAL
- * }
- * </pre>
- */
- public DERObject getDERObject()
- {
- return seq;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-public class DistributionPointName
- implements DEREncodable
-{
- DEREncodable name;
- int type;
-
- public static final int FULL_NAME = 0;
- public static final int NAME_RELATIVE_TO_CRL_ISSUER = 1;
-
- public DistributionPointName(
- int type,
- DEREncodable name)
- {
- this.type = type;
- this.name = name;
- }
-
- /**
- * <pre>
- * DistributionPointName ::= CHOICE {
- * fullName [0] GeneralNames,
- * nameRelativeToCRLIssuer [1] RelativeDistinguishedName
- * }
- * </pre>
- */
- public DERObject getDERObject()
- {
- return new DERTaggedObject(false, type, name);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * <pre>
- * GeneralName ::= CHOICE {
- * otherName [0] OtherName,
- * rfc822Name [1] IA5String,
- * dNSName [2] IA5String,
- * x400Address [3] ORAddress,
- * directoryName [4] Name,
- * ediPartyName [5] EDIPartyName,
- * uniformResourceIdentifier [6] IA5String,
- * iPAddress [7] OCTET STRING,
- * registeredID [8] OBJECT IDENTIFIER}
- *
- * OtherName ::= SEQUENCE {
- * type-id OBJECT IDENTIFIER,
- * value [0] EXPLICIT ANY DEFINED BY type-id }
- *
- * EDIPartyName ::= SEQUENCE {
- * nameAssigner [0] DirectoryString OPTIONAL,
- * partyName [1] DirectoryString }
- * </pre>
- */
-public class GeneralName
- implements DEREncodable
-{
- DEREncodable obj;
- int tag;
- boolean isInsideImplicit = false; // if we are in an implicitly tagged object
-
- public GeneralName(
- X509Name directoryName)
- {
- this.obj = directoryName;
- this.tag = 4;
- }
-
- /**
- * When the subjectAltName extension contains an Internet mail address,
- * the address MUST be included as an rfc822Name. The format of an
- * rfc822Name is an "addr-spec" as defined in RFC 822 [RFC 822].
- *
- * When the subjectAltName extension contains a domain name service
- * label, the domain name MUST be stored in the dNSName (an IA5String).
- * The name MUST be in the "preferred name syntax," as specified by RFC
- * 1034 [RFC 1034].
- *
- * When the subjectAltName extension contains a URI, the name MUST be
- * stored in the uniformResourceIdentifier (an IA5String). The name MUST
- * be a non-relative URL, and MUST follow the URL syntax and encoding
- * rules specified in [RFC 1738]. The name must include both a scheme
- * (e.g., "http" or "ftp") and a scheme-specific-part. The scheme-
- * specific-part must include a fully qualified domain name or IP
- * address as the host.
- *
- * When the subjectAltName extension contains a iPAddress, the address
- * MUST be stored in the octet string in "network byte order," as
- * specified in RFC 791 [RFC 791]. The least significant bit (LSB) of
- * each octet is the LSB of the corresponding byte in the network
- * address. For IP Version 4, as specified in RFC 791, the octet string
- * MUST contain exactly four octets. For IP Version 6, as specified in
- * RFC 1883, the octet string MUST contain exactly sixteen octets [RFC
- * 1883].
- */
- public GeneralName(
- DERObject name, int tag)
- {
- this.obj = name;
- this.tag = tag;
- }
-
- /**
- * mark whether or not we are contained inside an implicitly tagged
- * object.
- * @deprecated
- */
- public void markInsideImplicit(
- boolean isInsideImplicit)
- {
- this.isInsideImplicit = isInsideImplicit;
- }
-
- public DERObject getDERObject()
- {
- if (obj.getDERObject() instanceof ASN1Sequence)
- {
- return new DERTaggedObject(true, tag, obj);
- }
- else
- {
- return new DERTaggedObject(false, tag, obj);
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-public class GeneralNames
- implements DEREncodable
-{
- ASN1Sequence seq;
- boolean isInsideImplicit = false;
-
- public static GeneralNames getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof GeneralNames)
- {
- return (GeneralNames)obj;
- }
-
- if (obj instanceof ASN1Sequence)
- {
- return new GeneralNames((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- public static GeneralNames getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public GeneralNames(
- ASN1Sequence seq)
- {
- this.seq = seq;
- }
-
- /*
- * this is a hack! But it will have to do until the ambiguity rules
- * get sorted out for implicit/explicit tagging...
- * @deprecated
- */
- public void markInsideImplicit(
- boolean isInsideImplicit)
- {
- this.isInsideImplicit = isInsideImplicit;
- }
-
- /**
- * <pre>
- * GeneralNames ::= SEQUENCE SIZE {1..MAX} OF GeneralName
- * </pre>
- */
- public DERObject getDERObject()
- {
- return seq;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * <pre>
- * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
- *
- * KeyUsage ::= BIT STRING {
- * digitalSignature (0),
- * nonRepudiation (1),
- * keyEncipherment (2),
- * dataEncipherment (3),
- * keyAgreement (4),
- * keyCertSign (5),
- * cRLSign (6),
- * encipherOnly (7),
- * decipherOnly (8) }
- * </pre>
- */
-public class KeyUsage
- extends DERBitString
-{
- public static final int digitalSignature = (1 << 7);
- public static final int nonRepudiation = (1 << 6);
- public static final int keyEncipherment = (1 << 5);
- public static final int dataEncipherment = (1 << 4);
- public static final int keyAgreement = (1 << 3);
- public static final int keyCertSign = (1 << 2);
- public static final int cRLSign = (1 << 1);
- public static final int encipherOnly = (1 << 0);
- public static final int decipherOnly = (1 << 15);
-
- /**
- * Basic constructor.
- *
- * @param usage - the bitwise OR of the Key Usage flags giving the
- * allowed uses for the key.
- * e.g. (X509KeyUsage.keyEncipherment | X509KeyUsage.dataEncipherment)
- */
- public KeyUsage(
- int usage)
- {
- super(getBytes(usage), getPadBits(usage));
- }
-
- public KeyUsage(
- DERBitString usage)
- {
- super(usage.getBytes(), usage.getPadBits());
- }
-
- public String toString()
- {
- return "KeyUsage: 0x" + Integer.toHexString(data[0] & 0xff);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.util.Enumeration;
-import java.math.BigInteger;
-
-import org.bouncycastle.asn1.*;
-
-public class RSAPublicKeyStructure
- implements DEREncodable
-{
- private BigInteger modulus;
- private BigInteger publicExponent;
-
- public static RSAPublicKeyStructure getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static RSAPublicKeyStructure getInstance(
- Object obj)
- {
- if(obj == null || obj instanceof RSAPublicKeyStructure)
- {
- return (RSAPublicKeyStructure)obj;
- }
-
- if(obj instanceof ASN1Sequence)
- {
- return new RSAPublicKeyStructure((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("Invalid RSAPublicKeyStructure: " + obj.getClass().getName());
- }
-
- public RSAPublicKeyStructure(
- BigInteger modulus,
- BigInteger publicExponent)
- {
- this.modulus = modulus;
- this.publicExponent = publicExponent;
- }
-
- public RSAPublicKeyStructure(
- ASN1Sequence seq)
- {
- Enumeration e = seq.getObjects();
-
- modulus = ((DERInteger)e.nextElement()).getValue();
- publicExponent = ((DERInteger)e.nextElement()).getValue();
- }
-
- public BigInteger getModulus()
- {
- return modulus;
- }
-
- public BigInteger getPublicExponent()
- {
- return publicExponent;
- }
-
- /**
- * This outputs the key in PKCS1v2 format.
- * <pre>
- * RSAPublicKey ::= SEQUENCE {
- * modulus INTEGER, -- n
- * publicExponent INTEGER, -- e
- * }
- * </pre>
- * <p>
- */
- public DERObject getDERObject()
- {
- DERConstructedSequence seq = new DERConstructedSequence();
-
- seq.addObject(new DERInteger(getModulus()));
- seq.addObject(new DERInteger(getPublicExponent()));
-
- return seq;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-public class ReasonFlags
- extends DERBitString
-{
- public static final int UNUSED = (1 << 7);
- public static final int KEY_COMPROMISE = (1 << 6);
- public static final int CA_COMPROMISE = (1 << 5);
- public static final int AFFILIATION_CHANGED = (1 << 4);
- public static final int SUPERSEDED = (1 << 3);
- public static final int CESSATION_OF_OPERATION = (1 << 2);
- public static final int CERTIFICATE_HOLD = (1 << 1);
- public static final int PRIVILEGE_WITHDRAWN = (1 << 0);
- public static final int AA_COMPROMISE = (1 << 15);
-
- /**
- * <pre>
- * ReasonFlags ::= BIT STRING {
- * unused(0),
- * keyCompromise(1),
- * cACompromise(2),
- * affiliationChanged(3),
- * superseded(4),
- * cessationOfOperation(5),
- * certficateHold(6)
- * }
- * </pre>
- * @param reasons - the bitwise OR of the Key Reason flags giving the
- * allowed uses for the key.
- */
- public ReasonFlags(
- int reasons)
- {
- super(getBytes(reasons), getPadBits(reasons));
- }
-
- public ReasonFlags(
- DERBitString reasons)
- {
- super(reasons.getBytes(), reasons.getPadBits());
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.crypto.Digest;
-import org.bouncycastle.crypto.digests.SHA1Digest;
-import org.bouncycastle.asn1.*;
-
-/**
- * <pre>
- * SubjectKeyIdentifier::= OCTET STRING
- * </pre>
- */
-public class SubjectKeyIdentifier
- implements DEREncodable
-{
- private byte[] keyidentifier;
-
- public static SubjectKeyIdentifier getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1OctetString.getInstance(obj, explicit));
- }
-
- public static SubjectKeyIdentifier getInstance(
- Object obj)
- {
- if(obj == null || obj instanceof SubjectKeyIdentifier)
- {
- return (SubjectKeyIdentifier)obj;
- }
-
- if(obj instanceof SubjectPublicKeyInfo)
- {
- return new SubjectKeyIdentifier((SubjectPublicKeyInfo)obj);
- }
-
- if(obj instanceof ASN1OctetString)
- {
- return new SubjectKeyIdentifier((ASN1OctetString)obj);
- }
-
- throw new IllegalArgumentException("Invalid SubjectKeyIdentifier: " + obj.getClass().getName());
- }
-
- public SubjectKeyIdentifier(
- byte[] keyid)
- {
- this.keyidentifier=keyid;
- }
-
- public SubjectKeyIdentifier(
- ASN1OctetString keyid)
- {
- this.keyidentifier=keyid.getOctets();
-
- }
-
- /**
- *
- * Calulates the keyidentifier using a SHA1 hash over the BIT STRING
- * from SubjectPublicKeyInfo as defined in RFC2459.
- *
- **/
- public SubjectKeyIdentifier(
- SubjectPublicKeyInfo spki)
- {
- Digest digest = new SHA1Digest();
- byte[] resBuf = new byte[digest.getDigestSize()];
-
- byte[] bytes = spki.getPublicKeyData().getBytes();
- digest.update(bytes, 0, bytes.length);
- digest.doFinal(resBuf, 0);
- this.keyidentifier=resBuf;
- }
-
- public byte[] getKeyIdentifier()
- {
- return keyidentifier;
- }
-
- /**
- * <pre>
- * SubjectKeyIdentifier := OCTET STRING
- * </pre>
- */
- public DERObject getDERObject()
- {
- return new DEROctetString(keyidentifier);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.io.*;
-import java.util.Enumeration;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * The object that contains the public key stored in a certficate.
- * <p>
- * The getEncoded() method in the public keys in the JCE produces a DER
- * encoded one of these.
- */
-public class SubjectPublicKeyInfo
- implements DEREncodable
-{
- private AlgorithmIdentifier algId;
- private DERBitString keyData;
-
- public static SubjectPublicKeyInfo getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static SubjectPublicKeyInfo getInstance(
- Object obj)
- {
- if (obj instanceof SubjectPublicKeyInfo)
- {
- return (SubjectPublicKeyInfo)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new SubjectPublicKeyInfo((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public SubjectPublicKeyInfo(
- AlgorithmIdentifier algId,
- DEREncodable publicKey)
- {
- this.keyData = new DERBitString(publicKey);
- this.algId = algId;
- }
-
- public SubjectPublicKeyInfo(
- AlgorithmIdentifier algId,
- byte[] publicKey)
- {
- this.keyData = new DERBitString(publicKey);
- this.algId = algId;
- }
-
- public SubjectPublicKeyInfo(
- ASN1Sequence seq)
- {
- Enumeration e = seq.getObjects();
-
- this.algId = AlgorithmIdentifier.getInstance(e.nextElement());
- this.keyData = (DERBitString)e.nextElement();
- }
-
- public AlgorithmIdentifier getAlgorithmId()
- {
- return algId;
- }
-
- /**
- * for when the public key is an encoded object - if the bitstring
- * can't be decoded this routine throws an IOException.
- *
- * @exception IOException - if the bit string doesn't represent a DER
- * encoded object.
- */
- public DERObject getPublicKey()
- throws IOException
- {
- ByteArrayInputStream bIn = new ByteArrayInputStream(keyData.getBytes());
- DERInputStream dIn = new DERInputStream(bIn);
-
- return dIn.readObject();
- }
-
- /**
- * for when the public key is raw bits...
- */
- public DERBitString getPublicKeyData()
- {
- return keyData;
- }
-
- /**
- * <pre>
- * SubjectPublicKeyInfo ::= SEQUENCE {
- * algorithm AlgorithmIdentifier,
- * publicKey BIT STRING }
- * </pre>
- */
- public DERObject getDERObject()
- {
- DERConstructedSequence seq = new DERConstructedSequence();
-
- seq.addObject(algId);
- seq.addObject(keyData);
-
- return seq;
- }
-}
+++ /dev/null
-
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * PKIX RFC-2459
- *
- * <pre>
- * TBSCertList ::= SEQUENCE {
- * version Version OPTIONAL,
- * -- if present, shall be v2
- * signature AlgorithmIdentifier,
- * issuer Name,
- * thisUpdate Time,
- * nextUpdate Time OPTIONAL,
- * revokedCertificates SEQUENCE OF SEQUENCE {
- * userCertificate CertificateSerialNumber,
- * revocationDate Time,
- * crlEntryExtensions Extensions OPTIONAL
- * -- if present, shall be v2
- * } OPTIONAL,
- * crlExtensions [0] EXPLICIT Extensions OPTIONAL
- * -- if present, shall be v2
- * }
- * </pre>
- */
-
-public class TBSCertList
- implements DEREncodable
-{
- public class CRLEntry
- implements DEREncodable
- {
- DERConstructedSequence seq;
-
- DERInteger userCertificate;
- Time revocationDate;
- X509Extensions crlEntryExtensions;
-
- public CRLEntry(
- DERConstructedSequence seq)
- {
- this.seq = seq;
-
- userCertificate = (DERInteger)seq.getObjectAt(0);
- revocationDate = Time.getInstance(seq.getObjectAt(1));
- if (seq.getSize() == 3)
- {
- crlEntryExtensions = X509Extensions.getInstance(seq.getObjectAt(2));
- }
- }
-
- public DERInteger getUserCertificate()
- {
- return userCertificate;
- }
-
- public Time getRevocationDate()
- {
- return revocationDate;
- }
-
- public X509Extensions getExtensions()
- {
- return crlEntryExtensions;
- }
-
- public DERObject getDERObject()
- {
- return seq;
- }
- }
-
- ASN1Sequence seq;
-
- DERInteger version;
- AlgorithmIdentifier signature;
- X509Name issuer;
- Time thisUpdate;
- Time nextUpdate;
- CRLEntry[] revokedCertificates;
- X509Extensions crlExtensions;
-
- public static TBSCertList getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static TBSCertList getInstance(
- Object obj)
- {
- if (obj instanceof TBSCertList)
- {
- return (TBSCertList)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new TBSCertList((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public TBSCertList(
- ASN1Sequence seq)
- {
- int seqPos = 0;
-
- this.seq = seq;
-
- if (seq.getObjectAt(seqPos) instanceof DERInteger)
- {
- version = (DERInteger)seq.getObjectAt(seqPos++);
- }
- else
- {
- version = new DERInteger(0);
- }
-
- signature = AlgorithmIdentifier.getInstance(seq.getObjectAt(seqPos++));
- issuer = X509Name.getInstance(seq.getObjectAt(seqPos++));
- thisUpdate = Time.getInstance(seq.getObjectAt(seqPos++));
-
- if (seqPos < seq.size()
- && (seq.getObjectAt(seqPos) instanceof DERUTCTime
- || seq.getObjectAt(seqPos) instanceof DERGeneralizedTime
- || seq.getObjectAt(seqPos) instanceof Time))
- {
- nextUpdate = Time.getInstance(seq.getObjectAt(seqPos++));
- }
-
- if (seqPos < seq.size()
- && !(seq.getObjectAt(seqPos) instanceof DERTaggedObject))
- {
- DERConstructedSequence certs = (DERConstructedSequence)seq.getObjectAt(seqPos++);
- revokedCertificates = new CRLEntry[certs.getSize()];
-
- for ( int i = 0; i < revokedCertificates.length; i++)
- {
- revokedCertificates[i] = new CRLEntry((DERConstructedSequence)certs.getObjectAt(i));
- }
- }
-
- if (seqPos < seq.size()
- && seq.getObjectAt(seqPos) instanceof DERTaggedObject)
- {
- crlExtensions = X509Extensions.getInstance(seq.getObjectAt(seqPos++));
- }
- }
-
- public int getVersion()
- {
- return version.getValue().intValue() + 1;
- }
-
- public DERInteger getVersionNumber()
- {
- return version;
- }
-
- public AlgorithmIdentifier getSignature()
- {
- return signature;
- }
-
- public X509Name getIssuer()
- {
- return issuer;
- }
-
- public Time getThisUpdate()
- {
- return thisUpdate;
- }
-
- public Time getNextUpdate()
- {
- return nextUpdate;
- }
-
- public CRLEntry[] getRevokedCertificates()
- {
- return revokedCertificates;
- }
-
- public X509Extensions getExtensions()
- {
- return crlExtensions;
- }
-
- public DERObject getDERObject()
- {
- return seq;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
-
-/**
- * <pre>
- * TBSCertificate ::= SEQUENCE {
- * version [ 0 ] Version DEFAULT v1(0),
- * serialNumber CertificateSerialNumber,
- * signature AlgorithmIdentifier,
- * issuer Name,
- * validity Validity,
- * subject Name,
- * subjectPublicKeyInfo SubjectPublicKeyInfo,
- * issuerUniqueID [ 1 ] IMPLICIT UniqueIdentifier OPTIONAL,
- * subjectUniqueID [ 2 ] IMPLICIT UniqueIdentifier OPTIONAL,
- * extensions [ 3 ] Extensions OPTIONAL
- * }
- * </pre>
- * <p>
- * Note: issuerUniqueID and subjectUniqueID are both deprecated by the IETF. This class
- * will parse them, but you really shouldn't be creating new ones.
- */
-public class TBSCertificateStructure
- implements DEREncodable, X509ObjectIdentifiers, PKCSObjectIdentifiers
-{
- ASN1Sequence seq;
-
- DERInteger version;
- DERInteger serialNumber;
- AlgorithmIdentifier signature;
- X509Name issuer;
- Time startDate, endDate;
- X509Name subject;
- SubjectPublicKeyInfo subjectPublicKeyInfo;
- DERBitString issuerUniqueId;
- DERBitString subjectUniqueId;
- X509Extensions extensions;
-
- public static TBSCertificateStructure getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static TBSCertificateStructure getInstance(
- Object obj)
- {
- if (obj instanceof TBSCertificateStructure)
- {
- return (TBSCertificateStructure)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new TBSCertificateStructure((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public TBSCertificateStructure(
- ASN1Sequence seq)
- {
- int seqStart = 0;
-
- this.seq = seq;
-
- //
- // some certficates don't include a version number - we assume v1
- //
- if (seq.getObjectAt(0) instanceof DERTaggedObject)
- {
- version = DERInteger.getInstance(seq.getObjectAt(0));
- }
- else
- {
- seqStart = -1; // field 0 is missing!
- version = new DERInteger(0);
- }
-
- serialNumber = DERInteger.getInstance(seq.getObjectAt(seqStart + 1));
-
- signature = AlgorithmIdentifier.getInstance(seq.getObjectAt(seqStart + 2));
- issuer = X509Name.getInstance(seq.getObjectAt(seqStart + 3));
-
- //
- // before and after dates
- //
- ASN1Sequence dates = (ASN1Sequence)seq.getObjectAt(seqStart + 4);
-
- startDate = Time.getInstance(dates.getObjectAt(0));
- endDate = Time.getInstance(dates.getObjectAt(1));
-
- subject = X509Name.getInstance(seq.getObjectAt(seqStart + 5));
-
- //
- // public key info.
- //
- subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(seq.getObjectAt(seqStart + 6));
-
- for (int extras = seq.size() - (seqStart + 6) - 1; extras > 0; extras--)
- {
- DERTaggedObject extra = (DERTaggedObject)seq.getObjectAt(seqStart + 6 + extras);
-
- switch (extra.getTagNo())
- {
- case 1:
- issuerUniqueId = DERBitString.getInstance(extra);
- break;
- case 2:
- subjectUniqueId = DERBitString.getInstance(extra);
- break;
- case 3:
- extensions = X509Extensions.getInstance(extra);
- }
- }
- }
-
- public int getVersion()
- {
- return version.getValue().intValue() + 1;
- }
-
- public DERInteger getVersionNumber()
- {
- return version;
- }
-
- public DERInteger getSerialNumber()
- {
- return serialNumber;
- }
-
- public AlgorithmIdentifier getSignature()
- {
- return signature;
- }
-
- public X509Name getIssuer()
- {
- return issuer;
- }
-
- public Time getStartDate()
- {
- return startDate;
- }
-
- public Time getEndDate()
- {
- return endDate;
- }
-
- public X509Name getSubject()
- {
- return subject;
- }
-
- public SubjectPublicKeyInfo getSubjectPublicKeyInfo()
- {
- return subjectPublicKeyInfo;
- }
-
- public DERBitString getIssuerUniqueId()
- {
- return issuerUniqueId;
- }
-
- public DERBitString getSubjectUniqueId()
- {
- return subjectUniqueId;
- }
-
- public X509Extensions getExtensions()
- {
- return extensions;
- }
-
- public DERObject getDERObject()
- {
- return seq;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.util.Date;
-import java.util.SimpleTimeZone;
-import java.text.ParsePosition;
-import java.text.SimpleDateFormat;
-
-import org.bouncycastle.asn1.*;
-
-public class Time
- implements DEREncodable
-{
- DERObject time;
-
- public static Time getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(obj.getObject());
- }
-
- public Time(
- DERObject time)
- {
- if (!(time instanceof DERUTCTime)
- && !(time instanceof DERGeneralizedTime))
- {
- throw new IllegalArgumentException("unknown object passed to Time");
- }
-
- this.time = time;
- }
-
- /**
- * creates a time object from a given date - if the date is between 1950
- * and 2049 a UTCTime object is generated, otherwise a GeneralizedTime
- * is used.
- */
- public Time(
- Date date)
- {
- SimpleTimeZone tz = new SimpleTimeZone(0, "Z");
- SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmss");
-
- dateF.setTimeZone(tz);
-
- String d = dateF.format(date) + "Z";
- int year = Integer.parseInt(d.substring(0, 4));
-
- if (year < 1950 || year > 2049)
- {
- time = new DERGeneralizedTime(d);
- }
- else
- {
- time = new DERUTCTime(d.substring(2));
- }
- }
-
- public static Time getInstance(
- Object obj)
- {
- if (obj instanceof Time)
- {
- return (Time)obj;
- }
- else if (obj instanceof DERUTCTime)
- {
- return new Time((DERUTCTime)obj);
- }
- else if (obj instanceof DERGeneralizedTime)
- {
- return new Time((DERGeneralizedTime)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public String getTime()
- {
- if (time instanceof DERUTCTime)
- {
- return ((DERUTCTime)time).getAdjustedTime();
- }
- else
- {
- return ((DERGeneralizedTime)time).getTime();
- }
- }
-
- public Date getDate()
- {
- SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMddHHmmssz");
-
- return dateF.parse(this.getTime(), new ParsePosition(0));
- }
-
- /**
- * <pre>
- * Time ::= CHOICE {
- * utcTime UTCTime,
- * generalTime GeneralizedTime }
- * </pre>
- */
- public DERObject getDERObject()
- {
- return time;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * Generator for Version 1 TBSCertificateStructures.
- * <pre>
- * TBSCertificate ::= SEQUENCE {
- * version [ 0 ] Version DEFAULT v1(0),
- * serialNumber CertificateSerialNumber,
- * signature AlgorithmIdentifier,
- * issuer Name,
- * validity Validity,
- * subject Name,
- * subjectPublicKeyInfo SubjectPublicKeyInfo,
- * }
- * </pre>
- *
- */
-public class V1TBSCertificateGenerator
-{
- DERTaggedObject version = new DERTaggedObject(0, new DERInteger(0));
-
- DERInteger serialNumber;
- AlgorithmIdentifier signature;
- X509Name issuer;
- Time startDate, endDate;
- X509Name subject;
- SubjectPublicKeyInfo subjectPublicKeyInfo;
-
- public V1TBSCertificateGenerator()
- {
- }
-
- public void setSerialNumber(
- DERInteger serialNumber)
- {
- this.serialNumber = serialNumber;
- }
-
- public void setSignature(
- AlgorithmIdentifier signature)
- {
- this.signature = signature;
- }
-
- public void setIssuer(
- X509Name issuer)
- {
- this.issuer = issuer;
- }
-
- public void setStartDate(
- Time startDate)
- {
- this.startDate = startDate;
- }
-
- public void setStartDate(
- DERUTCTime startDate)
- {
- this.startDate = new Time(startDate);
- }
-
- public void setEndDate(
- Time endDate)
- {
- this.endDate = endDate;
- }
-
- public void setEndDate(
- DERUTCTime endDate)
- {
- this.endDate = new Time(endDate);
- }
-
- public void setSubject(
- X509Name subject)
- {
- this.subject = subject;
- }
-
- public void setSubjectPublicKeyInfo(
- SubjectPublicKeyInfo pubKeyInfo)
- {
- this.subjectPublicKeyInfo = pubKeyInfo;
- }
-
- public TBSCertificateStructure generateTBSCertificate()
- {
- if ((serialNumber == null) || (signature == null)
- || (issuer == null) || (startDate == null) || (endDate == null)
- || (subject == null) || (subjectPublicKeyInfo == null))
- {
- throw new IllegalStateException("not all mandatory fields set in V1 TBScertificate generator");
- }
-
- DERConstructedSequence seq = new DERConstructedSequence();
-
- seq.addObject(version);
- seq.addObject(serialNumber);
- seq.addObject(signature);
- seq.addObject(issuer);
-
- //
- // before and after dates
- //
- DERConstructedSequence validity = new DERConstructedSequence();
-
- validity.addObject(startDate);
- validity.addObject(endDate);
-
- seq.addObject(validity);
-
- seq.addObject(subject);
-
- seq.addObject(subjectPublicKeyInfo);
-
- return new TBSCertificateStructure(seq);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.io.*;
-import java.util.Vector;
-import java.util.Enumeration;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * Generator for Version 2 TBSCertList structures.
- * <pre>
- * TBSCertList ::= SEQUENCE {
- * version Version OPTIONAL,
- * -- if present, shall be v2
- * signature AlgorithmIdentifier,
- * issuer Name,
- * thisUpdate Time,
- * nextUpdate Time OPTIONAL,
- * revokedCertificates SEQUENCE OF SEQUENCE {
- * userCertificate CertificateSerialNumber,
- * revocationDate Time,
- * crlEntryExtensions Extensions OPTIONAL
- * -- if present, shall be v2
- * } OPTIONAL,
- * crlExtensions [0] EXPLICIT Extensions OPTIONAL
- * -- if present, shall be v2
- * }
- * </pre>
- *
- * <b>Note: This class may be subject to change</b>
- */
-public class V2TBSCertListGenerator
-{
- DERInteger version = new DERInteger(1);
-
- AlgorithmIdentifier signature;
- X509Name issuer;
- Time thisUpdate, nextUpdate=null;
- X509Extensions extensions=null;
- private Vector crlentries=null;
-
- public V2TBSCertListGenerator()
- {
- }
-
-
- public void setSignature(
- AlgorithmIdentifier signature)
- {
- this.signature = signature;
- }
-
- public void setIssuer(
- X509Name issuer)
- {
- this.issuer = issuer;
- }
-
- public void setThisUpdate(
- DERUTCTime thisUpdate)
- {
- this.thisUpdate = new Time(thisUpdate);
- }
-
- public void setNextUpdate(
- DERUTCTime nextUpdate)
- {
- this.nextUpdate = new Time(nextUpdate);
- }
-
- public void setThisUpdate(
- Time thisUpdate)
- {
- this.thisUpdate = thisUpdate;
- }
-
- public void setNextUpdate(
- Time nextUpdate)
- {
- this.nextUpdate = nextUpdate;
- }
-
- public void addCRLEntry(
- DERConstructedSequence crlEntry)
- {
- if (crlentries == null)
- crlentries = new Vector();
- crlentries.addElement(crlEntry);
- }
-
- public void addCRLEntry(DERInteger userCertificate, DERUTCTime revocationDate, int reason)
- {
- addCRLEntry(userCertificate, new Time(revocationDate), reason);
- }
-
- public void addCRLEntry(DERInteger userCertificate, Time revocationDate, int reason)
- {
- DERConstructedSequence seq = new DERConstructedSequence();
- seq.addObject(userCertificate);
- seq.addObject(revocationDate);
-
- if (reason != 0)
- {
- CRLReason rf = new CRLReason(reason);
- ByteArrayOutputStream bOut = new ByteArrayOutputStream();
- DEROutputStream dOut = new DEROutputStream(bOut);
- try
- {
- dOut.writeObject(rf);
- }
- catch (IOException e)
- {
- throw new IllegalArgumentException("error encoding value: " + e);
- }
- byte[] value = bOut.toByteArray();
- DERConstructedSequence eseq = new DERConstructedSequence();
- DERConstructedSequence eseq1 = new DERConstructedSequence();
- eseq1.addObject(X509Extensions.ReasonCode);
- eseq1.addObject(new DEROctetString(value));
- eseq.addObject(eseq1);
- X509Extensions ex = new X509Extensions(eseq);
- seq.addObject(ex);
- }
- if (crlentries == null)
- crlentries = new Vector();
- crlentries.addElement(seq);
- }
-
- public void setExtensions(
- X509Extensions extensions)
- {
- this.extensions = extensions;
- }
-
- public TBSCertList generateTBSCertList()
- {
- if ((signature == null) || (issuer == null) || (thisUpdate == null))
- {
- throw new IllegalStateException("Not all mandatory fields set in V2 TBSCertList generator.");
- }
-
- DERConstructedSequence seq = new DERConstructedSequence();
-
- seq.addObject(version);
- seq.addObject(signature);
- seq.addObject(issuer);
-
- seq.addObject(thisUpdate);
- if (nextUpdate != null)
- seq.addObject(nextUpdate);
-
- // Add CRLEntries if they exist
- if (crlentries != null) {
- DERConstructedSequence certseq = new DERConstructedSequence();
- Enumeration it = crlentries.elements();
- while( it.hasMoreElements() ) {
- certseq.addObject((DERConstructedSequence)it.nextElement());
- }
- seq.addObject(certseq);
- }
-
- if (extensions != null)
- {
- seq.addObject(new DERTaggedObject(0, extensions));
- }
-
- return new TBSCertList(seq);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * Generator for Version 3 TBSCertificateStructures.
- * <pre>
- * TBSCertificate ::= SEQUENCE {
- * version [ 0 ] Version DEFAULT v1(0),
- * serialNumber CertificateSerialNumber,
- * signature AlgorithmIdentifier,
- * issuer Name,
- * validity Validity,
- * subject Name,
- * subjectPublicKeyInfo SubjectPublicKeyInfo,
- * issuerUniqueID [ 1 ] IMPLICIT UniqueIdentifier OPTIONAL,
- * subjectUniqueID [ 2 ] IMPLICIT UniqueIdentifier OPTIONAL,
- * extensions [ 3 ] Extensions OPTIONAL
- * }
- * </pre>
- *
- */
-public class V3TBSCertificateGenerator
-{
- DERTaggedObject version = new DERTaggedObject(0, new DERInteger(2));
-
- DERInteger serialNumber;
- AlgorithmIdentifier signature;
- X509Name issuer;
- Time startDate, endDate;
- X509Name subject;
- SubjectPublicKeyInfo subjectPublicKeyInfo;
- X509Extensions extensions;
-
- public V3TBSCertificateGenerator()
- {
- }
-
- public void setSerialNumber(
- DERInteger serialNumber)
- {
- this.serialNumber = serialNumber;
- }
-
- public void setSignature(
- AlgorithmIdentifier signature)
- {
- this.signature = signature;
- }
-
- public void setIssuer(
- X509Name issuer)
- {
- this.issuer = issuer;
- }
-
- public void setStartDate(
- DERUTCTime startDate)
- {
- this.startDate = new Time(startDate);
- }
-
- public void setStartDate(
- Time startDate)
- {
- this.startDate = startDate;
- }
-
- public void setEndDate(
- DERUTCTime endDate)
- {
- this.endDate = new Time(endDate);
- }
-
- public void setEndDate(
- Time endDate)
- {
- this.endDate = endDate;
- }
-
- public void setSubject(
- X509Name subject)
- {
- this.subject = subject;
- }
-
- public void setSubjectPublicKeyInfo(
- SubjectPublicKeyInfo pubKeyInfo)
- {
- this.subjectPublicKeyInfo = pubKeyInfo;
- }
-
- public void setExtensions(
- X509Extensions extensions)
- {
- this.extensions = extensions;
- }
-
- public TBSCertificateStructure generateTBSCertificate()
- {
- if ((serialNumber == null) || (signature == null)
- || (issuer == null) || (startDate == null) || (endDate == null)
- || (subject == null) || (subjectPublicKeyInfo == null))
- {
- throw new IllegalStateException("not all mandatory fields set in V3 TBScertificate generator");
- }
-
- DERConstructedSequence seq = new DERConstructedSequence();
-
- seq.addObject(version);
- seq.addObject(serialNumber);
- seq.addObject(signature);
- seq.addObject(issuer);
-
- //
- // before and after dates
- //
- DERConstructedSequence validity = new DERConstructedSequence();
-
- validity.addObject(startDate);
- validity.addObject(endDate);
-
- seq.addObject(validity);
-
- seq.addObject(subject);
-
- seq.addObject(subjectPublicKeyInfo);
-
- if (extensions != null)
- {
- seq.addObject(new DERTaggedObject(3, extensions));
- }
-
- return new TBSCertificateStructure(seq);
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-import org.bouncycastle.asn1.pkcs.*;
-
-/**
- * an X509Certificate structure.
- * <pre>
- * Certificate ::= SEQUENCE {
- * tbsCertificate TBSCertificate,
- * signatureAlgorithm AlgorithmIdentifier,
- * signature BIT STRING
- * }
- * </pre>
- */
-public class X509CertificateStructure
- implements DEREncodable, X509ObjectIdentifiers, PKCSObjectIdentifiers
-{
- ASN1Sequence seq;
- TBSCertificateStructure tbsCert;
- AlgorithmIdentifier sigAlgId;
- DERBitString sig;
-
- public static X509CertificateStructure getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static X509CertificateStructure getInstance(
- Object obj)
- {
- if (obj instanceof X509CertificateStructure)
- {
- return (X509CertificateStructure)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new X509CertificateStructure((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- public X509CertificateStructure(
- ASN1Sequence seq)
- {
- this.seq = seq;
-
- //
- // correct x509 certficate
- //
- if (seq.size() == 3)
- {
- tbsCert = TBSCertificateStructure.getInstance(seq.getObjectAt(0));
- sigAlgId = AlgorithmIdentifier.getInstance(seq.getObjectAt(1));
-
- sig = (DERBitString)seq.getObjectAt(2);
- }
- }
-
- public TBSCertificateStructure getTBSCertificate()
- {
- return tbsCert;
- }
-
- public int getVersion()
- {
- return tbsCert.getVersion();
- }
-
- public DERInteger getSerialNumber()
- {
- return tbsCert.getSerialNumber();
- }
-
- public X509Name getIssuer()
- {
- return tbsCert.getIssuer();
- }
-
- public Time getStartDate()
- {
- return tbsCert.getStartDate();
- }
-
- public Time getEndDate()
- {
- return tbsCert.getEndDate();
- }
-
- public X509Name getSubject()
- {
- return tbsCert.getSubject();
- }
-
- public SubjectPublicKeyInfo getSubjectPublicKeyInfo()
- {
- return tbsCert.getSubjectPublicKeyInfo();
- }
-
- public AlgorithmIdentifier getSignatureAlgorithm()
- {
- return sigAlgId;
- }
-
- public DERBitString getSignature()
- {
- return sig;
- }
-
- public DERObject getDERObject()
- {
- return seq;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.*;
-
-/**
- * an object for the elements in the X.509 V3 extension block.
- */
-public class X509Extension
-{
- boolean critical;
- DEROctetString value;
-
- public X509Extension(
- DERBoolean critical,
- DEROctetString value)
- {
- this.critical = critical.isTrue();
- this.value = value;
- }
-
- public X509Extension(
- boolean critical,
- DEROctetString value)
- {
- this.critical = critical;
- this.value = value;
- }
-
- public boolean isCritical()
- {
- return critical;
- }
-
- public DEROctetString getValue()
- {
- return value;
- }
-
- public int hashCode()
- {
- if (this.isCritical())
- {
- return this.getValue().hashCode();
- }
-
-
- return ~this.getValue().hashCode();
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof X509Extension))
- {
- return false;
- }
-
- X509Extension other = (X509Extension)o;
-
- return other.getValue().equals(this.getValue())
- && (other.isCritical() == this.isCritical());
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.util.*;
-
-import org.bouncycastle.asn1.*;
-
-public class X509Extensions
- implements DEREncodable
-{
- /**
- * Subject Key Identifier
- */
- public static final DERObjectIdentifier SubjectKeyIdentifier = new DERObjectIdentifier("2.5.29.14");
-
- /**
- * Key Usage
- */
- public static final DERObjectIdentifier KeyUsage = new DERObjectIdentifier("2.5.29.15");
-
- /**
- * Private Key Usage Period
- */
- public static final DERObjectIdentifier PrivateKeyUsagePeriod = new DERObjectIdentifier("2.5.29.16");
-
- /**
- * Subject Alternative Name
- */
- public static final DERObjectIdentifier SubjectAlternativeName = new DERObjectIdentifier("2.5.29.17");
-
- /**
- * Issuer Alternative Name
- */
- public static final DERObjectIdentifier IssuerAlternativeName = new DERObjectIdentifier("2.5.29.18");
-
- /**
- * Basic Constraints
- */
- public static final DERObjectIdentifier BasicConstraints = new DERObjectIdentifier("2.5.29.19");
-
- /**
- * CRL Number
- */
- public static final DERObjectIdentifier CRLNumber = new DERObjectIdentifier("2.5.29.20");
-
- /**
- * Reason code
- */
- public static final DERObjectIdentifier ReasonCode = new DERObjectIdentifier("2.5.29.21");
-
- /**
- * Hold Instruction Code
- */
- public static final DERObjectIdentifier InstructionCode = new DERObjectIdentifier("2.5.29.23");
-
- /**
- * Invalidity Date
- */
- public static final DERObjectIdentifier InvalidityDate = new DERObjectIdentifier("2.5.29.24");
-
- /**
- * Delta CRL indicator
- */
- public static final DERObjectIdentifier DeltaCRLIndicator = new DERObjectIdentifier("2.5.29.27");
-
- /**
- * Issuing Distribution Point
- */
- public static final DERObjectIdentifier IssuingDistributionPoint = new DERObjectIdentifier("2.5.29.28");
-
- /**
- * Certificate Issuer
- */
- public static final DERObjectIdentifier CertificateIssuer = new DERObjectIdentifier("2.5.29.29");
-
- /**
- * Name Constraints
- */
- public static final DERObjectIdentifier NameConstraints = new DERObjectIdentifier("2.5.29.30");
-
- /**
- * CRL Distribution Points
- */
- public static final DERObjectIdentifier CRLDistributionPoints = new DERObjectIdentifier("2.5.29.31");
-
- /**
- * Certificate Policies
- */
- public static final DERObjectIdentifier CertificatePolicies = new DERObjectIdentifier("2.5.29.32");
-
- /**
- * Policy Mappings
- */
- public static final DERObjectIdentifier PolicyMappings = new DERObjectIdentifier("2.5.29.33");
-
- /**
- * Authority Key Identifier
- */
- public static final DERObjectIdentifier AuthorityKeyIdentifier = new DERObjectIdentifier("2.5.29.35");
-
- /**
- * Policy Constraints
- */
- public static final DERObjectIdentifier PolicyConstraints = new DERObjectIdentifier("2.5.29.36");
-
- /**
- * Extended Key Usage
- */
- public static final DERObjectIdentifier ExtendedKeyUsage = new DERObjectIdentifier("2.5.29.37");
-
- private Hashtable extensions = new Hashtable();
- private Vector ordering = new Vector();
-
- public static X509Extensions getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static X509Extensions getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof X509Extensions)
- {
- return (X509Extensions)obj;
- }
-
- if (obj instanceof ASN1Sequence)
- {
- return new X509Extensions((ASN1Sequence)obj);
- }
-
- if (obj instanceof ASN1TaggedObject)
- {
- return getInstance(((ASN1TaggedObject)obj).getObject());
- }
-
- throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName());
- }
-
- /**
- * Constructor from DERConstructedSequence.
- *
- * the extensions are a list of constructed sequences, either with (OID, OctetString) or (OID, Boolean, OctetString)
- */
- public X509Extensions(
- ASN1Sequence seq)
- {
- Enumeration e = seq.getObjects();
-
- while (e.hasMoreElements())
- {
- ASN1Sequence s = (ASN1Sequence)e.nextElement();
- Enumeration e1 = s.getObjects();
-
- if (s.size() == 3)
- {
- extensions.put(s.getObjectAt(0), new X509Extension((DERBoolean)s.getObjectAt(1), (DEROctetString)s.getObjectAt(2)));
- }
- else
- {
- extensions.put(s.getObjectAt(0), new X509Extension(false, (DEROctetString)s.getObjectAt(1)));
- }
-
- ordering.addElement(s.getObjectAt(0));
- }
- }
-
- /**
- * constructor from a table of extensions.
- * <p>
- * it's is assumed the table contains OID/String pairs.
- */
- public X509Extensions(
- Hashtable extensions)
- {
- this(null, extensions);
- }
-
- /**
- * constructor from a table of extensions with ordering
- * <p>
- * it's is assumed the table contains OID/String pairs.
- */
- public X509Extensions(
- Vector ordering,
- Hashtable extensions)
- {
- Enumeration e;
-
- if (ordering == null)
- {
- e = extensions.keys();
- }
- else
- {
- e = ordering.elements();
- }
-
- while (e.hasMoreElements())
- {
- this.ordering.addElement(e.nextElement());
- }
-
- e = this.ordering.elements();
-
- while (e.hasMoreElements())
- {
- DERObjectIdentifier oid = (DERObjectIdentifier)e.nextElement();
- X509Extension ext = (X509Extension)extensions.get(oid);
-
- this.extensions.put(oid, ext);
- }
- }
-
- /**
- * return an Enumeration of the extension field's object ids.
- */
- public Enumeration oids()
- {
- return ordering.elements();
- }
-
- /**
- * return the extension represented by the object identifier
- * passed in.
- *
- * @return the extension if it's present, null otherwise.
- */
- public X509Extension getExtension(
- DERObjectIdentifier oid)
- {
- return (X509Extension)extensions.get(oid);
- }
-
- public DERObject getDERObject()
- {
- DEREncodableVector vec = new DEREncodableVector();
- Enumeration e = ordering.elements();
-
- while (e.hasMoreElements())
- {
- DERObjectIdentifier oid = (DERObjectIdentifier)e.nextElement();
- X509Extension ext = (X509Extension)extensions.get(oid);
- DEREncodableVector v = new DEREncodableVector();
-
- v.add(oid);
-
- if (ext.isCritical())
- {
- v.add(new DERBoolean(true));
- }
-
- v.add(ext.getValue());
-
- vec.add(new DERSequence(v));
- }
-
- return new DERSequence(vec);
- }
-
- public int hashCode()
- {
- Enumeration e = extensions.keys();
- int hashCode = 0;
-
- while (e.hasMoreElements())
- {
- Object o = e.nextElement();
-
- hashCode ^= o.hashCode();
- hashCode ^= extensions.get(o).hashCode();
- }
-
- return hashCode;
- }
-
- public boolean equals(
- Object o)
- {
- if (o == null || !(o instanceof X509Extensions))
- {
- return false;
- }
-
- X509Extensions other = (X509Extensions)o;
-
- Enumeration e1 = extensions.keys();
- Enumeration e2 = other.extensions.keys();
-
- while (e1.hasMoreElements() && e2.hasMoreElements())
- {
- Object o1 = e1.nextElement();
- Object o2 = e2.nextElement();
-
- if (!o1.equals(o2))
- {
- return false;
- }
- }
-
- if (e1.hasMoreElements() || e2.hasMoreElements())
- {
- return false;
- }
-
- return true;
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import java.util.*;
-
-import org.bouncycastle.asn1.*;
-
-public class X509Name
- implements DEREncodable
-{
- /**
- * country code - StringType(SIZE(2))
- */
- public static final DERObjectIdentifier C = new DERObjectIdentifier("2.5.4.6");
-
- /**
- * organization - StringType(SIZE(1..64))
- */
- public static final DERObjectIdentifier O = new DERObjectIdentifier("2.5.4.10");
-
- /**
- * organizational unit name - StringType(SIZE(1..64))
- */
- public static final DERObjectIdentifier OU = new DERObjectIdentifier("2.5.4.11");
-
- /**
- * Title
- */
- public static final DERObjectIdentifier T = new DERObjectIdentifier("2.5.4.12");
-
- /**
- * common name - StringType(SIZE(1..64))
- */
- public static final DERObjectIdentifier CN = new DERObjectIdentifier("2.5.4.3");
-
- /**
- * device serial number name - StringType(SIZE(1..64))
- */
- public static final DERObjectIdentifier SN = new DERObjectIdentifier("2.5.4.5");
-
- /**
- * locality name - StringType(SIZE(1..64))
- */
- public static final DERObjectIdentifier L = new DERObjectIdentifier("2.5.4.7");
-
- /**
- * state, or province name - StringType(SIZE(1..64))
- */
- public static final DERObjectIdentifier ST = new DERObjectIdentifier("2.5.4.8");
-
-
- /**
- * email address (RSA PKCS#9 extension) - IA5String
- * <p>
- * note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.
- */
- public static final DERObjectIdentifier EmailAddress = new DERObjectIdentifier("1.2.840.113549.1.9.1");
-
- /**
- * email address in Verisign certificates
- */
- public static final DERObjectIdentifier E = EmailAddress;
-
- /*
- * others...
- */
- public static final DERObjectIdentifier DC = new DERObjectIdentifier("0.9.2342.19200300.100.1.25");
-
- /**
- * LDAP User id.
- */
- public static final DERObjectIdentifier UID = new DERObjectIdentifier("0.9.2342.19200300.100.1.1");
-
- /**
- * look up table translating OID values into their common symbols.
- */
- public static Hashtable OIDLookUp = new Hashtable();
-
- /**
- * look up table translating common symbols into their OIDS.
- */
- public static Hashtable SymbolLookUp = new Hashtable();
-
- static
- {
- OIDLookUp.put(C, "C");
- OIDLookUp.put(O, "O");
- OIDLookUp.put(T, "T");
- OIDLookUp.put(OU, "OU");
- OIDLookUp.put(CN, "CN");
- OIDLookUp.put(L, "L");
- OIDLookUp.put(ST, "ST");
- OIDLookUp.put(SN, "SN");
- OIDLookUp.put(EmailAddress, "E");
- OIDLookUp.put(DC, "DC");
- OIDLookUp.put(UID, "UID");
-
- SymbolLookUp.put("c", C);
- SymbolLookUp.put("o", O);
- SymbolLookUp.put("t", T);
- SymbolLookUp.put("ou", OU);
- SymbolLookUp.put("cn", CN);
- SymbolLookUp.put("l", L);
- SymbolLookUp.put("st", ST);
- SymbolLookUp.put("sn", SN);
- SymbolLookUp.put("emailaddress", E);
- SymbolLookUp.put("dc", DC);
- SymbolLookUp.put("e", E);
- SymbolLookUp.put("uid", UID);
- }
-
- private Vector ordering = new Vector();
- private Vector values = new Vector();
- private ASN1Sequence seq;
-
- public static X509Name getInstance(
- ASN1TaggedObject obj,
- boolean explicit)
- {
- return getInstance(ASN1Sequence.getInstance(obj, explicit));
- }
-
- public static X509Name getInstance(
- Object obj)
- {
- if (obj == null || obj instanceof X509Name)
- {
- return (X509Name)obj;
- }
- else if (obj instanceof ASN1Sequence)
- {
- return new X509Name((ASN1Sequence)obj);
- }
-
- throw new IllegalArgumentException("unknown object in factory");
- }
-
- /**
- * Constructor from ASN1Sequence
- *
- * the principal will be a list of constructed sets, each containing an (OID, String) pair.
- */
- public X509Name(
- ASN1Sequence seq)
- {
- this.seq = seq;
-
- Enumeration e = seq.getObjects();
-
- while (e.hasMoreElements())
- {
- ASN1Set set = (ASN1Set)e.nextElement();
- ASN1Sequence s = (ASN1Sequence)set.getObjectAt(0);
-
- ordering.addElement(s.getObjectAt(0));
- values.addElement(((DERString)s.getObjectAt(1)).getString());
- }
- }
-
- /**
- * constructor from a table of attributes.
- * <p>
- * it's is assumed the table contains OID/String pairs, and the contents
- * of the table are copied into an internal table as part of the
- * construction process.
- * <p>
- * <b>Note:</b> if the name you are trying to generate should be
- * following a specific ordering, you should use the constructor
- * with the ordering specified below.
- */
- public X509Name(
- Hashtable attributes)
- {
- this(null, attributes);
- }
-
- /**
- * constructor from a table of attributes with ordering.
- * <p>
- * it's is assumed the table contains OID/String pairs, and the contents
- * of the table are copied into an internal table as part of the
- * construction process. The ordering vector should contain the OIDs
- * in the order they are meant to be encoded or printed in toString.
- */
- public X509Name(
- Vector ordering,
- Hashtable attributes)
- {
- if (ordering != null)
- {
- for (int i = 0; i != ordering.size(); i++)
- {
- this.ordering.addElement(ordering.elementAt(i));
- }
- }
- else
- {
- Enumeration e = attributes.keys();
-
- while (e.hasMoreElements())
- {
- this.ordering.addElement(e.nextElement());
- }
- }
-
- for (int i = 0; i != this.ordering.size(); i++)
- {
- DERObjectIdentifier oid = (DERObjectIdentifier)this.ordering.elementAt(i);
-
- if (OIDLookUp.get(oid) == null)
- {
- throw new IllegalArgumentException("Unknown object id - " + oid.getId() + " - passed to distinguished name");
- }
-
- if (attributes.get(oid) == null)
- {
- throw new IllegalArgumentException("No attribute for object id - " + oid.getId() + " - passed to distinguished name");
- }
-
- this.values.addElement(attributes.get(oid)); // copy the hash table
- }
- }
-
- /**
- * takes two vectors one of the oids and the other of the values.
- */
- public X509Name(
- Vector ordering,
- Vector values)
- {
- if (ordering.size() != values.size())
- {
- throw new IllegalArgumentException("ordering vector must be same length as values.");
- }
-
- for (int i = 0; i < ordering.size(); i++)
- {
- this.ordering.addElement(ordering.elementAt(i));
- this.values.addElement(values.elementAt(i));
- }
- }
-
- /**
- * takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
- * some such, converting it into an ordered set of name attributes.
- */
- public X509Name(
- String dirName)
- {
- X509NameTokenizer nTok = new X509NameTokenizer(dirName);
-
- while (nTok.hasMoreTokens())
- {
- String token = nTok.nextToken();
- int index = token.indexOf('=');
-
- if (index == -1)
- {
- throw new IllegalArgumentException("badly formated directory string");
- }
-
- String name = token.substring(0, index);
- String value = token.substring(index + 1);
- DERObjectIdentifier oid = null;
-
- if (name.toUpperCase().startsWith("OID."))
- {
- oid = new DERObjectIdentifier(name.substring(4));
- }
- else if (name.charAt(0) >= '0' && name.charAt(0) <= '9')
- {
- oid = new DERObjectIdentifier(name);
- }
- else
- {
- oid = (DERObjectIdentifier)SymbolLookUp.get(name.toLowerCase());
- if (oid == null)
- {
- throw new IllegalArgumentException("Unknown object id - " + name + " - passed to distinguished name");
- }
- }
-
- this.ordering.addElement(oid);
- this.values.addElement(value);
- }
- }
-
- /**
- * return false if we have characters out of the range of a printable
- * string, true otherwise.
- */
- private boolean canBePrintable(
- String str)
- {
- for (int i = str.length() - 1; i >= 0; i--)
- {
- if (str.charAt(i) > 0x007f)
- {
- return false;
- }
- }
-
- return true;
- }
-
- public DERObject getDERObject()
- {
- if (seq == null)
- {
- DEREncodableVector vec = new DEREncodableVector();
-
- for (int i = 0; i != ordering.size(); i++)
- {
- DEREncodableVector v = new DEREncodableVector();
- DERObjectIdentifier oid = (DERObjectIdentifier)ordering.elementAt(i);
-
- v.add(oid);
-
- String str = (String)values.elementAt(i);
-
- if (oid.equals(EmailAddress))
- {
- v.add(new DERIA5String(str));
- }
- else
- {
- if (canBePrintable(str))
- {
- v.add(new DERPrintableString(str));
- }
- else
- {
- v.add(new DERUTF8String(str));
- }
- }
-
- vec.add(new DERSet(new DERSequence(v)));
- }
-
- seq = new DERSequence(vec);
- }
-
- return seq;
- }
-
- /**
- * test for equality - note: case is ignored.
- */
- public boolean equals(Object _obj)
- {
- if (_obj == this)
- {
- return true;
- }
-
- if (_obj == null || !(_obj instanceof X509Name))
- {
- return false;
- }
-
- X509Name _oxn = (X509Name)_obj;
- int _orderingSize = ordering.size();
-
- if (_orderingSize != _oxn.ordering.size())
- {
- return false;
- }
-
- boolean[] _indexes = new boolean[_orderingSize];
-
- for(int i = 0; i < _orderingSize; i++)
- {
- boolean _found = false;
- String _oid = ((DERObjectIdentifier)ordering.elementAt(i)).getId();
- String _val = (String)values.elementAt(i);
-
- for(int j = 0; j < _orderingSize; j++)
- {
- if(_indexes[j] == true)
- {
- continue;
- }
-
- String _oOID = ((DERObjectIdentifier)_oxn.ordering.elementAt(j)).getId();
- String _oVal = (String)_oxn.values.elementAt(j);
-
- // was equalsIgnoreCase but MIDP doesn't like that.
- if(_oid.equals(_oOID) && _val.toLowerCase().equals(_oVal.toLowerCase()))
- {
- _indexes[j] = true;
- _found = true;
- break;
- }
-
- }
-
- if(!_found)
- {
- return false;
- }
- }
-
- return true;
- }
-
- public int hashCode()
- {
- ASN1Sequence seq = (ASN1Sequence)this.getDERObject();
- Enumeration e = seq.getObjects();
- int hashCode = 0;
-
- while (e.hasMoreElements())
- {
- hashCode ^= e.nextElement().hashCode();
- }
-
- return hashCode;
- }
-
- public String toString()
- {
- StringBuffer buf = new StringBuffer();
- boolean first = true;
- Enumeration e1 = ordering.elements();
- Enumeration e2 = values.elements();
-
- while (e1.hasMoreElements())
- {
- Object oid = e1.nextElement();
- String sym = (String)OIDLookUp.get(oid);
-
- if (first)
- {
- first = false;
- }
- else
- {
- buf.append(",");
- }
-
- if (sym != null)
- {
- buf.append(sym);
- }
- else
- {
- buf.append(((DERObjectIdentifier)oid).getId());
- }
-
- buf.append("=");
-
- int index = buf.length();
-
- buf.append((String)e2.nextElement());
-
- int end = buf.length();
-
- while (index != end)
- {
- if ((buf.charAt(index) == ',')
- || (buf.charAt(index) == '"')
- || (buf.charAt(index) == '\\')
- || (buf.charAt(index) == '+')
- || (buf.charAt(index) == '<')
- || (buf.charAt(index) == '>')
- || (buf.charAt(index) == ';'))
- {
- buf.insert(index, "\\");
- index++;
- end++;
- }
-
- index++;
- }
- }
-
- return buf.toString();
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-/**
- * class for breaking up an X500 Name into it's component tokens, ala
- * java.util.StringTokenizer. We need this class as some of the
- * lightweight Java environment don't support classes like
- * StringTokenizer.
- */
-public class X509NameTokenizer
-{
- private String oid;
- private int index;
- private StringBuffer buf = new StringBuffer();
-
- public X509NameTokenizer(
- String oid)
- {
- this.oid = oid;
- this.index = -1;
- }
-
- public boolean hasMoreTokens()
- {
- return (index != oid.length());
- }
-
- public String nextToken()
- {
- if (index == oid.length())
- {
- return null;
- }
-
- int end = index + 1;
- boolean quoted = false;
- boolean escaped = false;
-
- buf.setLength(0);
-
- while (end != oid.length())
- {
- char c = oid.charAt(end);
-
- if (c == '"')
- {
- if (!escaped)
- {
- quoted = !quoted;
- }
- else
- {
- buf.append(c);
- }
- escaped = false;
- }
- else
- {
- if (escaped || quoted)
- {
- buf.append(c);
- escaped = false;
- }
- else if (c == '\\')
- {
- escaped = true;
- }
- else if (c == ',')
- {
- break;
- }
- else
- {
- buf.append(c);
- }
- }
- end++;
- }
-
- index = end;
- return buf.toString().trim();
- }
-}
+++ /dev/null
-package org.bouncycastle.asn1.x509;
-
-import org.bouncycastle.asn1.DERObjectIdentifier;
-
-public interface X509ObjectIdentifiers
-{
- //
- // base id
- //
- static final String id = "2.5.4";
-
- static final DERObjectIdentifier commonName = new DERObjectIdentifier(id + ".3");
- static final DERObjectIdentifier countryName = new DERObjectIdentifier(id + ".6");
- static final DERObjectIdentifier localityName = new DERObjectIdentifier(id + ".7");
- static final DERObjectIdentifier stateOrProvinceName = new DERObjectIdentifier(id + ".8");
- static final DERObjectIdentifier organization = new DERObjectIdentifier(id + ".10");
- static final DERObjectIdentifier organizationalUnitName = new DERObjectIdentifier(id + ".11");
-
- // id-SHA1 OBJECT IDENTIFIER ::=
- // {iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } //
- static final DERObjectIdentifier id_SHA1 = new DERObjectIdentifier("1.3.14.3.2.26");
-
- //
- // ripemd160 OBJECT IDENTIFIER ::=
- // {iso(1) identified-organization(3) TeleTrust(36) algorithm(3) hashAlgorithm(2) RIPEMD-160(1)}
- //
- static final DERObjectIdentifier ripemd160 = new DERObjectIdentifier("1.3.36.3.2.1");
-
- //
- // ripemd160WithRSAEncryption OBJECT IDENTIFIER ::=
- // {iso(1) identified-organization(3) TeleTrust(36) algorithm(3) signatureAlgorithm(3) rsaSignature(1) rsaSignatureWithripemd160(2) }
- //
- static final DERObjectIdentifier ripemd160WithRSAEncryption = new DERObjectIdentifier("1.3.36.3.3.1.2");
-
-
- static final DERObjectIdentifier id_ea_rsa = new DERObjectIdentifier("2.5.8.1.1");
-}
-
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * base interface that a public/private key block cipher needs
- * to conform to.
- */
-public interface AsymmetricBlockCipher
-{
- /**
- * initialise the cipher.
- *
- * @param forEncryption if true the cipher is initialised for
- * encryption, if false for decryption.
- * @param param the key and other data required by the cipher.
- */
- public void init(boolean forEncryption, CipherParameters param);
-
- /**
- * returns the largest size an input block can be.
- *
- * @return maximum size for an input block.
- */
- public int getInputBlockSize();
-
- /**
- * returns the maximum size of the block produced by this cipher.
- *
- * @return maximum size of the output block produced by the cipher.
- */
- public int getOutputBlockSize();
-
- /**
- * process the block of len bytes stored in in from offset inOff.
- *
- * @param in the input data
- * @param inOff offset into the in array where the data starts
- * @param len the length of the block to be processed.
- * @return the resulting byte array of the encryption/decryption process.
- * @exception InvalidCipherTextException data decrypts improperly.
- * @exception DataLengthException the input data is too large for the cipher.
- */
- public byte[] processBlock(byte[] in, int inOff, int len)
- throws InvalidCipherTextException;
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * a holding class for public/private parameter pairs.
- */
-public class AsymmetricCipherKeyPair
-{
- private CipherParameters publicParam;
- private CipherParameters privateParam;
-
- /**
- * basic constructor.
- *
- * @param publicParam a public key parameters object.
- * @param privateParam the corresponding private key parameters.
- */
- public AsymmetricCipherKeyPair(
- CipherParameters publicParam,
- CipherParameters privateParam)
- {
- this.publicParam = publicParam;
- this.privateParam = privateParam;
- }
-
- /**
- * return the public key parameters.
- *
- * @return the public key parameters.
- */
- public CipherParameters getPublic()
- {
- return publicParam;
- }
-
- /**
- * return the private key parameters.
- *
- * @return the private key parameters.
- */
- public CipherParameters getPrivate()
- {
- return privateParam;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * interface that a public/private key pair generator should conform to.
- */
-public interface AsymmetricCipherKeyPairGenerator
-{
- /**
- * intialise the key pair generator.
- *
- * @param the parameters the key pair is to be initialised with.
- */
- public void init(KeyGenerationParameters param);
-
- /**
- * return an AsymmetricCipherKeyPair containing the generated keys.
- *
- * @return an AsymmetricCipherKeyPair containing the generated keys.
- */
- public AsymmetricCipherKeyPair generateKeyPair();
-}
-
+++ /dev/null
-package org.bouncycastle.crypto;
-
-import java.lang.IllegalStateException;
-
-/**
- * Block cipher engines are expected to conform to this interface.
- */
-public interface BlockCipher
-{
- /**
- * Initialise the cipher.
- *
- * @param forEncryption if true the cipher is initialised for
- * encryption, if false for decryption.
- * @param param the key and other data required by the cipher.
- * @exception IllegalArgumentException if the params argument is
- * inappropriate.
- */
- public void init(boolean forEncryption, CipherParameters params)
- throws IllegalArgumentException;
-
- /**
- * Return the name of the algorithm the cipher implements.
- *
- * @return the name of the algorithm the cipher implements.
- */
- public String getAlgorithmName();
-
- /**
- * Return the block size for this cipher (in bytes).
- *
- * @return the block size for this cipher in bytes.
- */
- public int getBlockSize();
-
- /**
- * Process one block of input from the array in and write it to
- * the out array.
- *
- * @param in the array containing the input data.
- * @param inOff offset into the in array the data starts at.
- * @param out the array the output data will be copied into.
- * @param outOff the offset into the out array the output will start at.
- * @exception DataLengthException if there isn't enough data in in, or
- * space in out.
- * @exception IllegalStateException if the cipher isn't initialised.
- * @return the number of bytes processed and produced.
- */
- public int processBlock(byte[] in, int inOff, byte[] out, int outOff)
- throws DataLengthException, IllegalStateException;
-
- /**
- * Reset the cipher. After resetting the cipher is in the same state
- * as it was after the last init (if there was one).
- */
- public void reset();
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-import java.security.SecureRandom;
-
-/**
- * The base class for symmetric, or secret, cipher key generators.
- */
-public class CipherKeyGenerator
-{
- protected SecureRandom random;
- protected int strength;
-
- /**
- * initialise the key generator.
- *
- * @param param the parameters to be used for key generation
- */
- public void init(
- KeyGenerationParameters param)
- {
- this.random = param.getRandom();
- this.strength = (param.getStrength() + 7) / 8;
- }
-
- /**
- * generate a secret key.
- *
- * @return a byte array containing the key value.
- */
- public byte[] generateKey()
- {
- byte[] key = new byte[strength];
-
- random.nextBytes(key);
-
- return key;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * all parameter classes implement this.
- */
-public interface CipherParameters
-{
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * the foundation class for the hard exceptions thrown by the crypto packages.
- */
-public class CryptoException
- extends Exception
-{
- /**
- * base constructor.
- */
- public CryptoException()
- {
- }
-
- /**
- * create a CryptoException with the given message.
- *
- * @param message the message to be carried with the exception.
- */
- public CryptoException(
- String message)
- {
- super(message);
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * this exception is thrown if a buffer that is meant to have output
- * copied into it turns out to be too short, or if we've been given
- * insufficient input. In general this exception will get thrown rather
- * than an ArrayOutOfBounds exception.
- */
-public class DataLengthException
- extends RuntimeCryptoException
-{
- /**
- * base constructor.
- */
- public DataLengthException()
- {
- }
-
- /**
- * create a DataLengthException with the given message.
- *
- * @param message the message to be carried with the exception.
- */
- public DataLengthException(
- String message)
- {
- super(message);
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * interface that a message digest conforms to.
- */
-public interface Digest
-{
- /**
- * return the algorithm name
- *
- * @return the algorithm name
- */
- public String getAlgorithmName();
-
- /**
- * return the size, in bytes, of the digest produced by this message digest.
- *
- * @return the size, in bytes, of the digest produced by this message digest.
- */
- public int getDigestSize();
-
- /**
- * update the message digest with a single byte.
- *
- * @param in the input byte to be entered.
- */
- public void update(byte in);
-
- /**
- * update the message digest with a block of bytes.
- *
- * @param in the byte array containing the data.
- * @param inOff the offset into the byte array where the data starts.
- * @param len the length of the data.
- */
- public void update(byte[] in, int inOff, int len);
-
- /**
- * close the digest, producing the final digest value. The doFinal
- * call leaves the digest reset.
- *
- * @param out the array the digest is to be copied into.
- * @param outOff the offset into the out array the digest is to start at.
- */
- public int doFinal(byte[] out, int outOff);
-
- /**
- * reset the digest back to it's initial state.
- */
- public void reset();
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * this exception is thrown whenever we find something we don't expect in a
- * message.
- */
-public class InvalidCipherTextException
- extends CryptoException
-{
- /**
- * base constructor.
- */
- public InvalidCipherTextException()
- {
- }
-
- /**
- * create a InvalidCipherTextException with the given message.
- *
- * @param message the message to be carried with the exception.
- */
- public InvalidCipherTextException(
- String message)
- {
- super(message);
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-import java.security.SecureRandom;
-
-/**
- * The base class for parameters to key generators.
- */
-public class KeyGenerationParameters
-{
- private SecureRandom random;
- private int strength;
-
- /**
- * initialise the generator with a source of randomness
- * and a strength (in bits).
- *
- * @param random the random byte source.
- * @param strength the size, in bits, of the keys we want to produce.
- */
- public KeyGenerationParameters(
- SecureRandom random,
- int strength)
- {
- this.random = random;
- this.strength = strength;
- }
-
- /**
- * return the random source associated with this
- * generator.
- *
- * @return the generators random source.
- */
- public SecureRandom getRandom()
- {
- return random;
- }
-
- /**
- * return the bit strength for keys produced by this generator,
- *
- * @return the strength of the keys this generator produces (in bits).
- */
- public int getStrength()
- {
- return strength;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * the foundation class for the exceptions thrown by the crypto packages.
- */
-public class RuntimeCryptoException
- extends RuntimeException
-{
- /**
- * base constructor.
- */
- public RuntimeCryptoException()
- {
- }
-
- /**
- * create a RuntimeCryptoException with the given message.
- *
- * @param message the message to be carried with the exception.
- */
- public RuntimeCryptoException(
- String message)
- {
- super(message);
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * a wrapper for block ciphers with a single byte block size, so that they
- * can be treated like stream ciphers.
- */
-public class StreamBlockCipher
- implements StreamCipher
-{
- private BlockCipher cipher;
-
- private byte[] oneByte = new byte[1];
-
- /**
- * basic constructor.
- *
- * @param cipher the block cipher to be wrapped.
- * @exception IllegalArgumentException if the cipher has a block size other than
- * one.
- */
- public StreamBlockCipher(
- BlockCipher cipher)
- {
- if (cipher.getBlockSize() != 1)
- {
- throw new IllegalArgumentException("block cipher block size != 1.");
- }
-
- this.cipher = cipher;
- }
-
- /**
- * initialise the underlying cipher.
- *
- * @param forEncryption true if we are setting up for encryption, false otherwise.
- * @param param the necessary parameters for the underlying cipher to be initialised.
- */
- public void init(
- boolean forEncryption,
- CipherParameters params)
- {
- cipher.init(forEncryption, params);
- }
-
- /**
- * return the name of the algorithm we are wrapping.
- *
- * @return the name of the algorithm we are wrapping.
- */
- public String getAlgorithmName()
- {
- return cipher.getAlgorithmName();
- }
-
- /**
- * encrypt/decrypt a single byte returning the result.
- *
- * @param in the byte to be processed.
- * @return the result of processing the input byte.
- */
- public byte returnByte(
- byte in)
- {
- oneByte[0] = in;
-
- cipher.processBlock(oneByte, 0, oneByte, 0);
-
- return oneByte[0];
- }
-
- /**
- * process a block of bytes from in putting the result into out.
- *
- * @param in the input byte array.
- * @param inOff the offset into the in array where the data to be processed starts.
- * @param len the number of bytes to be processed.
- * @param out the output buffer the processed bytes go into.
- * @param outOff the offset into the output byte array the processed data stars at.
- * @exception DataLengthException if the output buffer is too small.
- */
- public void processBytes(
- byte[] in,
- int inOff,
- int len,
- byte[] out,
- int outOff)
- throws DataLengthException
- {
- if (outOff + len > out.length)
- {
- throw new DataLengthException("output buffer too small in processBytes()");
- }
-
- for (int i = 0; i != len; i++)
- {
- cipher.processBlock(in, inOff + i, out, outOff + i);
- }
- }
-
- /**
- * reset the underlying cipher. This leaves it in the same state
- * it was at after the last init (if there was one).
- */
- public void reset()
- {
- cipher.reset();
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto;
-
-/**
- * the interface stream ciphers conform to.
- */
-public interface StreamCipher
-{
- /**
- * Initialise the cipher.
- *
- * @param forEncryption if true the cipher is initialised for
- * encryption, if false for decryption.
- * @param param the key and other data required by the cipher.
- * @exception IllegalArgumentException if the params argument is
- * inappropriate.
- */
- public void init(boolean forEncryption, CipherParameters params)
- throws IllegalArgumentException;
-
- /**
- * Return the name of the algorithm the cipher implements.
- *
- * @return the name of the algorithm the cipher implements.
- */
- public String getAlgorithmName();
-
- /**
- * encrypt/decrypt a single byte returning the result.
- *
- * @param in the byte to be processed.
- * @return the result of processing the input byte.
- */
- public byte returnByte(byte in);
-
- /**
- * process a block of bytes from in putting the result into out.
- *
- * @param in the input byte array.
- * @param inOff the offset into the in array where the data to be processed starts.
- * @param len the number of bytes to be processed.
- * @param out the output buffer the processed bytes go into.
- * @param outOff the offset into the output byte array the processed data stars at.
- * @exception DataLengthException if the output buffer is too small.
- */
- public void processBytes(byte[] in, int inOff, int len, byte[] out, int outOff)
- throws DataLengthException;
-
- /**
- * reset the cipher. This leaves it in the same state
- * it was at after the last init (if there was one).
- */
- public void reset();
-}
+++ /dev/null
-package org.bouncycastle.crypto.digests;
-
-import org.bouncycastle.crypto.Digest;
-
-/**
- * base implementation of MD4 family style digest as outlined in
- * "Handbook of Applied Cryptography", pages 344 - 347.
- */
-public abstract class GeneralDigest
- implements Digest
-{
- private byte[] xBuf;
- private int xBufOff;
-
- private long byteCount;
-
- /**
- * Standard constructor
- */
- protected GeneralDigest()
- {
- xBuf = new byte[4];
- xBufOff = 0;
- }
-
- /**
- * Copy constructor. We are using copy constructors in place
- * of the Object.clone() interface as this interface is not
- * supported by J2ME.
- */
- protected GeneralDigest(GeneralDigest t)
- {
- xBuf = new byte[t.xBuf.length];
- System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length);
-
- xBufOff = t.xBufOff;
- byteCount = t.byteCount;
- }
-
- public void update(
- byte in)
- {
- xBuf[xBufOff++] = in;
-
- if (xBufOff == xBuf.length)
- {
- processWord(xBuf, 0);
- xBufOff = 0;
- }
-
- byteCount++;
- }
-
- public void update(
- byte[] in,
- int inOff,
- int len)
- {
- //
- // fill the current word
- //
- while ((xBufOff != 0) && (len > 0))
- {
- update(in[inOff]);
-
- inOff++;
- len--;
- }
-
- //
- // process whole words.
- //
- while (len > xBuf.length)
- {
- processWord(in, inOff);
-
- inOff += xBuf.length;
- len -= xBuf.length;
- byteCount += xBuf.length;
- }
-
- //
- // load in the remainder.
- //
- while (len > 0)
- {
- update(in[inOff]);
-
- inOff++;
- len--;
- }
- }
-
- public void finish()
- {
- long bitLength = (byteCount << 3);
-
- //
- // add the pad bytes.
- //
- update((byte)128);
-
- while (xBufOff != 0)
- {
- update((byte)0);
- }
-
- processLength(bitLength);
-
- processBlock();
- }
-
- public void reset()
- {
- byteCount = 0;
-
- xBufOff = 0;
- for ( int i = 0; i < xBuf.length; i++ ) {
- xBuf[i] = 0;
- }
- }
-
- protected abstract void processWord(byte[] in, int inOff);
-
- protected abstract void processLength(long bitLength);
-
- protected abstract void processBlock();
-}
+++ /dev/null
-package org.bouncycastle.crypto.digests;
-
-import org.bouncycastle.crypto.Digest;
-/**
- * implementation of MD2
- * as outlined in RFC1319 by B.Kaliski from RSA Laboratories April 1992
- */
-public class MD2Digest
- implements Digest
-{
- private static final int DIGEST_LENGTH = 16;
-
- /* X buffer */
- private byte[] X = new byte[48];
- private int xOff;
- /* M buffer */
- private byte[] M = new byte[16];
- private int mOff;
- /* check sum */
- private byte[] C = new byte[16];
- private int COff;
-
- public MD2Digest()
- {
- reset();
- }
- public MD2Digest(MD2Digest t)
- {
- System.arraycopy(t.X, 0, X, 0, t.X.length);
- xOff = t.xOff;
- System.arraycopy(t.M, 0, M, 0, t.M.length);
- mOff = t.mOff;
- System.arraycopy(t.C, 0, C, 0, t.C.length);
- COff = t.COff;
- }
- /**
- * return the algorithm name
- *
- * @return the algorithm name
- */
- public String getAlgorithmName()
- {
- return "MD2";
- }
- /**
- * return the size, in bytes, of the digest produced by this message digest.
- *
- * @return the size, in bytes, of the digest produced by this message digest.
- */
- public int getDigestSize()
- {
- return DIGEST_LENGTH;
- }
- /**
- * close the digest, producing the final digest value. The doFinal
- * call leaves the digest reset.
- *
- * @param out the array the digest is to be copied into.
- * @param outOff the offset into the out array the digest is to start at.
- */
- public int doFinal(byte[] out, int outOff)
- {
- // add padding
- byte paddingByte = (byte)(M.length-mOff);
- for (int i=mOff;i<M.length;i++)
- {
- M[i] = paddingByte;
- }
- //do final check sum
- processCheckSum(M);
- // do final block process
- processBlock(M);
-
- processBlock(C);
-
- System.arraycopy(X,xOff,out,outOff,16);
-
- reset();
-
- return DIGEST_LENGTH;
- }
- /**
- * reset the digest back to it's initial state.
- */
- public void reset()
- {
- xOff = 0;
- for (int i = 0; i != X.length; i++)
- {
- X[i] = 0;
- }
- mOff = 0;
- for (int i = 0; i != M.length; i++)
- {
- M[i] = 0;
- }
- COff = 0;
- for (int i = 0; i != C.length; i++)
- {
- C[i] = 0;
- }
- }
- /**
- * update the message digest with a single byte.
- *
- * @param in the input byte to be entered.
- */
- public void update(byte in)
- {
- M[mOff++] = in;
-
- if (mOff == 16)
- {
- processCheckSum(M);
- processBlock(M);
- mOff = 0;
- }
- }
-
- /**
- * update the message digest with a block of bytes.
- *
- * @param in the byte array containing the data.
- * @param inOff the offset into the byte array where the data starts.
- * @param len the length of the data.
- */
- public void update(byte[] in, int inOff, int len)
- {
- //
- // fill the current word
- //
- while ((mOff != 0) && (len > 0))
- {
- update(in[inOff]);
- inOff++;
- len--;
- }
-
- //
- // process whole words.
- //
- while (len > 16)
- {
- System.arraycopy(in,inOff,M,0,16);
- processCheckSum(M);
- processBlock(M);
- len -= 16;
- inOff += 16;
- }
-
- //
- // load in the remainder.
- //
- while (len > 0)
- {
- update(in[inOff]);
- inOff++;
- len--;
- }
- }
- protected void processCheckSum(byte[] m)
- {
- int L = C[15];
- for (int i=0;i<16;i++)
- {
- C[i] ^= S[(m[i] ^ L) & 0xff];
- L = C[i];
- }
- }
- protected void processBlock(byte[] m)
- {
- for (int i=0;i<16;i++)
- {
- X[i+16] = m[i];
- X[i+32] = (byte)(m[i] ^ X[i]);
- }
- // encrypt block
- int t = 0;
-
- for (int j=0;j<18;j++)
- {
- for (int k=0;k<48;k++)
- {
- t = X[k] ^= S[t];
- t = t & 0xff;
- }
- t = (t + j)%256;
- }
- }
- // 256-byte random permutation constructed from the digits of PI
- private static final byte[] S = {
- (byte)41,(byte)46,(byte)67,(byte)201,(byte)162,(byte)216,(byte)124,
- (byte)1,(byte)61,(byte)54,(byte)84,(byte)161,(byte)236,(byte)240,
- (byte)6,(byte)19,(byte)98,(byte)167,(byte)5,(byte)243,(byte)192,
- (byte)199,(byte)115,(byte)140,(byte)152,(byte)147,(byte)43,(byte)217,
- (byte)188,(byte)76,(byte)130,(byte)202,(byte)30,(byte)155,(byte)87,
- (byte)60,(byte)253,(byte)212,(byte)224,(byte)22,(byte)103,(byte)66,
- (byte)111,(byte)24,(byte)138,(byte)23,(byte)229,(byte)18,(byte)190,
- (byte)78,(byte)196,(byte)214,(byte)218,(byte)158,(byte)222,(byte)73,
- (byte)160,(byte)251,(byte)245,(byte)142,(byte)187,(byte)47,(byte)238,
- (byte)122,(byte)169,(byte)104,(byte)121,(byte)145,(byte)21,(byte)178,
- (byte)7,(byte)63,(byte)148,(byte)194,(byte)16,(byte)137,(byte)11,
- (byte)34,(byte)95,(byte)33,(byte)128,(byte)127,(byte)93,(byte)154,
- (byte)90,(byte)144,(byte)50,(byte)39,(byte)53,(byte)62,(byte)204,
- (byte)231,(byte)191,(byte)247,(byte)151,(byte)3,(byte)255,(byte)25,
- (byte)48,(byte)179,(byte)72,(byte)165,(byte)181,(byte)209,(byte)215,
- (byte)94,(byte)146,(byte)42,(byte)172,(byte)86,(byte)170,(byte)198,
- (byte)79,(byte)184,(byte)56,(byte)210,(byte)150,(byte)164,(byte)125,
- (byte)182,(byte)118,(byte)252,(byte)107,(byte)226,(byte)156,(byte)116,
- (byte)4,(byte)241,(byte)69,(byte)157,(byte)112,(byte)89,(byte)100,
- (byte)113,(byte)135,(byte)32,(byte)134,(byte)91,(byte)207,(byte)101,
- (byte)230,(byte)45,(byte)168,(byte)2,(byte)27,(byte)96,(byte)37,
- (byte)173,(byte)174,(byte)176,(byte)185,(byte)246,(byte)28,(byte)70,
- (byte)97,(byte)105,(byte)52,(byte)64,(byte)126,(byte)15,(byte)85,
- (byte)71,(byte)163,(byte)35,(byte)221,(byte)81,(byte)175,(byte)58,
- (byte)195,(byte)92,(byte)249,(byte)206,(byte)186,(byte)197,(byte)234,
- (byte)38,(byte)44,(byte)83,(byte)13,(byte)110,(byte)133,(byte)40,
- (byte)132, 9,(byte)211,(byte)223,(byte)205,(byte)244,(byte)65,
- (byte)129,(byte)77,(byte)82,(byte)106,(byte)220,(byte)55,(byte)200,
- (byte)108,(byte)193,(byte)171,(byte)250,(byte)36,(byte)225,(byte)123,
- (byte)8,(byte)12,(byte)189,(byte)177,(byte)74,(byte)120,(byte)136,
- (byte)149,(byte)139,(byte)227,(byte)99,(byte)232,(byte)109,(byte)233,
- (byte)203,(byte)213,(byte)254,(byte)59,(byte)0,(byte)29,(byte)57,
- (byte)242,(byte)239,(byte)183,(byte)14,(byte)102,(byte)88,(byte)208,
- (byte)228,(byte)166,(byte)119,(byte)114,(byte)248,(byte)235,(byte)117,
- (byte)75,(byte)10,(byte)49,(byte)68,(byte)80,(byte)180,(byte)143,
- (byte)237,(byte)31,(byte)26,(byte)219,(byte)153,(byte)141,(byte)51,
- (byte)159,(byte)17,(byte)131,(byte)20
- };
-}
+++ /dev/null
-package org.bouncycastle.crypto.digests;
-
-/**
- * implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for
- * Computer Science and RSA Data Security, Inc.
- * <p>
- * <b>NOTE</b>: This algorithm is only included for backwards compatability
- * with legacy applications, it's not secure, don't use it for anything new!
- */
-public class MD4Digest
- extends GeneralDigest
-{
- private static final int DIGEST_LENGTH = 16;
-
- private int H1, H2, H3, H4; // IV's
-
- private int[] X = new int[16];
- private int xOff;
-
- /**
- * Standard constructor
- */
- public MD4Digest()
- {
- reset();
- }
-
- /**
- * Copy constructor. This will copy the state of the provided
- * message digest.
- */
- public MD4Digest(MD4Digest t)
- {
- super(t);
-
- H1 = t.H1;
- H2 = t.H2;
- H3 = t.H3;
- H4 = t.H4;
-
- System.arraycopy(t.X, 0, X, 0, t.X.length);
- xOff = t.xOff;
- }
-
- public String getAlgorithmName()
- {
- return "MD4";
- }
-
- public int getDigestSize()
- {
- return DIGEST_LENGTH;
- }
-
- protected void processWord(
- byte[] in,
- int inOff)
- {
- X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8)
- | ((in[inOff + 2] & 0xff) << 16) | ((in[inOff + 3] & 0xff) << 24);
-
- if (xOff == 16)
- {
- processBlock();
- }
- }
-
- protected void processLength(
- long bitLength)
- {
- if (xOff > 14)
- {
- processBlock();
- }
-
- X[14] = (int)(bitLength & 0xffffffff);
- X[15] = (int)(bitLength >>> 32);
- }
-
- private void unpackWord(
- int word,
- byte[] out,
- int outOff)
- {
- out[outOff] = (byte)word;
- out[outOff + 1] = (byte)(word >>> 8);
- out[outOff + 2] = (byte)(word >>> 16);
- out[outOff + 3] = (byte)(word >>> 24);
- }
-
- public int doFinal(
- byte[] out,
- int outOff)
- {
- finish();
-
- unpackWord(H1, out, outOff);
- unpackWord(H2, out, outOff + 4);
- unpackWord(H3, out, outOff + 8);
- unpackWord(H4, out, outOff + 12);
-
- reset();
-
- return DIGEST_LENGTH;
- }
-
- /**
- * reset the chaining variables to the IV values.
- */
- public void reset()
- {
- super.reset();
-
- H1 = 0x67452301;
- H2 = 0xefcdab89;
- H3 = 0x98badcfe;
- H4 = 0x10325476;
-
- xOff = 0;
-
- for (int i = 0; i != X.length; i++)
- {
- X[i] = 0;
- }
- }
-
- //
- // round 1 left rotates
- //
- private static final int S11 = 3;
- private static final int S12 = 7;
- private static final int S13 = 11;
- private static final int S14 = 19;
-
- //
- // round 2 left rotates
- //
- private static final int S21 = 3;
- private static final int S22 = 5;
- private static final int S23 = 9;
- private static final int S24 = 13;
-
- //
- // round 3 left rotates
- //
- private static final int S31 = 3;
- private static final int S32 = 9;
- private static final int S33 = 11;
- private static final int S34 = 15;
-
- /*
- * rotate int x left n bits.
- */
- private int rotateLeft(
- int x,
- int n)
- {
- return (x << n) | (x >>> (32 - n));
- }
-
- /*
- * F, G, H and I are the basic MD4 functions.
- */
- private int F(
- int u,
- int v,
- int w)
- {
- return (u & v) | (~u & w);
- }
-
- private int G(
- int u,
- int v,
- int w)
- {
- return (u & v) | (u & w) | (v & w);
- }
-
- private int H(
- int u,
- int v,
- int w)
- {
- return u ^ v ^ w;
- }
-
- protected void processBlock()
- {
- int a = H1;
- int b = H2;
- int c = H3;
- int d = H4;
-
- //
- // Round 1 - F cycle, 16 times.
- //
- a = rotateLeft((a + F(b, c, d) + X[ 0]), S11);
- d = rotateLeft((d + F(a, b, c) + X[ 1]), S12);
- c = rotateLeft((c + F(d, a, b) + X[ 2]), S13);
- b = rotateLeft((b + F(c, d, a) + X[ 3]), S14);
- a = rotateLeft((a + F(b, c, d) + X[ 4]), S11);
- d = rotateLeft((d + F(a, b, c) + X[ 5]), S12);
- c = rotateLeft((c + F(d, a, b) + X[ 6]), S13);
- b = rotateLeft((b + F(c, d, a) + X[ 7]), S14);
- a = rotateLeft((a + F(b, c, d) + X[ 8]), S11);
- d = rotateLeft((d + F(a, b, c) + X[ 9]), S12);
- c = rotateLeft((c + F(d, a, b) + X[10]), S13);
- b = rotateLeft((b + F(c, d, a) + X[11]), S14);
- a = rotateLeft((a + F(b, c, d) + X[12]), S11);
- d = rotateLeft((d + F(a, b, c) + X[13]), S12);
- c = rotateLeft((c + F(d, a, b) + X[14]), S13);
- b = rotateLeft((b + F(c, d, a) + X[15]), S14);
-
- //
- // Round 2 - G cycle, 16 times.
- //
- a = rotateLeft((a + G(b, c, d) + X[ 0] + 0x5a827999), S21);
- d = rotateLeft((d + G(a, b, c) + X[ 4] + 0x5a827999), S22);
- c = rotateLeft((c + G(d, a, b) + X[ 8] + 0x5a827999), S23);
- b = rotateLeft((b + G(c, d, a) + X[12] + 0x5a827999), S24);
- a = rotateLeft((a + G(b, c, d) + X[ 1] + 0x5a827999), S21);
- d = rotateLeft((d + G(a, b, c) + X[ 5] + 0x5a827999), S22);
- c = rotateLeft((c + G(d, a, b) + X[ 9] + 0x5a827999), S23);
- b = rotateLeft((b + G(c, d, a) + X[13] + 0x5a827999), S24);
- a = rotateLeft((a + G(b, c, d) + X[ 2] + 0x5a827999), S21);
- d = rotateLeft((d + G(a, b, c) + X[ 6] + 0x5a827999), S22);
- c = rotateLeft((c + G(d, a, b) + X[10] + 0x5a827999), S23);
- b = rotateLeft((b + G(c, d, a) + X[14] + 0x5a827999), S24);
- a = rotateLeft((a + G(b, c, d) + X[ 3] + 0x5a827999), S21);
- d = rotateLeft((d + G(a, b, c) + X[ 7] + 0x5a827999), S22);
- c = rotateLeft((c + G(d, a, b) + X[11] + 0x5a827999), S23);
- b = rotateLeft((b + G(c, d, a) + X[15] + 0x5a827999), S24);
-
- //
- // Round 3 - H cycle, 16 times.
- //
- a = rotateLeft((a + H(b, c, d) + X[ 0] + 0x6ed9eba1), S31);
- d = rotateLeft((d + H(a, b, c) + X[ 8] + 0x6ed9eba1), S32);
- c = rotateLeft((c + H(d, a, b) + X[ 4] + 0x6ed9eba1), S33);
- b = rotateLeft((b + H(c, d, a) + X[12] + 0x6ed9eba1), S34);
- a = rotateLeft((a + H(b, c, d) + X[ 2] + 0x6ed9eba1), S31);
- d = rotateLeft((d + H(a, b, c) + X[10] + 0x6ed9eba1), S32);
- c = rotateLeft((c + H(d, a, b) + X[ 6] + 0x6ed9eba1), S33);
- b = rotateLeft((b + H(c, d, a) + X[14] + 0x6ed9eba1), S34);
- a = rotateLeft((a + H(b, c, d) + X[ 1] + 0x6ed9eba1), S31);
- d = rotateLeft((d + H(a, b, c) + X[ 9] + 0x6ed9eba1), S32);
- c = rotateLeft((c + H(d, a, b) + X[ 5] + 0x6ed9eba1), S33);
- b = rotateLeft((b + H(c, d, a) + X[13] + 0x6ed9eba1), S34);
- a = rotateLeft((a + H(b, c, d) + X[ 3] + 0x6ed9eba1), S31);
- d = rotateLeft((d + H(a, b, c) + X[11] + 0x6ed9eba1), S32);
- c = rotateLeft((c + H(d, a, b) + X[ 7] + 0x6ed9eba1), S33);
- b = rotateLeft((b + H(c, d, a) + X[15] + 0x6ed9eba1), S34);
-
- H1 += a;
- H2 += b;
- H3 += c;
- H4 += d;
-
- //
- // reset the offset and clean out the word buffer.
- //
- xOff = 0;
- for (int i = 0; i != X.length; i++)
- {
- X[i] = 0;
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.digests;
-
-/**
- * implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
- */
-public class MD5Digest
- extends GeneralDigest
-{
- private static final int DIGEST_LENGTH = 16;
-
- private int H1, H2, H3, H4; // IV's
-
- private int[] X = new int[16];
- private int xOff;
-
- /**
- * Standard constructor
- */
- public MD5Digest()
- {
- reset();
- }
-
- /**
- * Copy constructor. This will copy the state of the provided
- * message digest.
- */
- public MD5Digest(MD5Digest t)
- {
- super(t);
-
- H1 = t.H1;
- H2 = t.H2;
- H3 = t.H3;
- H4 = t.H4;
-
- System.arraycopy(t.X, 0, X, 0, t.X.length);
- xOff = t.xOff;
- }
-
- public String getAlgorithmName()
- {
- return "MD5";
- }
-
- public int getDigestSize()
- {
- return DIGEST_LENGTH;
- }
-
- protected void processWord(
- byte[] in,
- int inOff)
- {
- X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8)
- | ((in[inOff + 2] & 0xff) << 16) | ((in[inOff + 3] & 0xff) << 24);
-
- if (xOff == 16)
- {
- processBlock();
- }
- }
-
- protected void processLength(
- long bitLength)
- {
- if (xOff > 14)
- {
- processBlock();
- }
-
- X[14] = (int)(bitLength & 0xffffffff);
- X[15] = (int)(bitLength >>> 32);
- }
-
- private void unpackWord(
- int word,
- byte[] out,
- int outOff)
- {
- out[outOff] = (byte)word;
- out[outOff + 1] = (byte)(word >>> 8);
- out[outOff + 2] = (byte)(word >>> 16);
- out[outOff + 3] = (byte)(word >>> 24);
- }
-
- public int doFinal(
- byte[] out,
- int outOff)
- {
- finish();
-
- unpackWord(H1, out, outOff);
- unpackWord(H2, out, outOff + 4);
- unpackWord(H3, out, outOff + 8);
- unpackWord(H4, out, outOff + 12);
-
- reset();
-
- return DIGEST_LENGTH;
- }
-
- /**
- * reset the chaining variables to the IV values.
- */
- public void reset()
- {
- super.reset();
-
- H1 = 0x67452301;
- H2 = 0xefcdab89;
- H3 = 0x98badcfe;
- H4 = 0x10325476;
-
- xOff = 0;
-
- for (int i = 0; i != X.length; i++)
- {
- X[i] = 0;
- }
- }
-
- //
- // round 1 left rotates
- //
- private static final int S11 = 7;
- private static final int S12 = 12;
- private static final int S13 = 17;
- private static final int S14 = 22;
-
- //
- // round 2 left rotates
- //
- private static final int S21 = 5;
- private static final int S22 = 9;
- private static final int S23 = 14;
- private static final int S24 = 20;
-
- //
- // round 3 left rotates
- //
- private static final int S31 = 4;
- private static final int S32 = 11;
- private static final int S33 = 16;
- private static final int S34 = 23;
-
- //
- // round 4 left rotates
- //
- private static final int S41 = 6;
- private static final int S42 = 10;
- private static final int S43 = 15;
- private static final int S44 = 21;
-
- /*
- * rotate int x left n bits.
- */
- private int rotateLeft(
- int x,
- int n)
- {
- return (x << n) | (x >>> (32 - n));
- }
-
- /*
- * F, G, H and I are the basic MD5 functions.
- */
- private int F(
- int u,
- int v,
- int w)
- {
- return (u & v) | (~u & w);
- }
-
- private int G(
- int u,
- int v,
- int w)
- {
- return (u & w) | (v & ~w);
- }
-
- private int H(
- int u,
- int v,
- int w)
- {
- return u ^ v ^ w;
- }
-
- private int K(
- int u,
- int v,
- int w)
- {
- return v ^ (u | ~w);
- }
-
- protected void processBlock()
- {
- int a = H1;
- int b = H2;
- int c = H3;
- int d = H4;
-
- //
- // Round 1 - F cycle, 16 times.
- //
- a = rotateLeft((a + F(b, c, d) + X[ 0] + 0xd76aa478), S11) + b;
- d = rotateLeft((d + F(a, b, c) + X[ 1] + 0xe8c7b756), S12) + a;
- c = rotateLeft((c + F(d, a, b) + X[ 2] + 0x242070db), S13) + d;
- b = rotateLeft((b + F(c, d, a) + X[ 3] + 0xc1bdceee), S14) + c;
- a = rotateLeft((a + F(b, c, d) + X[ 4] + 0xf57c0faf), S11) + b;
- d = rotateLeft((d + F(a, b, c) + X[ 5] + 0x4787c62a), S12) + a;
- c = rotateLeft((c + F(d, a, b) + X[ 6] + 0xa8304613), S13) + d;
- b = rotateLeft((b + F(c, d, a) + X[ 7] + 0xfd469501), S14) + c;
- a = rotateLeft((a + F(b, c, d) + X[ 8] + 0x698098d8), S11) + b;
- d = rotateLeft((d + F(a, b, c) + X[ 9] + 0x8b44f7af), S12) + a;
- c = rotateLeft((c + F(d, a, b) + X[10] + 0xffff5bb1), S13) + d;
- b = rotateLeft((b + F(c, d, a) + X[11] + 0x895cd7be), S14) + c;
- a = rotateLeft((a + F(b, c, d) + X[12] + 0x6b901122), S11) + b;
- d = rotateLeft((d + F(a, b, c) + X[13] + 0xfd987193), S12) + a;
- c = rotateLeft((c + F(d, a, b) + X[14] + 0xa679438e), S13) + d;
- b = rotateLeft((b + F(c, d, a) + X[15] + 0x49b40821), S14) + c;
-
- //
- // Round 2 - G cycle, 16 times.
- //
- a = rotateLeft((a + G(b, c, d) + X[ 1] + 0xf61e2562), S21) + b;
- d = rotateLeft((d + G(a, b, c) + X[ 6] + 0xc040b340), S22) + a;
- c = rotateLeft((c + G(d, a, b) + X[11] + 0x265e5a51), S23) + d;
- b = rotateLeft((b + G(c, d, a) + X[ 0] + 0xe9b6c7aa), S24) + c;
- a = rotateLeft((a + G(b, c, d) + X[ 5] + 0xd62f105d), S21) + b;
- d = rotateLeft((d + G(a, b, c) + X[10] + 0x02441453), S22) + a;
- c = rotateLeft((c + G(d, a, b) + X[15] + 0xd8a1e681), S23) + d;
- b = rotateLeft((b + G(c, d, a) + X[ 4] + 0xe7d3fbc8), S24) + c;
- a = rotateLeft((a + G(b, c, d) + X[ 9] + 0x21e1cde6), S21) + b;
- d = rotateLeft((d + G(a, b, c) + X[14] + 0xc33707d6), S22) + a;
- c = rotateLeft((c + G(d, a, b) + X[ 3] + 0xf4d50d87), S23) + d;
- b = rotateLeft((b + G(c, d, a) + X[ 8] + 0x455a14ed), S24) + c;
- a = rotateLeft((a + G(b, c, d) + X[13] + 0xa9e3e905), S21) + b;
- d = rotateLeft((d + G(a, b, c) + X[ 2] + 0xfcefa3f8), S22) + a;
- c = rotateLeft((c + G(d, a, b) + X[ 7] + 0x676f02d9), S23) + d;
- b = rotateLeft((b + G(c, d, a) + X[12] + 0x8d2a4c8a), S24) + c;
-
- //
- // Round 3 - H cycle, 16 times.
- //
- a = rotateLeft((a + H(b, c, d) + X[ 5] + 0xfffa3942), S31) + b;
- d = rotateLeft((d + H(a, b, c) + X[ 8] + 0x8771f681), S32) + a;
- c = rotateLeft((c + H(d, a, b) + X[11] + 0x6d9d6122), S33) + d;
- b = rotateLeft((b + H(c, d, a) + X[14] + 0xfde5380c), S34) + c;
- a = rotateLeft((a + H(b, c, d) + X[ 1] + 0xa4beea44), S31) + b;
- d = rotateLeft((d + H(a, b, c) + X[ 4] + 0x4bdecfa9), S32) + a;
- c = rotateLeft((c + H(d, a, b) + X[ 7] + 0xf6bb4b60), S33) + d;
- b = rotateLeft((b + H(c, d, a) + X[10] + 0xbebfbc70), S34) + c;
- a = rotateLeft((a + H(b, c, d) + X[13] + 0x289b7ec6), S31) + b;
- d = rotateLeft((d + H(a, b, c) + X[ 0] + 0xeaa127fa), S32) + a;
- c = rotateLeft((c + H(d, a, b) + X[ 3] + 0xd4ef3085), S33) + d;
- b = rotateLeft((b + H(c, d, a) + X[ 6] + 0x04881d05), S34) + c;
- a = rotateLeft((a + H(b, c, d) + X[ 9] + 0xd9d4d039), S31) + b;
- d = rotateLeft((d + H(a, b, c) + X[12] + 0xe6db99e5), S32) + a;
- c = rotateLeft((c + H(d, a, b) + X[15] + 0x1fa27cf8), S33) + d;
- b = rotateLeft((b + H(c, d, a) + X[ 2] + 0xc4ac5665), S34) + c;
-
- //
- // Round 4 - K cycle, 16 times.
- //
- a = rotateLeft((a + K(b, c, d) + X[ 0] + 0xf4292244), S41) + b;
- d = rotateLeft((d + K(a, b, c) + X[ 7] + 0x432aff97), S42) + a;
- c = rotateLeft((c + K(d, a, b) + X[14] + 0xab9423a7), S43) + d;
- b = rotateLeft((b + K(c, d, a) + X[ 5] + 0xfc93a039), S44) + c;
- a = rotateLeft((a + K(b, c, d) + X[12] + 0x655b59c3), S41) + b;
- d = rotateLeft((d + K(a, b, c) + X[ 3] + 0x8f0ccc92), S42) + a;
- c = rotateLeft((c + K(d, a, b) + X[10] + 0xffeff47d), S43) + d;
- b = rotateLeft((b + K(c, d, a) + X[ 1] + 0x85845dd1), S44) + c;
- a = rotateLeft((a + K(b, c, d) + X[ 8] + 0x6fa87e4f), S41) + b;
- d = rotateLeft((d + K(a, b, c) + X[15] + 0xfe2ce6e0), S42) + a;
- c = rotateLeft((c + K(d, a, b) + X[ 6] + 0xa3014314), S43) + d;
- b = rotateLeft((b + K(c, d, a) + X[13] + 0x4e0811a1), S44) + c;
- a = rotateLeft((a + K(b, c, d) + X[ 4] + 0xf7537e82), S41) + b;
- d = rotateLeft((d + K(a, b, c) + X[11] + 0xbd3af235), S42) + a;
- c = rotateLeft((c + K(d, a, b) + X[ 2] + 0x2ad7d2bb), S43) + d;
- b = rotateLeft((b + K(c, d, a) + X[ 9] + 0xeb86d391), S44) + c;
-
- H1 += a;
- H2 += b;
- H3 += c;
- H4 += d;
-
- //
- // reset the offset and clean out the word buffer.
- //
- xOff = 0;
- for (int i = 0; i != X.length; i++)
- {
- X[i] = 0;
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.digests;
-
-/**
- * implementation of SHA-1 as outlined in "Handbook of Applied Cryptography", pages 346 - 349.
- *
- * It is interesting to ponder why the, apart from the extra IV, the other difference here from MD5
- * is the "endienness" of the word processing!
- */
-public class SHA1Digest
- extends GeneralDigest
-{
- private static final int DIGEST_LENGTH = 20;
-
- private int H1, H2, H3, H4, H5;
-
- private int[] X = new int[80];
- private int xOff;
-
- /**
- * Standard constructor
- */
- public SHA1Digest()
- {
- reset();
- }
-
- /**
- * Copy constructor. This will copy the state of the provided
- * message digest.
- */
- public SHA1Digest(SHA1Digest t)
- {
- super(t);
-
- H1 = t.H1;
- H2 = t.H2;
- H3 = t.H3;
- H4 = t.H4;
- H5 = t.H5;
-
- System.arraycopy(t.X, 0, X, 0, t.X.length);
- xOff = t.xOff;
- }
-
- public String getAlgorithmName()
- {
- return "SHA-1";
- }
-
- public int getDigestSize()
- {
- return DIGEST_LENGTH;
- }
-
- protected void processWord(
- byte[] in,
- int inOff)
- {
- X[xOff++] = ((in[inOff] & 0xff) << 24) | ((in[inOff + 1] & 0xff) << 16)
- | ((in[inOff + 2] & 0xff) << 8) | ((in[inOff + 3] & 0xff));
-
- if (xOff == 16)
- {
- processBlock();
- }
- }
-
- private void unpackWord(
- int word,
- byte[] out,
- int outOff)
- {
- out[outOff] = (byte)(word >>> 24);
- out[outOff + 1] = (byte)(word >>> 16);
- out[outOff + 2] = (byte)(word >>> 8);
- out[outOff + 3] = (byte)word;
- }
-
- protected void processLength(
- long bitLength)
- {
- if (xOff > 14)
- {
- processBlock();
- }
-
- X[14] = (int)(bitLength >>> 32);
- X[15] = (int)(bitLength & 0xffffffff);
- }
-
- public int doFinal(
- byte[] out,
- int outOff)
- {
- finish();
-
- unpackWord(H1, out, outOff);
- unpackWord(H2, out, outOff + 4);
- unpackWord(H3, out, outOff + 8);
- unpackWord(H4, out, outOff + 12);
- unpackWord(H5, out, outOff + 16);
-
- reset();
-
- return DIGEST_LENGTH;
- }
-
- /**
- * reset the chaining variables
- */
- public void reset()
- {
- super.reset();
-
- H1 = 0x67452301;
- H2 = 0xefcdab89;
- H3 = 0x98badcfe;
- H4 = 0x10325476;
- H5 = 0xc3d2e1f0;
-
- xOff = 0;
- for (int i = 0; i != X.length; i++)
- {
- X[i] = 0;
- }
- }
-
- //
- // Additive constants
- //
- private static final int Y1 = 0x5a827999;
- private static final int Y2 = 0x6ed9eba1;
- private static final int Y3 = 0x8f1bbcdc;
- private static final int Y4 = 0xca62c1d6;
-
- private int f(
- int u,
- int v,
- int w)
- {
- return ((u & v) | ((~u) & w));
- }
-
- private int h(
- int u,
- int v,
- int w)
- {
- return (u ^ v ^ w);
- }
-
- private int g(
- int u,
- int v,
- int w)
- {
- return ((u & v) | (u & w) | (v & w));
- }
-
- private int rotateLeft(
- int x,
- int n)
- {
- return (x << n) | (x >>> (32 - n));
- }
-
- protected void processBlock()
- {
- //
- // expand 16 word block into 80 word block.
- //
- for (int i = 16; i <= 79; i++)
- {
- X[i] = rotateLeft((X[i - 3] ^ X[i - 8] ^ X[i - 14] ^ X[i - 16]), 1);
- }
-
- //
- // set up working variables.
- //
- int A = H1;
- int B = H2;
- int C = H3;
- int D = H4;
- int E = H5;
-
- //
- // round 1
- //
- for (int j = 0; j <= 19; j++)
- {
- int t = rotateLeft(A, 5) + f(B, C, D) + E + X[j] + Y1;
-
- E = D;
- D = C;
- C = rotateLeft(B, 30);
- B = A;
- A = t;
- }
-
- //
- // round 2
- //
- for (int j = 20; j <= 39; j++)
- {
- int t = rotateLeft(A, 5) + h(B, C, D) + E + X[j] + Y2;
-
- E = D;
- D = C;
- C = rotateLeft(B, 30);
- B = A;
- A = t;
- }
-
- //
- // round 3
- //
- for (int j = 40; j <= 59; j++)
- {
- int t = rotateLeft(A, 5) + g(B, C, D) + E + X[j] + Y3;
-
- E = D;
- D = C;
- C = rotateLeft(B, 30);
- B = A;
- A = t;
- }
-
- //
- // round 4
- //
- for (int j = 60; j <= 79; j++)
- {
- int t = rotateLeft(A, 5) + h(B, C, D) + E + X[j] + Y4;
-
- E = D;
- D = C;
- C = rotateLeft(B, 30);
- B = A;
- A = t;
- }
-
- H1 += A;
- H2 += B;
- H3 += C;
- H4 += D;
- H5 += E;
-
- //
- // reset the offset and clean out the word buffer.
- //
- xOff = 0;
- for (int i = 0; i != X.length; i++)
- {
- X[i] = 0;
- }
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.encodings;
-
-import java.security.SecureRandom;
-
-import org.bouncycastle.crypto.CipherParameters;
-import org.bouncycastle.crypto.AsymmetricBlockCipher;
-import org.bouncycastle.crypto.InvalidCipherTextException;
-import org.bouncycastle.crypto.params.ParametersWithRandom;
-import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
-
-/**
- * this does your basic PKCS 1 v1.5 padding - whether or not you should be using this
- * depends on your application - see PKCS1 Version 2 for details.
- */
-public class PKCS1Encoding
- implements AsymmetricBlockCipher
-{
- private static int HEADER_LENGTH = 10;
-
- private SecureRandom random;
- private AsymmetricBlockCipher engine;
- private boolean forEncryption;
- private boolean forPrivateKey;
-
- public PKCS1Encoding(
- AsymmetricBlockCipher cipher)
- {
- this.engine = cipher;
- }
-
- public AsymmetricBlockCipher getUnderlyingCipher()
- {
- return engine;
- }
-
- public void init(
- boolean forEncryption,
- CipherParameters param)
- {
- AsymmetricKeyParameter kParam;
-
- if (param instanceof ParametersWithRandom)
- {
- ParametersWithRandom rParam = (ParametersWithRandom)param;
-
- this.random = rParam.getRandom();
- kParam = (AsymmetricKeyParameter)rParam.getParameters();
- }
- else
- {
- this.random = new SecureRandom();
- kParam = (AsymmetricKeyParameter)param;
- }
-
- engine.init(forEncryption, kParam);
-
- this.forPrivateKey = kParam.isPrivate();
- this.forEncryption = forEncryption;
- }
-
- public int getInputBlockSize()
- {
- int baseBlockSize = engine.getInputBlockSize();
-
- if (forEncryption)
- {
- return baseBlockSize - HEADER_LENGTH;
- }
- else
- {
- return baseBlockSize;
- }
- }
-
- public int getOutputBlockSize()
- {
- int baseBlockSize = engine.getOutputBlockSize();
-
- if (forEncryption)
- {
- return baseBlockSize;
- }
- else
- {
- return baseBlockSize - HEADER_LENGTH;
- }
- }
-
- public byte[] processBlock(
- byte[] in,
- int inOff,
- int inLen)
- throws InvalidCipherTextException
- {
- if (forEncryption)
- {
- return encodeBlock(in, inOff, inLen);
- }
- else
- {
- return decodeBlock(in, inOff, inLen);
- }
- }
-
- private byte[] encodeBlock(
- byte[] in,
- int inOff,
- int inLen)
- throws InvalidCipherTextException
- {
- byte[] block = new byte[engine.getInputBlockSize()];
-
- if (forPrivateKey)
- {
- block[0] = 0x01; // type code 1
-
- for (int i = 1; i != block.length - inLen - 1; i++)
- {
- block[i] = (byte)0xFF;
- }
- }
- else
- {
- random.nextBytes(block); // random fill
-
- block[0] = 0x02; // type code 2
-
- //
- // a zero byte marks the end of the padding, so all
- // the pad bytes must be non-zero.
- //
- for (int i = 1; i != block.length - inLen - 1; i++)
- {
- while (block[i] == 0)
- {
- block[i] = (byte)random.nextInt();
- }
- }
- }
-
- block[block.length - inLen - 1] = 0x00; // mark the end of the padding
- System.arraycopy(in, inOff, block, block.length - inLen, inLen);
-
- return engine.processBlock(block, 0, block.length);
- }
-
- /**
- * @exception InvalidCipherTextException if the decrypted block is not in PKCS1 format.
- */
- private byte[] decodeBlock(
- byte[] in,
- int inOff,
- int inLen)
- throws InvalidCipherTextException
- {
- byte[] block = engine.processBlock(in, inOff, inLen);
-
- if (block.length < getOutputBlockSize())
- {
- throw new InvalidCipherTextException("block truncated");
- }
-
- if (block[0] != 1 && block[0] != 2)
- {
- throw new InvalidCipherTextException("unknown block type");
- }
-
- //
- // find and extract the message block.
- //
- int start;
-
- for (start = 1; start != block.length; start++)
- {
- if (block[start] == 0)
- {
- break;
- }
- }
-
- start++; // data should start at the next byte
-
- if (start >= block.length || start < HEADER_LENGTH)
- {
- throw new InvalidCipherTextException("no data in block");
- }
-
- byte[] result = new byte[block.length - start];
-
- System.arraycopy(block, start, result, 0, result.length);
-
- return result;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.engines;
-
-import java.lang.IllegalStateException;
-
-import org.bouncycastle.crypto.BlockCipher;
-import org.bouncycastle.crypto.CipherParameters;
-import org.bouncycastle.crypto.DataLengthException;
-import org.bouncycastle.crypto.params.KeyParameter;
-
-/**
- * a class that provides a basic DES engine.
- */
-public class DESEngine
- implements BlockCipher
-{
- protected static final int BLOCK_SIZE = 8;
-
- private int[] workingKey = null;
-
- /**
- * standard constructor.
- */
- public DESEngine()
- {
- }
-
- /**
- * initialise a DES cipher.
- *
- * @param forEncryption whether or not we are for encryption.
- * @param params the parameters required to set up the cipher.
- * @exception IllegalArgumentException if the params argument is
- * inappropriate.
- */
- public void init(
- boolean encrypting,
- CipherParameters params)
- {
- if (params instanceof KeyParameter)
- {
- workingKey = generateWorkingKey(encrypting,
- ((KeyParameter)params).getKey());
-
- return;
- }
-
- throw new IllegalArgumentException("invalid parameter passed to DES init - " + params.getClass().getName());
- }
-
- public String getAlgorithmName()
- {
- return "DES";
- }
-
- public int getBlockSize()
- {
- return BLOCK_SIZE;
- }
-
- public int processBlock(
- byte[] in,
- int inOff,
- byte[] out,
- int outOff)
- {
- if (workingKey == null)
- {
- throw new IllegalStateException("DES engine not initialised");
- }
-
- if ((inOff + BLOCK_SIZE) > in.length)
- {
- throw new DataLengthException("input buffer too short");
- }
-
- if ((outOff + BLOCK_SIZE) > out.length)
- {
- throw new DataLengthException("output buffer too short");
- }
-
- desFunc(workingKey, in, inOff, out, outOff);
-
- return BLOCK_SIZE;
- }
-
- public void reset()
- {
- }
-
- /**
- * what follows is mainly taken from "Applied Cryptography", by
- * Bruce Schneier, however it also bears great resemblance to Richard
- * Outerbridge's D3DES...
- */
-
- static short[] Df_Key =
- {
- 0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
- 0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10,
- 0x89,0xab,0xcd,0xef,0x01,0x23,0x45,0x67
- };
-
- static short[] bytebit =
- {
- 0200, 0100, 040, 020, 010, 04, 02, 01
- };
-
- static int[] bigbyte =
- {
- 0x800000, 0x400000, 0x200000, 0x100000,
- 0x80000, 0x40000, 0x20000, 0x10000,
- 0x8000, 0x4000, 0x2000, 0x1000,
- 0x800, 0x400, 0x200, 0x100,
- 0x80, 0x40, 0x20, 0x10,
- 0x8, 0x4, 0x2, 0x1
- };
-
- /*
- * Use the key schedule specified in the Standard (ANSI X3.92-1981).
- */
-
- static byte[] pc1 =
- {
- 56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17,
- 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35,
- 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21,
- 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3
- };
-
- static byte[] totrot =
- {
- 1, 2, 4, 6, 8, 10, 12, 14,
- 15, 17, 19, 21, 23, 25, 27, 28
- };
-
- static byte[] pc2 =
- {
- 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9,
- 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1,
- 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47,
- 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31
- };
-
- static int[] SP1 = {
- 0x01010400, 0x00000000, 0x00010000, 0x01010404,
- 0x01010004, 0x00010404, 0x00000004, 0x00010000,
- 0x00000400, 0x01010400, 0x01010404, 0x00000400,
- 0x01000404, 0x01010004, 0x01000000, 0x00000004,
- 0x00000404, 0x01000400, 0x01000400, 0x00010400,
- 0x00010400, 0x01010000, 0x01010000, 0x01000404,
- 0x00010004, 0x01000004, 0x01000004, 0x00010004,
- 0x00000000, 0x00000404, 0x00010404, 0x01000000,
- 0x00010000, 0x01010404, 0x00000004, 0x01010000,
- 0x01010400, 0x01000000, 0x01000000, 0x00000400,
- 0x01010004, 0x00010000, 0x00010400, 0x01000004,
- 0x00000400, 0x00000004, 0x01000404, 0x00010404,
- 0x01010404, 0x00010004, 0x01010000, 0x01000404,
- 0x01000004, 0x00000404, 0x00010404, 0x01010400,
- 0x00000404, 0x01000400, 0x01000400, 0x00000000,
- 0x00010004, 0x00010400, 0x00000000, 0x01010004
- };
-
- static int[] SP2 = {
- 0x80108020, 0x80008000, 0x00008000, 0x00108020,
- 0x00100000, 0x00000020, 0x80100020, 0x80008020,
- 0x80000020, 0x80108020, 0x80108000, 0x80000000,
- 0x80008000, 0x00100000, 0x00000020, 0x80100020,
- 0x00108000, 0x00100020, 0x80008020, 0x00000000,
- 0x80000000, 0x00008000, 0x00108020, 0x80100000,
- 0x00100020, 0x80000020, 0x00000000, 0x00108000,
- 0x00008020, 0x80108000, 0x80100000, 0x00008020,
- 0x00000000, 0x00108020, 0x80100020, 0x00100000,
- 0x80008020, 0x80100000, 0x80108000, 0x00008000,
- 0x80100000, 0x80008000, 0x00000020, 0x80108020,
- 0x00108020, 0x00000020, 0x00008000, 0x80000000,
- 0x00008020, 0x80108000, 0x00100000, 0x80000020,
- 0x00100020, 0x80008020, 0x80000020, 0x00100020,
- 0x00108000, 0x00000000, 0x80008000, 0x00008020,
- 0x80000000, 0x80100020, 0x80108020, 0x00108000
- };
-
- static int[] SP3 = {
- 0x00000208, 0x08020200, 0x00000000, 0x08020008,
- 0x08000200, 0x00000000, 0x00020208, 0x08000200,
- 0x00020008, 0x08000008, 0x08000008, 0x00020000,
- 0x08020208, 0x00020008, 0x08020000, 0x00000208,
- 0x08000000, 0x00000008, 0x08020200, 0x00000200,
- 0x00020200, 0x08020000, 0x08020008, 0x00020208,
- 0x08000208, 0x00020200, 0x00020000, 0x08000208,
- 0x00000008, 0x08020208, 0x00000200, 0x08000000,
- 0x08020200, 0x08000000, 0x00020008, 0x00000208,
- 0x00020000, 0x08020200, 0x08000200, 0x00000000,
- 0x00000200, 0x00020008, 0x08020208, 0x08000200,
- 0x08000008, 0x00000200, 0x00000000, 0x08020008,
- 0x08000208, 0x00020000, 0x08000000, 0x08020208,
- 0x00000008, 0x00020208, 0x00020200, 0x08000008,
- 0x08020000, 0x08000208, 0x00000208, 0x08020000,
- 0x00020208, 0x00000008, 0x08020008, 0x00020200
- };
-
- static int[] SP4 = {
- 0x00802001, 0x00002081, 0x00002081, 0x00000080,
- 0x00802080, 0x00800081, 0x00800001, 0x00002001,
- 0x00000000, 0x00802000, 0x00802000, 0x00802081,
- 0x00000081, 0x00000000, 0x00800080, 0x00800001,
- 0x00000001, 0x00002000, 0x00800000, 0x00802001,
- 0x00000080, 0x00800000, 0x00002001, 0x00002080,
- 0x00800081, 0x00000001, 0x00002080, 0x00800080,
- 0x00002000, 0x00802080, 0x00802081, 0x00000081,
- 0x00800080, 0x00800001, 0x00802000, 0x00802081,
- 0x00000081, 0x00000000, 0x00000000, 0x00802000,
- 0x00002080, 0x00800080, 0x00800081, 0x00000001,
- 0x00802001, 0x00002081, 0x00002081, 0x00000080,
- 0x00802081, 0x00000081, 0x00000001, 0x00002000,
- 0x00800001, 0x00002001, 0x00802080, 0x00800081,
- 0x00002001, 0x00002080, 0x00800000, 0x00802001,
- 0x00000080, 0x00800000, 0x00002000, 0x00802080
- };
-
- static int[] SP5 = {
- 0x00000100, 0x02080100, 0x02080000, 0x42000100,
- 0x00080000, 0x00000100, 0x40000000, 0x02080000,
- 0x40080100, 0x00080000, 0x02000100, 0x40080100,
- 0x42000100, 0x42080000, 0x00080100, 0x40000000,
- 0x02000000, 0x40080000, 0x40080000, 0x00000000,
- 0x40000100, 0x42080100, 0x42080100, 0x02000100,
- 0x42080000, 0x40000100, 0x00000000, 0x42000000,
- 0x02080100, 0x02000000, 0x42000000, 0x00080100,
- 0x00080000, 0x42000100, 0x00000100, 0x02000000,
- 0x40000000, 0x02080000, 0x42000100, 0x40080100,
- 0x02000100, 0x40000000, 0x42080000, 0x02080100,
- 0x40080100, 0x00000100, 0x02000000, 0x42080000,
- 0x42080100, 0x00080100, 0x42000000, 0x42080100,
- 0x02080000, 0x00000000, 0x40080000, 0x42000000,
- 0x00080100, 0x02000100, 0x40000100, 0x00080000,
- 0x00000000, 0x40080000, 0x02080100, 0x40000100
- };
-
- static int[] SP6 = {
- 0x20000010, 0x20400000, 0x00004000, 0x20404010,
- 0x20400000, 0x00000010, 0x20404010, 0x00400000,
- 0x20004000, 0x00404010, 0x00400000, 0x20000010,
- 0x00400010, 0x20004000, 0x20000000, 0x00004010,
- 0x00000000, 0x00400010, 0x20004010, 0x00004000,
- 0x00404000, 0x20004010, 0x00000010, 0x20400010,
- 0x20400010, 0x00000000, 0x00404010, 0x20404000,
- 0x00004010, 0x00404000, 0x20404000, 0x20000000,
- 0x20004000, 0x00000010, 0x20400010, 0x00404000,
- 0x20404010, 0x00400000, 0x00004010, 0x20000010,
- 0x00400000, 0x20004000, 0x20000000, 0x00004010,
- 0x20000010, 0x20404010, 0x00404000, 0x20400000,
- 0x00404010, 0x20404000, 0x00000000, 0x20400010,
- 0x00000010, 0x00004000, 0x20400000, 0x00404010,
- 0x00004000, 0x00400010, 0x20004010, 0x00000000,
- 0x20404000, 0x20000000, 0x00400010, 0x20004010
- };
-
- static int[] SP7 = {
- 0x00200000, 0x04200002, 0x04000802, 0x00000000,
- 0x00000800, 0x04000802, 0x00200802, 0x04200800,
- 0x04200802, 0x00200000, 0x00000000, 0x04000002,
- 0x00000002, 0x04000000, 0x04200002, 0x00000802,
- 0x04000800, 0x00200802, 0x00200002, 0x04000800,
- 0x04000002, 0x04200000, 0x04200800, 0x00200002,
- 0x04200000, 0x00000800, 0x00000802, 0x04200802,
- 0x00200800, 0x00000002, 0x04000000, 0x00200800,
- 0x04000000, 0x00200800, 0x00200000, 0x04000802,
- 0x04000802, 0x04200002, 0x04200002, 0x00000002,
- 0x00200002, 0x04000000, 0x04000800, 0x00200000,
- 0x04200800, 0x00000802, 0x00200802, 0x04200800,
- 0x00000802, 0x04000002, 0x04200802, 0x04200000,
- 0x00200800, 0x00000000, 0x00000002, 0x04200802,
- 0x00000000, 0x00200802, 0x04200000, 0x00000800,
- 0x04000002, 0x04000800, 0x00000800, 0x00200002
- };
-
- static int[] SP8 = {
- 0x10001040, 0x00001000, 0x00040000, 0x10041040,
- 0x10000000, 0x10001040, 0x00000040, 0x10000000,
- 0x00040040, 0x10040000, 0x10041040, 0x00041000,
- 0x10041000, 0x00041040, 0x00001000, 0x00000040,
- 0x10040000, 0x10000040, 0x10001000, 0x00001040,
- 0x00041000, 0x00040040, 0x10040040, 0x10041000,
- 0x00001040, 0x00000000, 0x00000000, 0x10040040,
- 0x10000040, 0x10001000, 0x00041040, 0x00040000,
- 0x00041040, 0x00040000, 0x10041000, 0x00001000,
- 0x00000040, 0x10040040, 0x00001000, 0x00041040,
- 0x10001000, 0x00000040, 0x10000040, 0x10040000,
- 0x10040040, 0x10000000, 0x00040000, 0x10001040,
- 0x00000000, 0x10041040, 0x00040040, 0x10000040,
- 0x10040000, 0x10001000, 0x10001040, 0x00000000,
- 0x10041040, 0x00041000, 0x00041000, 0x00001040,
- 0x00001040, 0x00040040, 0x10000000, 0x10041000
- };
-
- /**
- * generate an integer based working key based on our secret key
- * and what we processing we are planning to do.
- *
- * Acknowledgements for this routine go to James Gillogly & Phil Karn.
- * (whoever, and wherever they are!).
- */
- protected int[] generateWorkingKey(
- boolean encrypting,
- byte[] key)
- {
- int[] newKey = new int[32];
- boolean[] pc1m = new boolean[56],
- pcr = new boolean[56];
-
- for (int j = 0; j < 56; j++ )
- {
- int l = pc1[j];
-
- pc1m[j] = ((key[l >>> 3] & bytebit[l & 07]) != 0);
- }
-
- for (int i = 0; i < 16; i++)
- {
- int l, m, n;
-
- if (encrypting)
- {
- m = i << 1;
- }
- else
- {
- m = (15 - i) << 1;
- }
-
- n = m + 1;
- newKey[m] = newKey[n] = 0;
-
- for (int j = 0; j < 28; j++)
- {
- l = j + totrot[i];
- if ( l < 28 )
- {
- pcr[j] = pc1m[l];
- }
- else
- {
- pcr[j] = pc1m[l - 28];
- }
- }
-
- for (int j = 28; j < 56; j++)
- {
- l = j + totrot[i];
- if (l < 56 )
- {
- pcr[j] = pc1m[l];
- }
- else
- {
- pcr[j] = pc1m[l - 28];
- }
- }
-
- for (int j = 0; j < 24; j++)
- {
- if (pcr[pc2[j]])
- {
- newKey[m] |= bigbyte[j];
- }
-
- if (pcr[pc2[j + 24]])
- {
- newKey[n] |= bigbyte[j];
- }
- }
- }
-
- //
- // store the processed key
- //
- for (int i = 0; i != 32; i += 2)
- {
- int i1, i2;
-
- i1 = newKey[i];
- i2 = newKey[i + 1];
-
- newKey[i] = ((i1 & 0x00fc0000) << 6) | ((i1 & 0x00000fc0) << 10)
- | ((i2 & 0x00fc0000) >>> 10) | ((i2 & 0x00000fc0) >>> 6);
-
- newKey[i + 1] = ((i1 & 0x0003f000) << 12) | ((i1 & 0x0000003f) << 16)
- | ((i2 & 0x0003f000) >>> 4) | (i2 & 0x0000003f);
- }
-
- return newKey;
- }
-
- /**
- * the DES engine.
- */
- protected void desFunc(
- int[] wKey,
- byte[] in,
- int inOff,
- byte[] out,
- int outOff)
- {
- int work, right, left;
-
- left = (in[inOff + 0] & 0xff) << 24;
- left |= (in[inOff + 1] & 0xff) << 16;
- left |= (in[inOff + 2] & 0xff) << 8;
- left |= (in[inOff + 3] & 0xff);
-
- right = (in[inOff + 4] & 0xff) << 24;
- right |= (in[inOff + 5] & 0xff) << 16;
- right |= (in[inOff + 6] & 0xff) << 8;
- right |= (in[inOff + 7] & 0xff);
-
- work = ((left >>> 4) ^ right) & 0x0f0f0f0f;
- right ^= work;
- left ^= (work << 4);
- work = ((left >>> 16) ^ right) & 0x0000ffff;
- right ^= work;
- left ^= (work << 16);
- work = ((right >>> 2) ^ left) & 0x33333333;
- left ^= work;
- right ^= (work << 2);
- work = ((right >>> 8) ^ left) & 0x00ff00ff;
- left ^= work;
- right ^= (work << 8);
- right = ((right << 1) | ((right >>> 31) & 1)) & 0xffffffff;
- work = (left ^ right) & 0xaaaaaaaa;
- left ^= work;
- right ^= work;
- left = ((left << 1) | ((left >>> 31) & 1)) & 0xffffffff;
-
- for (int round = 0; round < 8; round++)
- {
- int fval;
-
- work = (right << 28) | (right >>> 4);
- work ^= wKey[round * 4 + 0];
- fval = SP7[ work & 0x3f];
- fval |= SP5[(work >>> 8) & 0x3f];
- fval |= SP3[(work >>> 16) & 0x3f];
- fval |= SP1[(work >>> 24) & 0x3f];
- work = right ^ wKey[round * 4 + 1];
- fval |= SP8[ work & 0x3f];
- fval |= SP6[(work >>> 8) & 0x3f];
- fval |= SP4[(work >>> 16) & 0x3f];
- fval |= SP2[(work >>> 24) & 0x3f];
- left ^= fval;
- work = (left << 28) | (left >>> 4);
- work ^= wKey[round * 4 + 2];
- fval = SP7[ work & 0x3f];
- fval |= SP5[(work >>> 8) & 0x3f];
- fval |= SP3[(work >>> 16) & 0x3f];
- fval |= SP1[(work >>> 24) & 0x3f];
- work = left ^ wKey[round * 4 + 3];
- fval |= SP8[ work & 0x3f];
- fval |= SP6[(work >>> 8) & 0x3f];
- fval |= SP4[(work >>> 16) & 0x3f];
- fval |= SP2[(work >>> 24) & 0x3f];
- right ^= fval;
- }
-
- right = (right << 31) | (right >>> 1);
- work = (left ^ right) & 0xaaaaaaaa;
- left ^= work;
- right ^= work;
- left = (left << 31) | (left >>> 1);
- work = ((left >>> 8) ^ right) & 0x00ff00ff;
- right ^= work;
- left ^= (work << 8);
- work = ((left >>> 2) ^ right) & 0x33333333;
- right ^= work;
- left ^= (work << 2);
- work = ((right >>> 16) ^ left) & 0x0000ffff;
- left ^= work;
- right ^= (work << 16);
- work = ((right >>> 4) ^ left) & 0x0f0f0f0f;
- left ^= work;
- right ^= (work << 4);
-
- out[outOff + 0] = (byte)((right >>> 24) & 0xff);
- out[outOff + 1] = (byte)((right >>> 16) & 0xff);
- out[outOff + 2] = (byte)((right >>> 8) & 0xff);
- out[outOff + 3] = (byte)( right & 0xff);
- out[outOff + 4] = (byte)((left >>> 24) & 0xff);
- out[outOff + 5] = (byte)((left >>> 16) & 0xff);
- out[outOff + 6] = (byte)((left >>> 8) & 0xff);
- out[outOff + 7] = (byte)( left & 0xff);
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.engines;\r
-\r
-import org.bouncycastle.crypto.StreamCipher;\r
-import org.bouncycastle.crypto.CipherParameters;\r
-import org.bouncycastle.crypto.DataLengthException;\r
-import org.bouncycastle.crypto.params.KeyParameter;\r
-\r
-public class RC4Engine implements StreamCipher\r
-{\r
- private final static int STATE_LENGTH = 256;\r
-\r
- /*\r
- * variables to hold the state of the RC4 engine\r
- * during encryption and decryption\r
- */\r
-\r
- private byte[] engineState = null;\r
- private int x = 0;\r
- private int y = 0;\r
- private byte[] workingKey = null;\r
-\r
- /**\r
- * initialise a RC4 cipher.\r
- *\r
- * @param forEncryption whether or not we are for encryption.\r
- * @param params the parameters required to set up the cipher.\r
- * @exception IllegalArgumentException if the params argument is\r
- * inappropriate.\r
- */\r
- public void init(\r
- boolean forEncryption, \r
- CipherParameters params\r
- )\r
- {\r
- if (params instanceof KeyParameter)\r
- {\r
- /* \r
- * RC4 encryption and decryption is completely\r
- * symmetrical, so the 'forEncryption' is \r
- * irrelevant.\r
- */\r
- workingKey = ((KeyParameter)params).getKey();\r
- setKey(workingKey);\r
-\r
- return;\r
- }\r
-\r
- throw new IllegalArgumentException("invalid parameter passed to RC4 init - " + params.getClass().getName());\r
- }\r
-\r
- public String getAlgorithmName()\r
- {\r
- return "RC4";\r
- }\r
-\r
- public byte returnByte(byte in)\r
- {\r
- x = (x + 1) & 0xff;\r
- y = (engineState[x] + y) & 0xff;\r
-\r
- // swap\r
- byte tmp = engineState[x];\r
- engineState[x] = engineState[y];\r
- engineState[y] = tmp;\r
-\r
- // xor\r
- return (byte)(in ^ engineState[(engineState[x] + engineState[y]) & 0xff]);\r
- }\r
-\r
- public void processBytes(\r
- byte[] in, \r
- int inOff, \r
- int len, \r
- byte[] out, \r
- int outOff\r
- )\r
- {\r
- if ((inOff + len) > in.length)\r
- {\r
- throw new DataLengthException("input buffer too short");\r
- }\r
-\r
- if ((outOff + len) > out.length)\r
- {\r
- throw new DataLengthException("output buffer too short");\r
- }\r
-\r
- for (int i = 0; i < len ; i++)\r
- {\r
- x = (x + 1) & 0xff;\r
- y = (engineState[x] + y) & 0xff;\r
-\r
- // swap\r
- byte tmp = engineState[x];\r
- engineState[x] = engineState[y];\r
- engineState[y] = tmp;\r
-\r
- // xor\r
- out[i+outOff] = (byte)(in[i + inOff]\r
- ^ engineState[(engineState[x] + engineState[y]) & 0xff]);\r
- }\r
- }\r
-\r
- public void reset()\r
- {\r
- setKey(workingKey);\r
- }\r
-\r
- // Private implementation\r
-\r
- private void setKey(byte[] keyBytes)\r
- {\r
- workingKey = keyBytes;\r
-\r
- // System.out.println("the key length is ; "+ workingKey.length);\r
-\r
- x = 0;\r
- y = 0;\r
-\r
- if (engineState == null)\r
- {\r
- engineState = new byte[STATE_LENGTH];\r
- }\r
-\r
- // reset the state of the engine\r
- for (int i=0; i < STATE_LENGTH; i++)\r
- {\r
- engineState[i] = (byte)i;\r
- }\r
- \r
- int i1 = 0;\r
- int i2 = 0;\r
-\r
- for (int i=0; i < STATE_LENGTH; i++)\r
- {\r
- i2 = ((keyBytes[i1] & 0xff) + engineState[i] + i2) & 0xff;\r
- // do the byte-swap inline\r
- byte tmp = engineState[i];\r
- engineState[i] = engineState[i2];\r
- engineState[i2] = tmp;\r
- i1 = (i1+1) % keyBytes.length; \r
- }\r
- }\r
-}\r
+++ /dev/null
-package org.bouncycastle.crypto.engines;
-
-import java.math.BigInteger;
-
-import org.bouncycastle.crypto.CipherParameters;
-import org.bouncycastle.crypto.DataLengthException;
-import org.bouncycastle.crypto.AsymmetricBlockCipher;
-import org.bouncycastle.crypto.params.RSAKeyParameters;
-import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
-
-/**
- * this does your basic RSA algorithm.
- */
-public class RSAEngine
- implements AsymmetricBlockCipher
-{
- private RSAKeyParameters key;
- private boolean forEncryption;
-
- /**
- * initialise the RSA engine.
- *
- * @param forEncryption true if we are encrypting, false otherwise.
- * @param param the necessary RSA key parameters.
- */
- public void init(
- boolean forEncryption,
- CipherParameters param)
- {
- this.key = (RSAKeyParameters)param;
- this.forEncryption = forEncryption;
- }
-
- /**
- * Return the maximum size for an input block to this engine.
- * For RSA this is always one byte less than the key size on
- * encryption, and the same length as the key size on decryption.
- *
- * @return maximum size for an input block.
- */
- public int getInputBlockSize()
- {
- int bitSize = key.getModulus().bitLength();
-
- if (forEncryption)
- {
- return (bitSize + 7) / 8 - 1;
- }
- else
- {
- return (bitSize + 7) / 8;
- }
- }
-
- /**
- * Return the maximum size for an output block to this engine.
- * For RSA this is always one byte less than the key size on
- * decryption, and the same length as the key size on encryption.
- *
- * @return maximum size for an output block.
- */
- public int getOutputBlockSize()
- {
- int bitSize = key.getModulus().bitLength();
-
- if (forEncryption)
- {
- return (bitSize + 7) / 8;
- }
- else
- {
- return (bitSize + 7) / 8 - 1;
- }
- }
-
- /**
- * Process a single block using the basic RSA algorithm.
- *
- * @param in the input array.
- * @param inOff the offset into the input buffer where the data starts.
- * @param inLen the length of the data to be processed.
- * @return the result of the RSA process.
- * @exception DataLengthException the input block is too large.
- */
- public byte[] processBlock(
- byte[] in,
- int inOff,
- int inLen)
- {
- if (inLen > (getInputBlockSize() + 1))
- {
- throw new DataLengthException("input too large for RSA cipher.\n");
- }
- else if (inLen == (getInputBlockSize() + 1) && (in[inOff] & 0x80) != 0)
- {
- throw new DataLengthException("input too large for RSA cipher.\n");
- }
-
- byte[] block;
-
- if (inOff != 0 || inLen != in.length)
- {
- block = new byte[inLen];
-
- System.arraycopy(in, inOff, block, 0, inLen);
- }
- else
- {
- block = in;
- }
-
- BigInteger input = new BigInteger(1, block);
- byte[] output;
-
- if (key instanceof RSAPrivateCrtKeyParameters)
- {
- //
- // we have the extra factors, use the Chinese Remainder Theorem - the author
- // wishes to express his thanks to Dirk Bonekaemper at rtsffm.com for
- // advice regarding the expression of this.
- //
- RSAPrivateCrtKeyParameters crtKey = (RSAPrivateCrtKeyParameters)key;
-
- BigInteger d = crtKey.getExponent();
- BigInteger p = crtKey.getP();
- BigInteger q = crtKey.getQ();
- BigInteger dP = crtKey.getDP();
- BigInteger dQ = crtKey.getDQ();
- BigInteger qInv = crtKey.getQInv();
-
- BigInteger mP, mQ, h, m;
-
- // mP = ((input mod p) ^ dP)) mod p
- mP = (input.remainder(p)).modPow(dP, p);
-
- // mQ = ((input mod q) ^ dQ)) mod q
- mQ = (input.remainder(q)).modPow(dQ, q);
-
- // h = qInv * (mP - mQ) mod p
- h = mP.subtract(mQ);
- h = h.multiply(qInv);
- h = h.mod(p); // mod (in Java) returns the positive residual
-
- // m = h * q + mQ
- m = h.multiply(q);
- m = m.add(mQ);
-
- output = m.toByteArray();
- }
- else
- {
- output = input.modPow(
- key.getExponent(), key.getModulus()).toByteArray();
- }
-
- if (forEncryption)
- {
- if (output[0] == 0 && output.length > getOutputBlockSize()) // have ended up with an extra zero byte, copy down.
- {
- byte[] tmp = new byte[output.length - 1];
-
- System.arraycopy(output, 1, tmp, 0, tmp.length);
-
- return tmp;
- }
-
- if (output.length < getOutputBlockSize()) // have ended up with less bytes than normal, lengthen
- {
- byte[] tmp = new byte[getOutputBlockSize()];
-
- System.arraycopy(output, 0, tmp, tmp.length - output.length, output.length);
-
- return tmp;
- }
- }
- else
- {
- if (output[0] == 0) // have ended up with an extra zero byte, copy down.
- {
- byte[] tmp = new byte[output.length - 1];
-
- System.arraycopy(output, 1, tmp, 0, tmp.length);
-
- return tmp;
- }
- }
- return output;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.io;
-
-import java.io.*;
-
-import org.bouncycastle.crypto.Digest;
-
-public class DigestInputStream
- extends FilterInputStream
-{
- protected Digest digest;
-
- public DigestInputStream(
- InputStream stream,
- Digest digest)
- {
- super(stream);
- this.digest = digest;
- }
-
- public int read()
- throws IOException
- {
- int b = in.read();
-
- if (b >= 0)
- {
- digest.update((byte)b);
- }
- return b;
- }
-
- public int read(
- byte[] b,
- int off,
- int len)
- throws IOException
- {
- int n = in.read(b, off, len);
- if (n > 0)
- {
- digest.update(b, off, n);
- }
- return n;
- }
-
- public Digest getDigest()
- {
- return digest;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.io;
-
-import java.io.*;
-
-import org.bouncycastle.crypto.Digest;
-
-public class DigestOutputStream
- extends FilterOutputStream
-{
- protected Digest digest;
-
- public DigestOutputStream(
- OutputStream stream,
- Digest digest)
- {
- super(stream);
- this.digest = digest;
- }
-
- public void write(int b)
- throws IOException
- {
- digest.update((byte)b);
- out.write(b);
- }
-
- public void write(
- byte[] b,
- int off,
- int len)
- throws IOException
- {
- digest.update(b, off, len);
- out.write(b, off, len);
- }
-
- public Digest getDigest()
- {
- return digest;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.params;
-
-import org.bouncycastle.crypto.CipherParameters;
-
-public class AsymmetricKeyParameter
- implements CipherParameters
-{
- boolean privateKey;
-
- public AsymmetricKeyParameter(
- boolean privateKey)
- {
- this.privateKey = privateKey;
- }
-
- public boolean isPrivate()
- {
- return privateKey;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.params;
-
-import org.bouncycastle.crypto.CipherParameters;
-
-public class KeyParameter
- implements CipherParameters
-{
- private byte[] key;
-
- public KeyParameter(
- byte[] key)
- {
- this(key, 0, key.length);
- }
-
- public KeyParameter(
- byte[] key,
- int keyOff,
- int keyLen)
- {
- this.key = new byte[keyLen];
-
- System.arraycopy(key, keyOff, this.key, 0, keyLen);
- }
-
- public byte[] getKey()
- {
- return key;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.params;
-
-import java.security.SecureRandom;
-
-import org.bouncycastle.crypto.CipherParameters;
-
-public class ParametersWithRandom
- implements CipherParameters
-{
- private SecureRandom random;
- private CipherParameters parameters;
-
- public ParametersWithRandom(
- CipherParameters parameters,
- SecureRandom random)
- {
- this.random = random;
- this.parameters = parameters;
- }
-
- public ParametersWithRandom(
- CipherParameters parameters)
- {
- this.random = null;
- this.parameters = parameters;
- }
-
- public SecureRandom getRandom()
- {
- if (random == null)
- {
- random = new SecureRandom();
- }
- return random;
- }
-
- public CipherParameters getParameters()
- {
- return parameters;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.params;
-
-import java.math.BigInteger;
-
-public class RSAKeyParameters
- extends AsymmetricKeyParameter
-{
- private BigInteger modulus;
- private BigInteger exponent;
-
- public RSAKeyParameters(
- boolean isPrivate,
- BigInteger modulus,
- BigInteger exponent)
- {
- super(isPrivate);
-
- this.modulus = modulus;
- this.exponent = exponent;
- }
-
- public BigInteger getModulus()
- {
- return modulus;
- }
-
- public BigInteger getExponent()
- {
- return exponent;
- }
-}
+++ /dev/null
-package org.bouncycastle.crypto.params;
-
-import java.math.BigInteger;
-
-public class RSAPrivateCrtKeyParameters
- extends RSAKeyParameters
-{
- private BigInteger e;
- private BigInteger p;
- private BigInteger q;
- private BigInteger dP;
- private BigInteger dQ;
- private BigInteger qInv;
-
- /**
- *
- */
- public RSAPrivateCrtKeyParameters(
- BigInteger modulus,
- BigInteger publicExponent,
- BigInteger privateExponent,
- BigInteger p,
- BigInteger q,
- BigInteger dP,
- BigInteger dQ,
- BigInteger qInv)
- {
- super(true, modulus, privateExponent);
-
- this.e = publicExponent;
- this.p = p;
- this.q = q;
- this.dP = dP;
- this.dQ = dQ;
- this.qInv = qInv;
- }
-
- public BigInteger getPublicExponent()
- {
- return e;
- }
-
- public BigInteger getP()
- {
- return p;
- }
-
- public BigInteger getQ()
- {
- return q;
- }
-
- public BigInteger getDP()
- {
- return dP;
- }
-
- public BigInteger getDQ()
- {
- return dQ;
- }
-
- public BigInteger getQInv()
- {
- return qInv;
- }
-}
+++ /dev/null
-package org.bouncycastle.util.encoders;
-
-public class Base64
-{
- private static final byte[] encodingTable =
- {
- (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
- (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
- (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
- (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
- (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
- (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
- (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
- (byte)'v',
- (byte)'w', (byte)'x', (byte)'y', (byte)'z',
- (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6',
- (byte)'7', (byte)'8', (byte)'9',
- (byte)'+', (byte)'/'
- };
-
- /**
- * encode the input data producong a base 64 encoded byte array.
- *
- * @return a byte array containing the base 64 encoded data.
- */
- public static byte[] encode(
- byte[] data)
- {
- byte[] bytes;
-
- int modulus = data.length % 3;
- if (modulus == 0)
- {
- bytes = new byte[4 * data.length / 3];
- }
- else
- {
- bytes = new byte[4 * ((data.length / 3) + 1)];
- }
-
- int dataLength = (data.length - modulus);
- int a1, a2, a3;
- for (int i = 0, j = 0; i < dataLength; i += 3, j += 4)
- {
- a1 = data[i] & 0xff;
- a2 = data[i + 1] & 0xff;
- a3 = data[i + 2] & 0xff;
-
- bytes[j] = encodingTable[(a1 >>> 2) & 0x3f];
- bytes[j + 1] = encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f];
- bytes[j + 2] = encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f];
- bytes[j + 3] = encodingTable[a3 & 0x3f];
- }
-
- /*
- * process the tail end.
- */
- int b1, b2, b3;
- int d1, d2;
-
- switch (modulus)
- {
- case 0: /* nothing left to do */
- break;
- case 1:
- d1 = data[data.length - 1] & 0xff;
- b1 = (d1 >>> 2) & 0x3f;
- b2 = (d1 << 4) & 0x3f;
-
- bytes[bytes.length - 4] = encodingTable[b1];
- bytes[bytes.length - 3] = encodingTable[b2];
- bytes[bytes.length - 2] = (byte)'=';
- bytes[bytes.length - 1] = (byte)'=';
- break;
- case 2:
- d1 = data[data.length - 2] & 0xff;
- d2 = data[data.length - 1] & 0xff;
-
- b1 = (d1 >>> 2) & 0x3f;
- b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
- b3 = (d2 << 2) & 0x3f;
-
- bytes[bytes.length - 4] = encodingTable[b1];
- bytes[bytes.length - 3] = encodingTable[b2];
- bytes[bytes.length - 2] = encodingTable[b3];
- bytes[bytes.length - 1] = (byte)'=';
- break;
- }
-
- return bytes;
- }
-
- /*
- * set up the decoding table.
- */
- private static final byte[] decodingTable;
-
- static
- {
- decodingTable = new byte[128];
-
- for (int i = 'A'; i <= 'Z'; i++)
- {
- decodingTable[i] = (byte)(i - 'A');
- }
-
- for (int i = 'a'; i <= 'z'; i++)
- {
- decodingTable[i] = (byte)(i - 'a' + 26);
- }
-
- for (int i = '0'; i <= '9'; i++)
- {
- decodingTable[i] = (byte)(i - '0' + 52);
- }
-
- decodingTable['+'] = 62;
- decodingTable['/'] = 63;
- }
-
- /**
- * decode the base 64 encoded input data.
- *
- * @return a byte array representing the decoded data.
- */
- public static byte[] decode(
- byte[] data)
- {
- byte[] bytes;
- byte b1, b2, b3, b4;
-
- if (data[data.length - 2] == '=')
- {
- bytes = new byte[(((data.length / 4) - 1) * 3) + 1];
- }
- else if (data[data.length - 1] == '=')
- {
- bytes = new byte[(((data.length / 4) - 1) * 3) + 2];
- }
- else
- {
- bytes = new byte[((data.length / 4) * 3)];
- }
-
- for (int i = 0, j = 0; i < data.length - 4; i += 4, j += 3)
- {
- b1 = decodingTable[data[i]];
- b2 = decodingTable[data[i + 1]];
- b3 = decodingTable[data[i + 2]];
- b4 = decodingTable[data[i + 3]];
-
- bytes[j] = (byte)((b1 << 2) | (b2 >> 4));
- bytes[j + 1] = (byte)((b2 << 4) | (b3 >> 2));
- bytes[j + 2] = (byte)((b3 << 6) | b4);
- }
-
- if (data[data.length - 2] == '=')
- {
- b1 = decodingTable[data[data.length - 4]];
- b2 = decodingTable[data[data.length - 3]];
-
- bytes[bytes.length - 1] = (byte)((b1 << 2) | (b2 >> 4));
- }
- else if (data[data.length - 1] == '=')
- {
- b1 = decodingTable[data[data.length - 4]];
- b2 = decodingTable[data[data.length - 3]];
- b3 = decodingTable[data[data.length - 2]];
-
- bytes[bytes.length - 2] = (byte)((b1 << 2) | (b2 >> 4));
- bytes[bytes.length - 1] = (byte)((b2 << 4) | (b3 >> 2));
- }
- else
- {
- b1 = decodingTable[data[data.length - 4]];
- b2 = decodingTable[data[data.length - 3]];
- b3 = decodingTable[data[data.length - 2]];
- b4 = decodingTable[data[data.length - 1]];
-
- bytes[bytes.length - 3] = (byte)((b1 << 2) | (b2 >> 4));
- bytes[bytes.length - 2] = (byte)((b2 << 4) | (b3 >> 2));
- bytes[bytes.length - 1] = (byte)((b3 << 6) | b4);
- }
-
- return bytes;
- }
-
- /**
- * decode the base 64 encoded String data.
- *
- * @return a byte array representing the decoded data.
- */
- public static byte[] decode(
- String data)
- {
- byte[] bytes;
- byte b1, b2, b3, b4;
-
- if (data.charAt(data.length() - 2) == '=')
- {
- bytes = new byte[(((data.length() / 4) - 1) * 3) + 1];
- }
- else if (data.charAt(data.length() - 1) == '=')
- {
- bytes = new byte[(((data.length() / 4) - 1) * 3) + 2];
- }
- else
- {
- bytes = new byte[((data.length() / 4) * 3)];
- }
-
- for (int i = 0, j = 0; i < data.length() - 4; i += 4, j += 3)
- {
- b1 = decodingTable[data.charAt(i)];
- b2 = decodingTable[data.charAt(i + 1)];
- b3 = decodingTable[data.charAt(i + 2)];
- b4 = decodingTable[data.charAt(i + 3)];
-
- bytes[j] = (byte)((b1 << 2) | (b2 >> 4));
- bytes[j + 1] = (byte)((b2 << 4) | (b3 >> 2));
- bytes[j + 2] = (byte)((b3 << 6) | b4);
- }
-
- if (data.charAt(data.length() - 2) == '=')
- {
- b1 = decodingTable[data.charAt(data.length() - 4)];
- b2 = decodingTable[data.charAt(data.length() - 3)];
-
- bytes[bytes.length - 1] = (byte)((b1 << 2) | (b2 >> 4));
- }
- else if (data.charAt(data.length() - 1) == '=')
- {
- b1 = decodingTable[data.charAt(data.length() - 4)];
- b2 = decodingTable[data.charAt(data.length() - 3)];
- b3 = decodingTable[data.charAt(data.length() - 2)];
-
- bytes[bytes.length - 2] = (byte)((b1 << 2) | (b2 >> 4));
- bytes[bytes.length - 1] = (byte)((b2 << 4) | (b3 >> 2));
- }
- else
- {
- b1 = decodingTable[data.charAt(data.length() - 4)];
- b2 = decodingTable[data.charAt(data.length() - 3)];
- b3 = decodingTable[data.charAt(data.length() - 2)];
- b4 = decodingTable[data.charAt(data.length() - 1)];
-
- bytes[bytes.length - 3] = (byte)((b1 << 2) | (b2 >> 4));
- bytes[bytes.length - 2] = (byte)((b2 << 4) | (b3 >> 2));
- bytes[bytes.length - 1] = (byte)((b3 << 6) | b4);
- }
-
- return bytes;
- }
-}
+++ /dev/null
-<body>
-
-<p>
-The Ibex JavaScript Engine.
-</p>
-
-</body>
+++ /dev/null
-
-<body>
-
-<p>
-The core Ibex engine classes.
-</p>
-
-<h3>Interfacing with other code</h3>
-
-<p>
-This engine is not meant to be used as a library or to interface with
-any other code. Because of this, all classes and methods have package
-(nonpublic) access, except where interpackage calls or reflection
-demand that they be public. Authors of other software should NEVER
-depend on any of these APIs.
-</p>
-
-<h3>An important note about Threads</h3>
-
-<p>
-All operations are single-threaded, except sleep(), yield(), xmlrpc
-calls, and MessageQueue message loop. That means that while one thread
-is rendering or executing a script, no other thread can be rendering
-or executing a script.
-</p>
-
-<p>
-For performance reasons, we do <i>not</i> enforce this
-single-threadedness with Java synchronization primitives. If you
-change the engine code, be very careful not to violate this
-invariant. In general, you should only render or execute JavaScripts
-if (Thread.currentThread() == MessageQueue.singleton). The only
-exception is instances of ThreadMessage -- they include logic to block
-the MessageQueue thread on a semaphore, execute some javascript, and
-unblock the MessageQueue thread once the javascript has returned or
-performed some blocking operation. Be especially careful not to
-manipulate instances of Box from within the AWT thread. @see
-MessageQueue ThreadMessage
-</p>
-
-</body>
+++ /dev/null
-<body>
-
-<p>
-Each platform which Ibex is ported to should have a subclass of {@link
-org.ibex.Platform} in this package as well as an ant buildfile.
-</p>
-
-<p>
-The subclass of {@link org.ibex.Platform} should be named
-<i>plat</i>.java, where <i>plat</i> is the descriptive name for the
-platform. The ant buildfile should be named <i>plat</i>.xml, and
-should contain three targets:
-</p>
-
-<ul><li> <b><tt>build</tt></b>: compiles all code required for the Ibex
- Engine and creates an executable in
- <tt>ibex/www/html/dist/</tt>. If applicable, all debugging
- symbols should be left in this executable.
-
- <li> <b><tt>run</tt></b>: runs the executable, loading the
- <tt>org.ibex.demo.main</tt> widget demo. This is useful for
- testing.
-
- <li> <b><tt>dist</tt></b>: prepares any files required to
- distribute the engine (for example, a jar or cab). This step
- should remove debugging symbols, if applicable.
-</ul>
-
-<p>
-Other platform-specific files can be included in this directory, as
-long as they share the same filename as the main class, and differ
-only in extension (for example, <i>plat</i>.cc).
-</p>
-
-<p>
-Classes in this package may subclass each other; this is useful when
-two classes are very similar -- they can share a superclass containing
-the common functionality.
-</p>
-
-</body>
+++ /dev/null
-package org.ibex.translators;
-import org.ibex.*;
-import org.ibex.util.*;
-import java.io.*;
-import java.util.zip.*;
-import java.util.*;
-import org.bouncycastle.util.encoders.Base64;
-
-import org.xwt.mips.Runtime;
-
-// FEATURE: use streams, not memoryfont's
-// FEATURE: kerning pairs
-public class Freetype {
-
- public Freetype() { }
-
- private int mem_allocated = 0;
- private Runtime vm = null;
-
- private Stream loadedStream = null;
-
- public void loadFontByteStream(Stream res) {
- try {
- Log.info(this, "loading font " + res);
- loadedStream = res;
- InputStream is = Stream.getInputStream(res);
- byte[] fontstream = InputStreamToByteArray.convert(is);
- vm = (Runtime)Class.forName("org.ibex.translators.MIPSApps").newInstance();
- int baseAddr = vm.sbrk(fontstream.length);
- vm.copyout(fontstream, baseAddr, fontstream.length);
- vm.setUserInfo(0, baseAddr);
- vm.setUserInfo(1, fontstream.length);
- vm.start(new String[]{ "freetype" });
- vm.execute();
- if(vm.getState() == Runtime.DONE) throw new Error("Freetype VM exited: " + vm.exitStatus());
- } catch (Exception e) {
- Log.info(this, e);
- }
- }
-
- public synchronized void renderGlyph(Font.Glyph glyph) throws IOException {
- try {
- Log.debug(this, "rasterizing glyph " + glyph.c + " of font " + glyph.font);
- if (loadedStream != glyph.font.stream) loadFontByteStream(glyph.font.stream);
- vm.setUserInfo(2, (int)glyph.c);
- vm.setUserInfo(3, (int)glyph.c);
- vm.setUserInfo(4, glyph.font.pointsize);
- long start = System.currentTimeMillis();
- vm.execute();
- glyph.font.max_ascent = vm.getUserInfo(8);
- glyph.font.max_descent = vm.getUserInfo(9);
- glyph.baseline = vm.getUserInfo(10);
- glyph.advance = vm.getUserInfo(11);
-
- glyph.width = vm.getUserInfo(6);
- glyph.height = vm.getUserInfo(7);
-
- glyph.data = new byte[glyph.width * glyph.height];
- int addr = vm.getUserInfo(5);
- vm.copyin(addr, glyph.data, glyph.width * glyph.height);
- glyph.isLoaded = true;
-
- } catch (Exception e) {
- Log.info(this, e);
- }
- }
-}
+++ /dev/null
-
-char *user_info[1024];
-
-extern int mspack_main();
-extern int freetype_main();
-
-int main(int argc, char **argv) {
- if(argc < 1) return 1;
- if(strcmp(argv[0],"mspack")==0) return mspack_main();
- if(strcmp(argv[0],"freetype")==0) return freetype_main();
- return 1;
-}
+++ /dev/null
-<body>
-An assortment of useful utility classes.
-</body>