From ac1ed908de999523efc36f38e69bca1aadfe0808 Mon Sep 17 00:00:00 2001
From: Mark Wielaard
Date: Mon, 14 Aug 2006 23:12:35 +0000
Subject: Imported GNU Classpath 0.92
2006-08-14 Mark Wielaard
Imported GNU Classpath 0.92
* HACKING: Add more importing hints. Update automake version
requirement.
* configure.ac (gconf-peer): New enable AC argument.
Add --disable-gconf-peer and --enable-default-preferences-peer
to classpath configure when gconf is disabled.
* scripts/makemake.tcl: Set gnu/java/util/prefs/gconf and
gnu/java/awt/dnd/peer/gtk to bc. Classify
gnu/java/security/Configuration.java as generated source file.
* gnu/java/lang/management/VMGarbageCollectorMXBeanImpl.java,
gnu/java/lang/management/VMMemoryPoolMXBeanImpl.java,
gnu/java/lang/management/VMClassLoadingMXBeanImpl.java,
gnu/java/lang/management/VMRuntimeMXBeanImpl.java,
gnu/java/lang/management/VMMemoryManagerMXBeanImpl.java,
gnu/java/lang/management/VMThreadMXBeanImpl.java,
gnu/java/lang/management/VMMemoryMXBeanImpl.java,
gnu/java/lang/management/VMCompilationMXBeanImpl.java: New VM stub
classes.
* java/lang/management/VMManagementFactory.java: Likewise.
* java/net/VMURLConnection.java: Likewise.
* gnu/java/nio/VMChannel.java: Likewise.
* java/lang/Thread.java (getState): Add stub implementation.
* java/lang/Class.java (isEnum): Likewise.
* java/lang/Class.h (isEnum): Likewise.
* gnu/awt/xlib/XToolkit.java (getClasspathTextLayoutPeer): Removed.
* javax/naming/spi/NamingManager.java: New override for StackWalker
functionality.
* configure, sources.am, Makefile.in, gcj/Makefile.in,
include/Makefile.in, testsuite/Makefile.in: Regenerated.
From-SVN: r116139
---
.../classpath/gnu/CORBA/ForwardRequestHelper.java | 25 +-
libjava/classpath/gnu/classpath/ByteArray.java | 109 -
.../gnu/classpath/debug/Simple1LineFormatter.java | 22 +-
.../gnu/classpath/debug/SystemLogger.java | 8 +-
.../gnu/classpath/debug/TeeInputStream.java | 98 +
.../gnu/classpath/debug/TeeOutputStream.java | 93 +
.../classpath/gnu/classpath/debug/TeeReader.java | 98 +
.../classpath/gnu/classpath/debug/TeeWriter.java | 93 +
libjava/classpath/gnu/classpath/jdwp/Jdwp.java | 46 +-
.../gnu/classpath/jdwp/event/BreakpointEvent.java | 15 +-
.../classpath/jdwp/event/ClassPrepareEvent.java | 6 +-
.../gnu/classpath/jdwp/event/ClassUnloadEvent.java | 96 +
.../classpath/gnu/classpath/jdwp/event/Event.java | 37 +-
.../gnu/classpath/jdwp/event/EventManager.java | 9 +-
.../gnu/classpath/jdwp/event/ExceptionEvent.java | 157 ++
.../gnu/classpath/jdwp/event/MethodEntryEvent.java | 118 ++
.../gnu/classpath/jdwp/event/MethodExitEvent.java | 115 ++
.../gnu/classpath/jdwp/event/SingleStepEvent.java | 121 ++
.../gnu/classpath/jdwp/event/ThreadEndEvent.java | 4 +-
.../gnu/classpath/jdwp/event/ThreadStartEvent.java | 4 +-
.../gnu/classpath/jdwp/event/VmDeathEvent.java | 2 +-
.../gnu/classpath/jdwp/event/VmInitEvent.java | 2 +-
.../jdwp/event/filters/ClassMatchFilter.java | 3 +-
.../jdwp/event/filters/ClassOnlyFilter.java | 2 +-
.../jdwp/event/filters/ExceptionOnlyFilter.java | 62 +-
.../jdwp/event/filters/InstanceOnlyFilter.java | 2 +-
.../jdwp/event/filters/ThreadOnlyFilter.java | 4 +-
.../jdwp/processor/ClassTypeCommandSet.java | 8 +-
.../jdwp/processor/EventRequestCommandSet.java | 2 +-
.../classpath/jdwp/processor/PacketProcessor.java | 8 +-
.../processor/ThreadGroupReferenceCommandSet.java | 8 +-
.../classpath/jdwp/transport/JdwpConnection.java | 6 +-
.../gnu/classpath/jdwp/util/Location.java | 40 +-
.../classpath/gnu/java/awt/ClasspathToolkit.java | 27 +-
.../awt/dnd/GtkMouseDragGestureRecognizer.java | 172 ++
.../awt/dnd/peer/gtk/GtkDragSourceContextPeer.java | 174 ++
.../awt/dnd/peer/gtk/GtkDropTargetContextPeer.java | 125 ++
.../java/awt/dnd/peer/gtk/GtkDropTargetPeer.java | 68 +
.../gnu/java/awt/java2d/AbstractGraphics2D.java | 42 +-
.../gnu/java/awt/java2d/CubicSegment.java | 98 +-
.../classpath/gnu/java/awt/java2d/LineSegment.java | 21 +-
.../classpath/gnu/java/awt/java2d/QuadSegment.java | 24 +-
libjava/classpath/gnu/java/awt/java2d/Segment.java | 37 +-
.../gnu/java/awt/peer/ClasspathFontPeer.java | 7 +-
.../gnu/java/awt/peer/ClasspathTextLayoutPeer.java | 104 -
.../java/awt/peer/gtk/BufferedImageGraphics.java | 2 -
.../gnu/java/awt/peer/gtk/CairoGraphics2D.java | 222 +-
.../gnu/java/awt/peer/gtk/CairoSurface.java | 63 +-
.../java/awt/peer/gtk/CairoSurfaceGraphics.java | 5 -
.../gnu/java/awt/peer/gtk/ComponentGraphics.java | 146 +-
.../java/awt/peer/gtk/ComponentGraphicsCopy.java | 6 -
.../gnu/java/awt/peer/gtk/FreetypeGlyphVector.java | 44 +-
.../gnu/java/awt/peer/gtk/GdkFontPeer.java | 3 -
.../java/awt/peer/gtk/GdkGraphicsEnvironment.java | 6 +-
.../gnu/java/awt/peer/gtk/GdkPixbufDecoder.java | 3 -
.../gnu/java/awt/peer/gtk/GdkTextLayout.java | 393 ----
.../gnu/java/awt/peer/gtk/GtkButtonPeer.java | 5 -
.../gnu/java/awt/peer/gtk/GtkCanvasPeer.java | 4 +-
.../java/awt/peer/gtk/GtkCheckboxGroupPeer.java | 86 -
.../gnu/java/awt/peer/gtk/GtkCheckboxPeer.java | 167 +-
.../java/awt/peer/gtk/GtkClipboardNotifier.java | 4 +-
.../gnu/java/awt/peer/gtk/GtkComponentPeer.java | 93 +-
.../gnu/java/awt/peer/gtk/GtkContainerPeer.java | 3 -
.../gnu/java/awt/peer/gtk/GtkDialogPeer.java | 5 +-
.../gnu/java/awt/peer/gtk/GtkFramePeer.java | 8 +-
.../classpath/gnu/java/awt/peer/gtk/GtkImage.java | 2 -
.../gnu/java/awt/peer/gtk/GtkImageConsumer.java | 7 +-
.../gnu/java/awt/peer/gtk/GtkLabelPeer.java | 8 +-
.../gnu/java/awt/peer/gtk/GtkMenuBarPeer.java | 3 -
.../gnu/java/awt/peer/gtk/GtkMenuItemPeer.java | 5 -
.../gnu/java/awt/peer/gtk/GtkMouseInfoPeer.java | 76 +
.../gnu/java/awt/peer/gtk/GtkPanelPeer.java | 3 +-
.../gnu/java/awt/peer/gtk/GtkPopupMenuPeer.java | 1 -
.../gnu/java/awt/peer/gtk/GtkScrollbarPeer.java | 2 -
.../gnu/java/awt/peer/gtk/GtkToolkit.java | 111 +-
.../gnu/java/awt/peer/gtk/GtkVolatileImage.java | 3 +
.../gnu/java/awt/peer/gtk/GtkWindowPeer.java | 48 +-
.../java/awt/peer/gtk/VolatileImageGraphics.java | 16 +-
.../gnu/java/awt/peer/qt/QtCheckboxPeer.java | 3 +-
.../gnu/java/awt/peer/qt/QtComponentGraphics.java | 4 +-
.../gnu/java/awt/peer/qt/QtComponentPeer.java | 3 +-
.../gnu/java/awt/peer/qt/QtContainerPeer.java | 3 +-
.../gnu/java/awt/peer/qt/QtDialogPeer.java | 4 +-
.../gnu/java/awt/peer/qt/QtEmbeddedWindowPeer.java | 3 +-
.../gnu/java/awt/peer/qt/QtFontMetrics.java | 5 +-
.../classpath/gnu/java/awt/peer/qt/QtFontPeer.java | 3 +-
.../classpath/gnu/java/awt/peer/qt/QtGraphics.java | 16 +-
.../java/awt/peer/qt/QtGraphicsEnvironment.java | 3 +-
.../classpath/gnu/java/awt/peer/qt/QtImage.java | 3 +-
.../gnu/java/awt/peer/qt/QtImageConsumer.java | 7 +-
.../java/awt/peer/qt/QtImageDirectGraphics.java | 21 +-
.../gnu/java/awt/peer/qt/QtImageGraphics.java | 4 +-
.../gnu/java/awt/peer/qt/QtMenuBarPeer.java | 3 +-
.../gnu/java/awt/peer/qt/QtMenuItemPeer.java | 3 +-
.../gnu/java/awt/peer/qt/QtPopupMenuPeer.java | 5 +-
.../awt/peer/qt/QtScreenDeviceConfiguration.java | 4 +-
.../gnu/java/awt/peer/qt/QtScrollPanePeer.java | 3 +-
.../classpath/gnu/java/awt/peer/qt/QtToolkit.java | 35 +-
.../gnu/java/awt/peer/qt/QtVolatileImage.java | 6 +-
.../java/awt/peer/swing/SwingComponentPeer.java | 76 +-
.../classpath/gnu/java/awt/peer/x/GLGraphics.java | 123 ++
.../gnu/java/awt/peer/x/ImageConverter.java | 113 ++
.../gnu/java/awt/peer/x/KeyboardMapping.java | 415 ++++
.../classpath/gnu/java/awt/peer/x/XDialogPeer.java | 61 +
.../classpath/gnu/java/awt/peer/x/XEventPump.java | 287 +++
.../classpath/gnu/java/awt/peer/x/XFontPeer.java | 766 +++++++
.../classpath/gnu/java/awt/peer/x/XFontPeer2.java | 335 +++
.../classpath/gnu/java/awt/peer/x/XFramePeer.java | 140 ++
.../classpath/gnu/java/awt/peer/x/XGraphics.java | 792 ++++++++
.../classpath/gnu/java/awt/peer/x/XGraphics2D.java | 295 +++
.../java/awt/peer/x/XGraphicsConfiguration.java | 118 ++
.../gnu/java/awt/peer/x/XGraphicsDevice.java | 166 ++
.../gnu/java/awt/peer/x/XGraphicsEnvironment.java | 202 ++
libjava/classpath/gnu/java/awt/peer/x/XImage.java | 111 +
.../gnu/java/awt/peer/x/XLightweightPeer.java | 56 +
.../classpath/gnu/java/awt/peer/x/XToolkit.java | 608 ++++++
.../classpath/gnu/java/awt/peer/x/XWindowPeer.java | 255 +++
.../gnu/java/awt/print/PostScriptGraphics2D.java | 4 +-
libjava/classpath/gnu/java/io/PlatformHelper.java | 94 +-
.../gnu/java/lang/management/BeanImpl.java | 84 +
.../lang/management/ClassLoadingMXBeanImpl.java | 99 +
.../lang/management/CompilationMXBeanImpl.java | 105 +
.../management/GarbageCollectorMXBeanImpl.java | 84 +
.../gnu/java/lang/management/MemoryMXBeanImpl.java | 322 +++
.../lang/management/MemoryManagerMXBeanImpl.java | 112 ++
.../java/lang/management/MemoryPoolMXBeanImpl.java | 225 +++
.../lang/management/OperatingSystemMXBeanImpl.java | 90 +
.../java/lang/management/RuntimeMXBeanImpl.java | 197 ++
.../gnu/java/lang/management/ThreadMXBeanImpl.java | 291 +++
.../gnu/java/lang/management/package.html | 46 +
.../classpath/gnu/java/net/IndexListParser.java | 6 +-
.../gnu/java/net/loader/FileResource.java | 82 +
.../gnu/java/net/loader/FileURLLoader.java | 145 ++
.../gnu/java/net/loader/JarURLLoader.java | 215 ++
.../gnu/java/net/loader/JarURLResource.java | 94 +
.../gnu/java/net/loader/RemoteResource.java | 78 +
.../gnu/java/net/loader/RemoteURLLoader.java | 101 +
.../classpath/gnu/java/net/loader/Resource.java | 110 +
.../classpath/gnu/java/net/loader/URLLoader.java | 147 ++
.../gnu/java/net/loader/URLStreamHandlerCache.java | 84 +
.../classpath/gnu/java/net/local/LocalSocket.java | 5 +-
.../gnu/java/net/local/LocalSocketImpl.java | 19 +-
.../gnu/java/net/protocol/http/HTTPConnection.java | 5 +-
.../java/net/protocol/http/HTTPURLConnection.java | 28 +-
.../gnu/java/net/protocol/jar/Connection.java | 2 +-
libjava/classpath/gnu/java/nio/PipeImpl.java | 32 +-
.../classpath/gnu/java/nio/SelectionKeyImpl.java | 22 +-
libjava/classpath/gnu/java/nio/SelectorImpl.java | 9 +-
.../java/nio/SocketChannelSelectionKeyImpl.java | 69 +
.../gnu/java/nio/channels/FileChannelImpl.java | 49 +-
.../classpath/gnu/java/nio/charset/Provider.java | 30 +-
.../gnu/java/rmi/server/ActivatableServerRef.java | 2 +-
.../gnu/java/rmi/server/UnicastServerRef.java | 2 +-
.../gnu/java/security/Configuration.java.in | 56 +
libjava/classpath/gnu/java/security/Engine.java | 56 +-
libjava/classpath/gnu/java/security/OID.java | 27 +-
.../classpath/gnu/java/security/PolicyFile.java | 23 +-
.../classpath/gnu/java/security/Properties.java | 160 +-
libjava/classpath/gnu/java/security/Registry.java | 69 +-
.../classpath/gnu/java/security/hash/BaseHash.java | 61 +-
.../gnu/java/security/hash/HashFactory.java | 89 +-
.../classpath/gnu/java/security/hash/Haval.java | 410 ++--
.../gnu/java/security/hash/IMessageDigest.java | 72 +-
libjava/classpath/gnu/java/security/hash/MD2.java | 163 +-
libjava/classpath/gnu/java/security/hash/MD4.java | 169 +-
libjava/classpath/gnu/java/security/hash/MD5.java | 166 +-
.../gnu/java/security/hash/RipeMD128.java | 148 +-
.../gnu/java/security/hash/RipeMD160.java | 163 +-
.../classpath/gnu/java/security/hash/Sha160.java | 141 +-
.../classpath/gnu/java/security/hash/Sha256.java | 150 +-
.../classpath/gnu/java/security/hash/Sha384.java | 203 +-
.../classpath/gnu/java/security/hash/Sha512.java | 209 +-
.../classpath/gnu/java/security/hash/Tiger.java | 1339 ++++++------
.../gnu/java/security/hash/Whirlpool.java | 177 +-
.../gnu/java/security/jce/hash/HavalSpi.java | 20 +-
.../gnu/java/security/jce/hash/MD2Spi.java | 20 +-
.../gnu/java/security/jce/hash/MD4Spi.java | 20 +-
.../gnu/java/security/jce/hash/MD5Spi.java | 18 +-
.../security/jce/hash/MessageDigestAdapter.java | 50 +-
.../gnu/java/security/jce/hash/RipeMD128Spi.java | 18 +-
.../gnu/java/security/jce/hash/RipeMD160Spi.java | 18 +-
.../gnu/java/security/jce/hash/Sha160Spi.java | 18 +-
.../gnu/java/security/jce/hash/Sha256Spi.java | 20 +-
.../gnu/java/security/jce/hash/Sha384Spi.java | 20 +-
.../gnu/java/security/jce/hash/Sha512Spi.java | 20 +-
.../gnu/java/security/jce/hash/TigerSpi.java | 20 +-
.../gnu/java/security/jce/hash/WhirlpoolSpi.java | 18 +-
.../gnu/java/security/jce/prng/HavalRandomSpi.java | 18 +-
.../gnu/java/security/jce/prng/MD2RandomSpi.java | 18 +-
.../gnu/java/security/jce/prng/MD4RandomSpi.java | 18 +-
.../gnu/java/security/jce/prng/MD5RandomSpi.java | 18 +-
.../java/security/jce/prng/RipeMD128RandomSpi.java | 20 +-
.../java/security/jce/prng/RipeMD160RandomSpi.java | 18 +-
.../security/jce/prng/SecureRandomAdapter.java | 53 +-
.../java/security/jce/prng/Sha160RandomSpi.java | 18 +-
.../java/security/jce/prng/Sha256RandomSpi.java | 20 +-
.../java/security/jce/prng/Sha384RandomSpi.java | 20 +-
.../java/security/jce/prng/Sha512RandomSpi.java | 20 +-
.../gnu/java/security/jce/prng/TigerRandomSpi.java | 18 +-
.../java/security/jce/prng/WhirlpoolRandomSpi.java | 18 +-
.../gnu/java/security/jce/sig/DSSKeyFactory.java | 35 +-
.../security/jce/sig/DSSKeyPairGeneratorSpi.java | 63 +-
.../gnu/java/security/jce/sig/DSSParameters.java | 2 -
.../java/security/jce/sig/DSSRawSignatureSpi.java | 22 +-
.../java/security/jce/sig/EncodedKeyFactory.java | 97 +-
.../security/jce/sig/KeyPairGeneratorAdapter.java | 44 +-
.../gnu/java/security/jce/sig/RSAKeyFactory.java | 50 +-
.../security/jce/sig/RSAKeyPairGeneratorSpi.java | 47 +-
.../security/jce/sig/RSAPSSRawSignatureSpi.java | 21 +-
.../java/security/jce/sig/SignatureAdapter.java | 75 +-
.../gnu/java/security/key/IKeyPairCodec.java | 56 +-
.../gnu/java/security/key/IKeyPairGenerator.java | 23 +-
.../gnu/java/security/key/KeyPairCodecFactory.java | 2 -
.../java/security/key/KeyPairGeneratorFactory.java | 61 +-
.../gnu/java/security/key/dss/DSSKey.java | 128 +-
.../java/security/key/dss/DSSKeyPairGenerator.java | 259 +--
.../security/key/dss/DSSKeyPairPKCS8Codec.java | 20 +-
.../java/security/key/dss/DSSKeyPairRawCodec.java | 250 +--
.../java/security/key/dss/DSSKeyPairX509Codec.java | 98 +-
.../gnu/java/security/key/dss/DSSPrivateKey.java | 78 +-
.../gnu/java/security/key/dss/DSSPublicKey.java | 72 +-
.../gnu/java/security/key/dss/FIPS186.java | 108 +-
.../gnu/java/security/key/rsa/GnuRSAKey.java | 72 +-
.../java/security/key/rsa/GnuRSAPrivateKey.java | 119 +-
.../gnu/java/security/key/rsa/GnuRSAPublicKey.java | 74 +-
.../java/security/key/rsa/RSAKeyPairGenerator.java | 110 +-
.../security/key/rsa/RSAKeyPairPKCS8Codec.java | 58 +-
.../java/security/key/rsa/RSAKeyPairRawCodec.java | 210 +-
.../java/security/key/rsa/RSAKeyPairX509Codec.java | 21 +-
.../gnu/java/security/pkcs/PKCS7SignedData.java | 66 +-
.../gnu/java/security/pkcs/SignerInfo.java | 79 +-
.../classpath/gnu/java/security/prng/BasePRNG.java | 39 +-
.../gnu/java/security/prng/EntropySource.java | 1 -
.../classpath/gnu/java/security/prng/IRandom.java | 156 +-
.../java/security/prng/LimitReachedException.java | 18 +-
.../gnu/java/security/prng/MDGenerator.java | 60 +-
.../gnu/java/security/prng/PRNGFactory.java | 41 +-
.../gnu/java/security/prng/RandomEvent.java | 11 +-
.../java/security/prng/RandomEventListener.java | 8 +-
.../classpath/gnu/java/security/provider/Gnu.java | 82 +-
.../provider/PKIXCertPathValidatorImpl.java | 253 ++-
.../security/provider/X509CertificateFactory.java | 61 +-
.../gnu/java/security/sig/BaseSignature.java | 98 +-
.../gnu/java/security/sig/ISignature.java | 111 +-
.../gnu/java/security/sig/ISignatureCodec.java | 11 +-
.../gnu/java/security/sig/SignatureFactory.java | 24 +-
.../gnu/java/security/sig/dss/DSSSignature.java | 204 +-
.../security/sig/dss/DSSSignatureRawCodec.java | 105 +-
.../gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java | 142 +-
.../gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java | 190 +-
.../gnu/java/security/sig/rsa/EMSA_PSS.java | 267 +--
.../classpath/gnu/java/security/sig/rsa/RSA.java | 182 +-
.../security/sig/rsa/RSAPKCS1V1_5Signature.java | 145 +-
.../gnu/java/security/sig/rsa/RSAPSSSignature.java | 219 +-
.../security/sig/rsa/RSAPSSSignatureRawCodec.java | 79 +-
.../classpath/gnu/java/security/util/Base64.java | 237 +--
.../gnu/java/security/util/ByteArray.java | 109 +
.../gnu/java/security/util/ExpirableObject.java | 70 +-
.../gnu/java/security/util/IntegerUtil.java | 109 +
libjava/classpath/gnu/java/security/util/PRNG.java | 31 +-
.../classpath/gnu/java/security/util/Prime2.java | 417 ----
.../classpath/gnu/java/security/util/Sequence.java | 64 +-
.../gnu/java/security/util/SimpleList.java | 50 +-
libjava/classpath/gnu/java/security/util/Util.java | 353 ++--
libjava/classpath/gnu/java/security/x509/Util.java | 4 +-
.../classpath/gnu/java/security/x509/X509CRL.java | 73 +-
.../gnu/java/security/x509/X509CRLEntry.java | 41 +-
.../gnu/java/security/x509/X509Certificate.java | 16 +-
.../gnu/java/security/x509/ext/Extension.java | 26 +-
.../gnu/java/security/x509/ext/GeneralNames.java | 5 +-
.../gnu/java/util/prefs/EventDispatcher.java | 3 +-
.../gnu/java/util/prefs/GConfBasedFactory.java | 78 +
.../gnu/java/util/prefs/GConfBasedPreferences.java | 412 ++++
.../gnu/java/util/prefs/gconf/GConfNativePeer.java | 298 +++
.../gnu/java/util/regex/BacktrackStack.java | 112 ++
.../classpath/gnu/java/util/regex/CharIndexed.java | 116 ++
.../gnu/java/util/regex/CharIndexedCharArray.java | 46 +
.../java/util/regex/CharIndexedCharSequence.java | 82 +
.../java/util/regex/CharIndexedInputStream.java | 181 ++
.../gnu/java/util/regex/CharIndexedString.java | 44 +
.../java/util/regex/CharIndexedStringBuffer.java | 45 +
libjava/classpath/gnu/java/util/regex/RE.java | 2128 ++++++++++++++++++++
.../classpath/gnu/java/util/regex/REException.java | 182 ++
.../gnu/java/util/regex/REFilterInputStream.java | 140 ++
libjava/classpath/gnu/java/util/regex/REMatch.java | 324 +++
.../gnu/java/util/regex/REMatchEnumeration.java | 135 ++
.../classpath/gnu/java/util/regex/RESyntax.java | 563 ++++++
libjava/classpath/gnu/java/util/regex/REToken.java | 189 ++
.../classpath/gnu/java/util/regex/RETokenAny.java | 99 +
.../gnu/java/util/regex/RETokenBackRef.java | 86 +
.../classpath/gnu/java/util/regex/RETokenChar.java | 128 ++
.../classpath/gnu/java/util/regex/RETokenEnd.java | 109 +
.../java/util/regex/RETokenEndOfPreviousMatch.java | 72 +
.../gnu/java/util/regex/RETokenEndSub.java | 66 +
.../gnu/java/util/regex/RETokenIndependent.java | 78 +
.../gnu/java/util/regex/RETokenLookAhead.java | 80 +
.../gnu/java/util/regex/RETokenLookBehind.java | 118 ++
.../gnu/java/util/regex/RETokenNamedProperty.java | 315 +++
.../gnu/java/util/regex/RETokenOneOf.java | 280 +++
.../gnu/java/util/regex/RETokenPOSIX.java | 167 ++
.../gnu/java/util/regex/RETokenRange.java | 100 +
.../gnu/java/util/regex/RETokenRepeated.java | 427 ++++
.../gnu/java/util/regex/RETokenStart.java | 121 ++
.../gnu/java/util/regex/RETokenWordBoundary.java | 116 ++
.../classpath/gnu/java/util/regex/UncheckedRE.java | 109 +
.../classpath/gnu/javax/crypto/RSACipherImpl.java | 211 +-
.../gnu/javax/crypto/assembly/Assembly.java | 109 +-
.../gnu/javax/crypto/assembly/Cascade.java | 203 +-
.../gnu/javax/crypto/assembly/CascadeStage.java | 22 +-
.../javax/crypto/assembly/CascadeTransformer.java | 24 +-
.../javax/crypto/assembly/DeflateTransformer.java | 124 +-
.../gnu/javax/crypto/assembly/Direction.java | 30 +-
.../javax/crypto/assembly/LoopbackTransformer.java | 20 +-
.../gnu/javax/crypto/assembly/ModeStage.java | 33 +-
.../gnu/javax/crypto/assembly/Operation.java | 32 +-
.../javax/crypto/assembly/PaddingTransformer.java | 52 +-
.../classpath/gnu/javax/crypto/assembly/Stage.java | 103 +-
.../gnu/javax/crypto/assembly/Transformer.java | 194 +-
.../crypto/assembly/TransformerException.java | 58 +-
.../classpath/gnu/javax/crypto/cipher/Anubis.java | 532 ++---
.../gnu/javax/crypto/cipher/BaseCipher.java | 127 +-
.../gnu/javax/crypto/cipher/Blowfish.java | 842 ++++----
.../classpath/gnu/javax/crypto/cipher/Cast5.java | 1290 ++++--------
.../gnu/javax/crypto/cipher/CipherFactory.java | 96 +-
libjava/classpath/gnu/javax/crypto/cipher/DES.java | 758 +++----
.../gnu/javax/crypto/cipher/IBlockCipher.java | 130 +-
.../gnu/javax/crypto/cipher/IBlockCipherSpi.java | 64 +-
.../classpath/gnu/javax/crypto/cipher/Khazad.java | 450 ++---
.../gnu/javax/crypto/cipher/NullCipher.java | 45 +-
.../gnu/javax/crypto/cipher/Rijndael.java | 783 +++----
.../classpath/gnu/javax/crypto/cipher/Serpent.java | 249 +--
.../classpath/gnu/javax/crypto/cipher/Square.java | 415 ++--
.../gnu/javax/crypto/cipher/TripleDES.java | 199 +-
.../classpath/gnu/javax/crypto/cipher/Twofish.java | 678 +++----
.../gnu/javax/crypto/cipher/WeakKeyException.java | 22 +-
.../gnu/javax/crypto/jce/DiffieHellmanImpl.java | 67 +-
.../classpath/gnu/javax/crypto/jce/GnuCrypto.java | 182 +-
.../classpath/gnu/javax/crypto/jce/GnuSasl.java | 94 +-
.../javax/crypto/jce/PBKDF2SecretKeyFactory.java | 77 +-
.../javax/crypto/jce/cipher/AES128KeyWrapSpi.java | 54 +
.../javax/crypto/jce/cipher/AES192KeyWrapSpi.java | 54 +
.../javax/crypto/jce/cipher/AES256KeyWrapSpi.java | 54 +
.../gnu/javax/crypto/jce/cipher/AESKeyWrapSpi.java | 88 +
.../gnu/javax/crypto/jce/cipher/AESSpi.java | 24 +-
.../gnu/javax/crypto/jce/cipher/ARCFourSpi.java | 49 +-
.../gnu/javax/crypto/jce/cipher/AnubisSpi.java | 7 +-
.../gnu/javax/crypto/jce/cipher/BlowfishSpi.java | 7 +-
.../gnu/javax/crypto/jce/cipher/Cast5Spi.java | 20 +-
.../gnu/javax/crypto/jce/cipher/CipherAdapter.java | 285 +--
.../gnu/javax/crypto/jce/cipher/DESSpi.java | 11 +-
.../jce/cipher/KeyWrappingAlgorithmAdapter.java | 423 ++++
.../gnu/javax/crypto/jce/cipher/KhazadSpi.java | 7 +-
.../gnu/javax/crypto/jce/cipher/NullCipherSpi.java | 7 +-
.../gnu/javax/crypto/jce/cipher/PBES2.java | 513 ++---
.../gnu/javax/crypto/jce/cipher/RijndaelSpi.java | 7 +-
.../gnu/javax/crypto/jce/cipher/SerpentSpi.java | 7 +-
.../gnu/javax/crypto/jce/cipher/SquareSpi.java | 7 +-
.../crypto/jce/cipher/TripleDESKeyWrapSpi.java | 54 +
.../gnu/javax/crypto/jce/cipher/TripleDESSpi.java | 7 +-
.../gnu/javax/crypto/jce/cipher/TwofishSpi.java | 7 +-
.../crypto/jce/key/AnubisKeyGeneratorImpl.java | 11 +-
.../crypto/jce/key/AnubisSecretKeyFactoryImpl.java | 10 +-
.../crypto/jce/key/BlowfishKeyGeneratorImpl.java | 11 +-
.../jce/key/BlowfishSecretKeyFactoryImpl.java | 10 +-
.../crypto/jce/key/Cast5KeyGeneratorImpl.java | 11 +-
.../crypto/jce/key/Cast5SecretKeyFactoryImpl.java | 10 +-
.../javax/crypto/jce/key/DESKeyGeneratorImpl.java | 31 +-
.../crypto/jce/key/DESSecretKeyFactoryImpl.java | 28 +-
.../crypto/jce/key/DESedeSecretKeyFactoryImpl.java | 28 +-
.../crypto/jce/key/KhazadKeyGeneratorImpl.java | 12 +-
.../crypto/jce/key/KhazadSecretKeyFactoryImpl.java | 11 +-
.../crypto/jce/key/RijndaelKeyGeneratorImpl.java | 12 +-
.../jce/key/RijndaelSecretKeyFactoryImpl.java | 11 +-
.../javax/crypto/jce/key/SecretKeyFactoryImpl.java | 34 +-
.../crypto/jce/key/SecretKeyGeneratorImpl.java | 58 +-
.../crypto/jce/key/SerpentKeyGeneratorImpl.java | 12 +-
.../jce/key/SerpentSecretKeyFactoryImpl.java | 11 +-
.../crypto/jce/key/SquareKeyGeneratorImpl.java | 12 +-
.../crypto/jce/key/SquareSecretKeyFactoryImpl.java | 11 +-
.../crypto/jce/key/TripleDESKeyGeneratorImpl.java | 12 +-
.../crypto/jce/key/TwofishKeyGeneratorImpl.java | 12 +-
.../jce/key/TwofishSecretKeyFactoryImpl.java | 11 +-
.../gnu/javax/crypto/jce/keyring/GnuKeyring.java | 266 ++-
.../gnu/javax/crypto/jce/mac/HMacHavalSpi.java | 21 +-
.../gnu/javax/crypto/jce/mac/HMacMD2Spi.java | 7 +-
.../gnu/javax/crypto/jce/mac/HMacMD4Spi.java | 7 +-
.../gnu/javax/crypto/jce/mac/HMacMD5Spi.java | 7 +-
.../gnu/javax/crypto/jce/mac/HMacRipeMD128Spi.java | 7 +-
.../gnu/javax/crypto/jce/mac/HMacRipeMD160Spi.java | 7 +-
.../gnu/javax/crypto/jce/mac/HMacSHA160Spi.java | 7 +-
.../gnu/javax/crypto/jce/mac/HMacSHA256Spi.java | 21 +-
.../gnu/javax/crypto/jce/mac/HMacSHA384Spi.java | 21 +-
.../gnu/javax/crypto/jce/mac/HMacSHA512Spi.java | 21 +-
.../gnu/javax/crypto/jce/mac/HMacTigerSpi.java | 7 +-
.../gnu/javax/crypto/jce/mac/HMacWhirlpoolSpi.java | 7 +-
.../gnu/javax/crypto/jce/mac/MacAdapter.java | 44 +-
.../gnu/javax/crypto/jce/mac/OMacAnubisImpl.java | 9 +-
.../gnu/javax/crypto/jce/mac/OMacBlowfishImpl.java | 9 +-
.../gnu/javax/crypto/jce/mac/OMacCast5Impl.java | 9 +-
.../gnu/javax/crypto/jce/mac/OMacDESImpl.java | 9 +-
.../gnu/javax/crypto/jce/mac/OMacImpl.java | 43 +-
.../gnu/javax/crypto/jce/mac/OMacKhazadImpl.java | 9 +-
.../gnu/javax/crypto/jce/mac/OMacRijndaelImpl.java | 9 +-
.../gnu/javax/crypto/jce/mac/OMacSerpentImpl.java | 9 +-
.../gnu/javax/crypto/jce/mac/OMacSquareImpl.java | 9 +-
.../javax/crypto/jce/mac/OMacTripleDESImpl.java | 9 +-
.../gnu/javax/crypto/jce/mac/OMacTwofishImpl.java | 9 +-
.../gnu/javax/crypto/jce/mac/TMMH16Spi.java | 16 +-
.../gnu/javax/crypto/jce/mac/UHash32Spi.java | 7 +-
.../gnu/javax/crypto/jce/mac/UMac32Spi.java | 22 +-
.../crypto/jce/params/BlockCipherParameters.java | 146 +-
.../crypto/jce/params/DEREncodingException.java | 5 +-
.../gnu/javax/crypto/jce/params/DERReader.java | 35 +-
.../gnu/javax/crypto/jce/params/DERWriter.java | 29 +-
.../javax/crypto/jce/prng/ARCFourRandomSpi.java | 33 +-
.../gnu/javax/crypto/jce/prng/CSPRNGSpi.java | 38 +-
.../gnu/javax/crypto/jce/prng/FortunaImpl.java | 26 +-
.../gnu/javax/crypto/jce/prng/ICMRandomSpi.java | 125 +-
.../gnu/javax/crypto/jce/prng/UMacRandomSpi.java | 83 +-
.../gnu/javax/crypto/jce/sig/DHKeyFactory.java | 29 +-
.../crypto/jce/sig/DHKeyPairGeneratorSpi.java | 6 +-
.../crypto/jce/spec/BlockCipherParameterSpec.java | 57 +-
.../javax/crypto/jce/spec/TMMHParameterSpec.java | 40 +-
.../javax/crypto/jce/spec/UMac32ParameterSpec.java | 25 +-
.../javax/crypto/key/BaseKeyAgreementParty.java | 88 +-
.../gnu/javax/crypto/key/GnuSecretKey.java | 48 +-
.../gnu/javax/crypto/key/IKeyAgreementParty.java | 43 +-
.../gnu/javax/crypto/key/IncomingMessage.java | 114 +-
.../javax/crypto/key/KeyAgreementException.java | 107 +-
.../gnu/javax/crypto/key/KeyAgreementFactory.java | 88 +-
.../gnu/javax/crypto/key/OutgoingMessage.java | 79 +-
.../javax/crypto/key/dh/DHKeyPairPKCS8Codec.java | 11 +
.../gnu/javax/crypto/key/dh/DHKeyPairRawCodec.java | 286 ++-
.../javax/crypto/key/dh/DHKeyPairX509Codec.java | 11 +
.../crypto/key/dh/DiffieHellmanKeyAgreement.java | 91 +-
.../javax/crypto/key/dh/DiffieHellmanReceiver.java | 50 +-
.../javax/crypto/key/dh/DiffieHellmanSender.java | 51 +-
.../javax/crypto/key/dh/ElGamalKeyAgreement.java | 91 +-
.../gnu/javax/crypto/key/dh/ElGamalReceiver.java | 36 +-
.../gnu/javax/crypto/key/dh/ElGamalSender.java | 34 +-
.../gnu/javax/crypto/key/dh/GnuDHKey.java | 106 +-
.../javax/crypto/key/dh/GnuDHKeyPairGenerator.java | 120 +-
.../gnu/javax/crypto/key/dh/GnuDHPrivateKey.java | 86 +-
.../gnu/javax/crypto/key/dh/GnuDHPublicKey.java | 82 +-
.../classpath/gnu/javax/crypto/key/dh/RFC2631.java | 98 +-
.../gnu/javax/crypto/key/srp6/SRP6Host.java | 82 +-
.../javax/crypto/key/srp6/SRP6KeyAgreement.java | 113 +-
.../gnu/javax/crypto/key/srp6/SRP6SaslClient.java | 53 +-
.../gnu/javax/crypto/key/srp6/SRP6SaslServer.java | 53 +-
.../gnu/javax/crypto/key/srp6/SRP6TLSClient.java | 62 +-
.../gnu/javax/crypto/key/srp6/SRP6TLSServer.java | 69 +-
.../gnu/javax/crypto/key/srp6/SRP6User.java | 72 +-
.../gnu/javax/crypto/key/srp6/SRPAlgorithm.java | 136 +-
.../gnu/javax/crypto/key/srp6/SRPKey.java | 79 +-
.../javax/crypto/key/srp6/SRPKeyPairGenerator.java | 127 +-
.../javax/crypto/key/srp6/SRPKeyPairRawCodec.java | 292 ++-
.../gnu/javax/crypto/key/srp6/SRPPrivateKey.java | 129 +-
.../gnu/javax/crypto/key/srp6/SRPPublicKey.java | 95 +-
.../javax/crypto/keyring/AuthenticatedEntry.java | 108 +-
.../gnu/javax/crypto/keyring/BaseKeyring.java | 78 +-
.../gnu/javax/crypto/keyring/BinaryDataEntry.java | 39 +-
.../gnu/javax/crypto/keyring/CertPathEntry.java | 31 +-
.../gnu/javax/crypto/keyring/CertificateEntry.java | 42 +-
.../gnu/javax/crypto/keyring/CompressedEntry.java | 34 +-
.../gnu/javax/crypto/keyring/EncryptedEntry.java | 90 +-
.../classpath/gnu/javax/crypto/keyring/Entry.java | 81 +-
.../gnu/javax/crypto/keyring/EnvelopeEntry.java | 275 +--
.../javax/crypto/keyring/GnuPrivateKeyring.java | 185 +-
.../gnu/javax/crypto/keyring/GnuPublicKeyring.java | 69 +-
.../gnu/javax/crypto/keyring/IKeyring.java | 102 +-
.../gnu/javax/crypto/keyring/IPrivateKeyring.java | 76 +-
.../gnu/javax/crypto/keyring/IPublicKeyring.java | 35 +-
.../crypto/keyring/MalformedKeyringException.java | 7 +-
.../crypto/keyring/MaskableEnvelopeEntry.java | 57 +-
.../javax/crypto/keyring/MeteredInputStream.java | 18 +-
.../crypto/keyring/PasswordAuthenticatedEntry.java | 203 +-
.../crypto/keyring/PasswordEncryptedEntry.java | 174 +-
.../crypto/keyring/PasswordProtectedEntry.java | 15 +-
.../gnu/javax/crypto/keyring/PrimitiveEntry.java | 41 +-
.../gnu/javax/crypto/keyring/PrivateKeyEntry.java | 79 +-
.../gnu/javax/crypto/keyring/Properties.java | 68 +-
.../gnu/javax/crypto/keyring/PublicKeyEntry.java | 62 +-
.../classpath/gnu/javax/crypto/kwa/AESKeyWrap.java | 168 ++
.../javax/crypto/kwa/BaseKeyWrappingAlgorithm.java | 145 ++
.../javax/crypto/kwa/IKeyWrappingAlgorithm.java | 160 ++
.../javax/crypto/kwa/KeyUnwrappingException.java | 67 +
.../crypto/kwa/KeyWrappingAlgorithmFactory.java | 110 +
.../gnu/javax/crypto/kwa/TripleDESKeyWrap.java | 292 +++
.../classpath/gnu/javax/crypto/mac/BaseMac.java | 43 +-
libjava/classpath/gnu/javax/crypto/mac/HMac.java | 195 +-
.../gnu/javax/crypto/mac/HMacFactory.java | 65 +-
libjava/classpath/gnu/javax/crypto/mac/IMac.java | 154 +-
.../classpath/gnu/javax/crypto/mac/MacFactory.java | 78 +-
.../gnu/javax/crypto/mac/MacInputStream.java | 42 +-
.../gnu/javax/crypto/mac/MacOutputStream.java | 59 +-
libjava/classpath/gnu/javax/crypto/mac/OMAC.java | 211 +-
libjava/classpath/gnu/javax/crypto/mac/TMMH16.java | 195 +-
.../classpath/gnu/javax/crypto/mac/UHash32.java | 499 ++---
libjava/classpath/gnu/javax/crypto/mac/UMac32.java | 287 +--
.../classpath/gnu/javax/crypto/mode/BaseMode.java | 153 +-
libjava/classpath/gnu/javax/crypto/mode/CBC.java | 62 +-
libjava/classpath/gnu/javax/crypto/mode/CFB.java | 116 +-
libjava/classpath/gnu/javax/crypto/mode/CTR.java | 127 +-
libjava/classpath/gnu/javax/crypto/mode/EAX.java | 127 +-
libjava/classpath/gnu/javax/crypto/mode/ECB.java | 74 +-
.../gnu/javax/crypto/mode/IAuthenticatedMode.java | 18 +-
libjava/classpath/gnu/javax/crypto/mode/ICM.java | 139 +-
libjava/classpath/gnu/javax/crypto/mode/IMode.java | 114 +-
.../gnu/javax/crypto/mode/ModeFactory.java | 95 +-
libjava/classpath/gnu/javax/crypto/mode/OFB.java | 128 +-
.../classpath/gnu/javax/crypto/pad/BasePad.java | 148 +-
libjava/classpath/gnu/javax/crypto/pad/IPad.java | 63 +-
.../classpath/gnu/javax/crypto/pad/ISO10126.java | 109 +
.../classpath/gnu/javax/crypto/pad/PKCS1_V1_5.java | 90 +-
libjava/classpath/gnu/javax/crypto/pad/PKCS7.java | 174 +-
.../classpath/gnu/javax/crypto/pad/PadFactory.java | 87 +-
libjava/classpath/gnu/javax/crypto/pad/SSL3.java | 44 +-
libjava/classpath/gnu/javax/crypto/pad/TBC.java | 104 +-
libjava/classpath/gnu/javax/crypto/pad/TLS1.java | 52 +-
.../javax/crypto/pad/WrongPaddingException.java | 21 +-
.../classpath/gnu/javax/crypto/prng/ARCFour.java | 88 +-
.../classpath/gnu/javax/crypto/prng/CSPRNG.java | 1019 ++++------
.../classpath/gnu/javax/crypto/prng/Fortuna.java | 110 +-
.../gnu/javax/crypto/prng/ICMGenerator.java | 252 +--
.../classpath/gnu/javax/crypto/prng/PBKDF2.java | 103 +-
.../gnu/javax/crypto/prng/PRNGFactory.java | 66 +-
.../gnu/javax/crypto/prng/UMacGenerator.java | 136 +-
.../classpath/gnu/javax/crypto/sasl/AuthInfo.java | 40 +-
.../javax/crypto/sasl/AuthInfoProviderFactory.java | 34 +-
.../gnu/javax/crypto/sasl/ClientFactory.java | 86 +-
.../gnu/javax/crypto/sasl/ClientMechanism.java | 150 +-
.../crypto/sasl/ConfidentialityException.java | 12 +-
.../gnu/javax/crypto/sasl/IAuthInfoProvider.java | 59 +-
.../crypto/sasl/IAuthInfoProviderFactory.java | 17 +-
.../sasl/IllegalMechanismStateException.java | 8 +-
.../gnu/javax/crypto/sasl/InputBuffer.java | 211 +-
.../gnu/javax/crypto/sasl/IntegrityException.java | 10 +-
.../crypto/sasl/NoSuchMechanismException.java | 10 +-
.../gnu/javax/crypto/sasl/NoSuchUserException.java | 10 +-
.../gnu/javax/crypto/sasl/OutputBuffer.java | 113 +-
.../javax/crypto/sasl/SaslEncodingException.java | 8 +-
.../gnu/javax/crypto/sasl/SaslInputStream.java | 316 ++-
.../gnu/javax/crypto/sasl/SaslOutputStream.java | 123 +-
.../classpath/gnu/javax/crypto/sasl/SaslUtil.java | 16 +-
.../gnu/javax/crypto/sasl/ServerFactory.java | 76 +-
.../gnu/javax/crypto/sasl/ServerMechanism.java | 157 +-
.../crypto/sasl/UserAlreadyExistsException.java | 6 +-
.../crypto/sasl/anonymous/AnonymousClient.java | 36 +-
.../crypto/sasl/anonymous/AnonymousServer.java | 27 +-
.../javax/crypto/sasl/anonymous/AnonymousUtil.java | 44 +-
.../sasl/crammd5/CramMD5AuthInfoProvider.java | 62 +-
.../javax/crypto/sasl/crammd5/CramMD5Client.java | 63 +-
.../javax/crypto/sasl/crammd5/CramMD5Registry.java | 8 +-
.../javax/crypto/sasl/crammd5/CramMD5Server.java | 51 +-
.../gnu/javax/crypto/sasl/crammd5/CramMD5Util.java | 33 +-
.../javax/crypto/sasl/crammd5/PasswordFile.java | 121 +-
.../gnu/javax/crypto/sasl/plain/PasswordFile.java | 150 +-
.../crypto/sasl/plain/PlainAuthInfoProvider.java | 72 +-
.../gnu/javax/crypto/sasl/plain/PlainClient.java | 73 +-
.../gnu/javax/crypto/sasl/plain/PlainRegistry.java | 12 +-
.../gnu/javax/crypto/sasl/plain/PlainServer.java | 83 +-
.../classpath/gnu/javax/crypto/sasl/srp/CALG.java | 173 +-
.../gnu/javax/crypto/sasl/srp/ClientStore.java | 66 +-
.../classpath/gnu/javax/crypto/sasl/srp/IALG.java | 49 +-
.../classpath/gnu/javax/crypto/sasl/srp/KDF.java | 69 +-
.../gnu/javax/crypto/sasl/srp/PasswordFile.java | 308 ++-
.../classpath/gnu/javax/crypto/sasl/srp/SRP.java | 94 +-
.../javax/crypto/sasl/srp/SRPAuthInfoProvider.java | 77 +-
.../gnu/javax/crypto/sasl/srp/SRPClient.java | 795 +++-----
.../gnu/javax/crypto/sasl/srp/SRPRegistry.java | 80 +-
.../gnu/javax/crypto/sasl/srp/SRPServer.java | 814 +++-----
.../gnu/javax/crypto/sasl/srp/SecurityContext.java | 28 +-
.../gnu/javax/crypto/sasl/srp/ServerStore.java | 73 +-
.../gnu/javax/crypto/sasl/srp/StoreEntry.java | 24 +-
.../gnu/javax/imageio/IIOInputStream.java | 102 +
.../classpath/gnu/javax/imageio/gif/GIFFile.java | 709 +++++++
.../gnu/javax/imageio/gif/GIFImageReader.java | 241 +++
.../gnu/javax/imageio/gif/GIFImageReaderSpi.java | 124 ++
libjava/classpath/gnu/javax/imageio/jpeg/DCT.java | 347 ++++
.../gnu/javax/imageio/jpeg/HuffmanTable.java | 207 ++
.../gnu/javax/imageio/jpeg/JPEGComponent.java | 351 ++++
.../gnu/javax/imageio/jpeg/JPEGDecoder.java | 630 ++++++
.../gnu/javax/imageio/jpeg/JPEGException.java | 55 +
.../gnu/javax/imageio/jpeg/JPEGFrame.java | 108 +
.../javax/imageio/jpeg/JPEGImageInputStream.java | 195 ++
.../gnu/javax/imageio/jpeg/JPEGImageReader.java | 141 ++
.../gnu/javax/imageio/jpeg/JPEGImageReaderSpi.java | 137 ++
.../gnu/javax/imageio/jpeg/JPEGMarker.java | 205 ++
.../imageio/jpeg/JPEGMarkerFoundException.java | 50 +
.../classpath/gnu/javax/imageio/jpeg/JPEGScan.java | 151 ++
.../gnu/javax/imageio/jpeg/YCbCr_ColorSpace.java | 113 ++
.../classpath/gnu/javax/imageio/jpeg/ZigZag.java | 520 +++++
.../classpath/gnu/javax/imageio/png/PNGChunk.java | 284 +++
.../classpath/gnu/javax/imageio/png/PNGData.java | 104 +
.../gnu/javax/imageio/png/PNGDecoder.java | 331 +++
.../gnu/javax/imageio/png/PNGEncoder.java | 235 +++
.../gnu/javax/imageio/png/PNGException.java | 48 +
.../classpath/gnu/javax/imageio/png/PNGFile.java | 258 +++
.../classpath/gnu/javax/imageio/png/PNGFilter.java | 237 +++
.../classpath/gnu/javax/imageio/png/PNGGamma.java | 89 +
.../classpath/gnu/javax/imageio/png/PNGHeader.java | 257 +++
.../gnu/javax/imageio/png/PNGICCProfile.java | 114 ++
.../gnu/javax/imageio/png/PNGImageReader.java | 224 +++
.../gnu/javax/imageio/png/PNGImageReaderSpi.java | 128 ++
.../gnu/javax/imageio/png/PNGPalette.java | 127 ++
.../classpath/gnu/javax/imageio/png/PNGPhys.java | 112 ++
.../classpath/gnu/javax/imageio/png/PNGTime.java | 83 +
.../gnu/javax/net/ssl/provider/KeyPool.java | 13 +-
libjava/classpath/gnu/javax/print/CupsServer.java | 31 +-
.../classpath/gnu/javax/print/ipp/IppRequest.java | 16 +-
.../auth/callback/ConsoleCallbackHandler.java | 2 +-
.../security/auth/login/ConfigFileParser.java | 72 +-
.../security/auth/login/ConfigFileTokenizer.java | 21 +-
.../security/auth/login/GnuConfiguration.java | 100 +-
.../sound/midi/file/ExtendedMidiFileFormat.java | 77 +
.../javax/sound/midi/file/MidiDataInputStream.java | 83 +
.../sound/midi/file/MidiDataOutputStream.java | 114 ++
.../gnu/javax/sound/midi/file/MidiFileReader.java | 378 ++++
.../gnu/javax/sound/midi/file/MidiFileWriter.java | 199 ++
.../gnu/javax/sound/sampled/AU/AUReader.java | 212 ++
.../gnu/javax/sound/sampled/WAV/WAVReader.java | 236 +++
.../gnu/javax/swing/plaf/gnu/GNULookAndFeel.java | 1 +
.../text/html/CharacterAttributeTranslator.java | 2 +-
.../swing/text/html/parser/GnuParserDelegator.java | 178 ++
.../javax/swing/text/html/parser/HTML_401F.java | 47 +-
.../swing/text/html/parser/HTML_401Swing.java | 91 +
.../text/html/parser/SmallHtmlAttributeSet.java | 2 -
.../swing/text/html/parser/htmlValidator.java | 39 +-
libjava/classpath/gnu/regexp/BacktrackStack.java | 112 --
libjava/classpath/gnu/regexp/CharIndexed.java | 116 --
.../classpath/gnu/regexp/CharIndexedCharArray.java | 46 -
.../gnu/regexp/CharIndexedCharSequence.java | 82 -
.../gnu/regexp/CharIndexedInputStream.java | 181 --
.../classpath/gnu/regexp/CharIndexedString.java | 44 -
.../gnu/regexp/CharIndexedStringBuffer.java | 45 -
libjava/classpath/gnu/regexp/RE.java | 2102 -------------------
libjava/classpath/gnu/regexp/REException.java | 182 --
.../classpath/gnu/regexp/REFilterInputStream.java | 140 --
libjava/classpath/gnu/regexp/REMatch.java | 324 ---
.../classpath/gnu/regexp/REMatchEnumeration.java | 135 --
libjava/classpath/gnu/regexp/RESyntax.java | 563 ------
libjava/classpath/gnu/regexp/REToken.java | 189 --
libjava/classpath/gnu/regexp/RETokenAny.java | 99 -
libjava/classpath/gnu/regexp/RETokenBackRef.java | 86 -
libjava/classpath/gnu/regexp/RETokenChar.java | 128 --
libjava/classpath/gnu/regexp/RETokenEnd.java | 89 -
.../gnu/regexp/RETokenEndOfPreviousMatch.java | 72 -
libjava/classpath/gnu/regexp/RETokenEndSub.java | 66 -
.../classpath/gnu/regexp/RETokenIndependent.java | 78 -
libjava/classpath/gnu/regexp/RETokenLookAhead.java | 80 -
.../classpath/gnu/regexp/RETokenLookBehind.java | 118 --
.../classpath/gnu/regexp/RETokenNamedProperty.java | 315 ---
libjava/classpath/gnu/regexp/RETokenOneOf.java | 280 ---
libjava/classpath/gnu/regexp/RETokenPOSIX.java | 167 --
libjava/classpath/gnu/regexp/RETokenRange.java | 100 -
libjava/classpath/gnu/regexp/RETokenRepeated.java | 427 ----
libjava/classpath/gnu/regexp/RETokenStart.java | 98 -
.../classpath/gnu/regexp/RETokenWordBoundary.java | 116 --
libjava/classpath/gnu/regexp/UncheckedRE.java | 109 -
libjava/classpath/gnu/xml/dom/DomIterator.java | 14 +-
libjava/classpath/gnu/xml/stream/SAXParser.java | 54 +-
libjava/classpath/gnu/xml/stream/XMLParser.java | 261 ++-
.../gnu/xml/transform/ApplyTemplatesNode.java | 2 +-
.../classpath/gnu/xml/transform/ForEachNode.java | 2 +-
.../gnu/xml/transform/TransformerImpl.java | 19 +-
665 files changed, 43284 insertions(+), 31669 deletions(-)
delete mode 100644 libjava/classpath/gnu/classpath/ByteArray.java
create mode 100644 libjava/classpath/gnu/classpath/debug/TeeInputStream.java
create mode 100644 libjava/classpath/gnu/classpath/debug/TeeOutputStream.java
create mode 100644 libjava/classpath/gnu/classpath/debug/TeeReader.java
create mode 100644 libjava/classpath/gnu/classpath/debug/TeeWriter.java
create mode 100644 libjava/classpath/gnu/classpath/jdwp/event/ClassUnloadEvent.java
create mode 100644 libjava/classpath/gnu/classpath/jdwp/event/ExceptionEvent.java
create mode 100644 libjava/classpath/gnu/classpath/jdwp/event/MethodEntryEvent.java
create mode 100644 libjava/classpath/gnu/classpath/jdwp/event/MethodExitEvent.java
create mode 100644 libjava/classpath/gnu/classpath/jdwp/event/SingleStepEvent.java
create mode 100644 libjava/classpath/gnu/java/awt/dnd/GtkMouseDragGestureRecognizer.java
create mode 100644 libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDragSourceContextPeer.java
create mode 100644 libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDropTargetContextPeer.java
create mode 100644 libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDropTargetPeer.java
delete mode 100644 libjava/classpath/gnu/java/awt/peer/ClasspathTextLayoutPeer.java
delete mode 100644 libjava/classpath/gnu/java/awt/peer/gtk/GdkTextLayout.java
delete mode 100644 libjava/classpath/gnu/java/awt/peer/gtk/GtkCheckboxGroupPeer.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/gtk/GtkMouseInfoPeer.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/GLGraphics.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/ImageConverter.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/KeyboardMapping.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XDialogPeer.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XEventPump.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XFontPeer.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XFontPeer2.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XFramePeer.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XGraphics.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XGraphics2D.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XGraphicsConfiguration.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XGraphicsDevice.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XGraphicsEnvironment.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XImage.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XLightweightPeer.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XToolkit.java
create mode 100644 libjava/classpath/gnu/java/awt/peer/x/XWindowPeer.java
create mode 100644 libjava/classpath/gnu/java/lang/management/BeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/ClassLoadingMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/CompilationMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/GarbageCollectorMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/MemoryMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/MemoryManagerMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/MemoryPoolMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/OperatingSystemMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/RuntimeMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/ThreadMXBeanImpl.java
create mode 100644 libjava/classpath/gnu/java/lang/management/package.html
create mode 100644 libjava/classpath/gnu/java/net/loader/FileResource.java
create mode 100644 libjava/classpath/gnu/java/net/loader/FileURLLoader.java
create mode 100644 libjava/classpath/gnu/java/net/loader/JarURLLoader.java
create mode 100644 libjava/classpath/gnu/java/net/loader/JarURLResource.java
create mode 100644 libjava/classpath/gnu/java/net/loader/RemoteResource.java
create mode 100644 libjava/classpath/gnu/java/net/loader/RemoteURLLoader.java
create mode 100644 libjava/classpath/gnu/java/net/loader/Resource.java
create mode 100644 libjava/classpath/gnu/java/net/loader/URLLoader.java
create mode 100644 libjava/classpath/gnu/java/net/loader/URLStreamHandlerCache.java
create mode 100644 libjava/classpath/gnu/java/nio/SocketChannelSelectionKeyImpl.java
create mode 100644 libjava/classpath/gnu/java/security/Configuration.java.in
create mode 100644 libjava/classpath/gnu/java/security/util/ByteArray.java
create mode 100644 libjava/classpath/gnu/java/security/util/IntegerUtil.java
delete mode 100644 libjava/classpath/gnu/java/security/util/Prime2.java
create mode 100644 libjava/classpath/gnu/java/util/prefs/GConfBasedFactory.java
create mode 100644 libjava/classpath/gnu/java/util/prefs/GConfBasedPreferences.java
create mode 100644 libjava/classpath/gnu/java/util/prefs/gconf/GConfNativePeer.java
create mode 100644 libjava/classpath/gnu/java/util/regex/BacktrackStack.java
create mode 100644 libjava/classpath/gnu/java/util/regex/CharIndexed.java
create mode 100644 libjava/classpath/gnu/java/util/regex/CharIndexedCharArray.java
create mode 100644 libjava/classpath/gnu/java/util/regex/CharIndexedCharSequence.java
create mode 100644 libjava/classpath/gnu/java/util/regex/CharIndexedInputStream.java
create mode 100644 libjava/classpath/gnu/java/util/regex/CharIndexedString.java
create mode 100644 libjava/classpath/gnu/java/util/regex/CharIndexedStringBuffer.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RE.java
create mode 100644 libjava/classpath/gnu/java/util/regex/REException.java
create mode 100644 libjava/classpath/gnu/java/util/regex/REFilterInputStream.java
create mode 100644 libjava/classpath/gnu/java/util/regex/REMatch.java
create mode 100644 libjava/classpath/gnu/java/util/regex/REMatchEnumeration.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RESyntax.java
create mode 100644 libjava/classpath/gnu/java/util/regex/REToken.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenAny.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenBackRef.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenChar.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenEnd.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenEndOfPreviousMatch.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenEndSub.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenIndependent.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenLookAhead.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenLookBehind.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenNamedProperty.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenOneOf.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenPOSIX.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenRange.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenRepeated.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenStart.java
create mode 100644 libjava/classpath/gnu/java/util/regex/RETokenWordBoundary.java
create mode 100644 libjava/classpath/gnu/java/util/regex/UncheckedRE.java
create mode 100644 libjava/classpath/gnu/javax/crypto/jce/cipher/AES128KeyWrapSpi.java
create mode 100644 libjava/classpath/gnu/javax/crypto/jce/cipher/AES192KeyWrapSpi.java
create mode 100644 libjava/classpath/gnu/javax/crypto/jce/cipher/AES256KeyWrapSpi.java
create mode 100644 libjava/classpath/gnu/javax/crypto/jce/cipher/AESKeyWrapSpi.java
create mode 100644 libjava/classpath/gnu/javax/crypto/jce/cipher/KeyWrappingAlgorithmAdapter.java
create mode 100644 libjava/classpath/gnu/javax/crypto/jce/cipher/TripleDESKeyWrapSpi.java
create mode 100644 libjava/classpath/gnu/javax/crypto/kwa/AESKeyWrap.java
create mode 100644 libjava/classpath/gnu/javax/crypto/kwa/BaseKeyWrappingAlgorithm.java
create mode 100644 libjava/classpath/gnu/javax/crypto/kwa/IKeyWrappingAlgorithm.java
create mode 100644 libjava/classpath/gnu/javax/crypto/kwa/KeyUnwrappingException.java
create mode 100644 libjava/classpath/gnu/javax/crypto/kwa/KeyWrappingAlgorithmFactory.java
create mode 100644 libjava/classpath/gnu/javax/crypto/kwa/TripleDESKeyWrap.java
create mode 100644 libjava/classpath/gnu/javax/crypto/pad/ISO10126.java
create mode 100644 libjava/classpath/gnu/javax/imageio/IIOInputStream.java
create mode 100644 libjava/classpath/gnu/javax/imageio/gif/GIFFile.java
create mode 100644 libjava/classpath/gnu/javax/imageio/gif/GIFImageReader.java
create mode 100644 libjava/classpath/gnu/javax/imageio/gif/GIFImageReaderSpi.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/DCT.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/HuffmanTable.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGComponent.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGDecoder.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGException.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGFrame.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGImageInputStream.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGImageReader.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGImageReaderSpi.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGMarker.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGMarkerFoundException.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/JPEGScan.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/YCbCr_ColorSpace.java
create mode 100644 libjava/classpath/gnu/javax/imageio/jpeg/ZigZag.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGChunk.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGData.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGDecoder.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGEncoder.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGException.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGFile.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGFilter.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGGamma.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGHeader.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGICCProfile.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGImageReader.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGImageReaderSpi.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGPalette.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGPhys.java
create mode 100644 libjava/classpath/gnu/javax/imageio/png/PNGTime.java
create mode 100644 libjava/classpath/gnu/javax/sound/midi/file/ExtendedMidiFileFormat.java
create mode 100644 libjava/classpath/gnu/javax/sound/midi/file/MidiDataInputStream.java
create mode 100644 libjava/classpath/gnu/javax/sound/midi/file/MidiDataOutputStream.java
create mode 100644 libjava/classpath/gnu/javax/sound/midi/file/MidiFileReader.java
create mode 100644 libjava/classpath/gnu/javax/sound/midi/file/MidiFileWriter.java
create mode 100644 libjava/classpath/gnu/javax/sound/sampled/AU/AUReader.java
create mode 100644 libjava/classpath/gnu/javax/sound/sampled/WAV/WAVReader.java
create mode 100644 libjava/classpath/gnu/javax/swing/text/html/parser/GnuParserDelegator.java
create mode 100644 libjava/classpath/gnu/javax/swing/text/html/parser/HTML_401Swing.java
delete mode 100644 libjava/classpath/gnu/regexp/BacktrackStack.java
delete mode 100644 libjava/classpath/gnu/regexp/CharIndexed.java
delete mode 100644 libjava/classpath/gnu/regexp/CharIndexedCharArray.java
delete mode 100644 libjava/classpath/gnu/regexp/CharIndexedCharSequence.java
delete mode 100644 libjava/classpath/gnu/regexp/CharIndexedInputStream.java
delete mode 100644 libjava/classpath/gnu/regexp/CharIndexedString.java
delete mode 100644 libjava/classpath/gnu/regexp/CharIndexedStringBuffer.java
delete mode 100644 libjava/classpath/gnu/regexp/RE.java
delete mode 100644 libjava/classpath/gnu/regexp/REException.java
delete mode 100644 libjava/classpath/gnu/regexp/REFilterInputStream.java
delete mode 100644 libjava/classpath/gnu/regexp/REMatch.java
delete mode 100644 libjava/classpath/gnu/regexp/REMatchEnumeration.java
delete mode 100644 libjava/classpath/gnu/regexp/RESyntax.java
delete mode 100644 libjava/classpath/gnu/regexp/REToken.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenAny.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenBackRef.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenChar.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenEnd.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenEndOfPreviousMatch.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenEndSub.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenIndependent.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenLookAhead.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenLookBehind.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenNamedProperty.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenOneOf.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenPOSIX.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenRange.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenRepeated.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenStart.java
delete mode 100644 libjava/classpath/gnu/regexp/RETokenWordBoundary.java
delete mode 100644 libjava/classpath/gnu/regexp/UncheckedRE.java
(limited to 'libjava/classpath/gnu')
diff --git a/libjava/classpath/gnu/CORBA/ForwardRequestHelper.java b/libjava/classpath/gnu/CORBA/ForwardRequestHelper.java
index cbdf46f..5b77fa0 100644
--- a/libjava/classpath/gnu/CORBA/ForwardRequestHelper.java
+++ b/libjava/classpath/gnu/CORBA/ForwardRequestHelper.java
@@ -62,11 +62,6 @@ import org.omg.PortableServer.ForwardRequest;
public abstract class ForwardRequestHelper
{
/**
- * The cached typecode value, computed only once.
- */
- private static TypeCode typeCode;
-
- /**
* Extract the ForwardRequest from given Any.
* This method uses the ForwardRequestHolder.
*
@@ -132,18 +127,14 @@ public abstract class ForwardRequestHelper
*/
public static TypeCode type()
{
- if (typeCode == null)
- {
- ORB orb = ORB.init();
- StructMember[] members = new StructMember[ 1 ];
-
- TypeCode field;
-
- field = ObjectHelper.type();
- members [ 0 ] = new StructMember("forward_reference", field, null);
- typeCode = orb.create_exception_tc(id(), "ForwardRequest", members);
- }
- return typeCode;
+ ORB orb = OrbRestricted.Singleton;
+ StructMember[] members = new StructMember[ 1 ];
+
+ TypeCode field;
+
+ field = ObjectHelper.type();
+ members [ 0 ] = new StructMember("forward_reference", field, null);
+ return orb.create_exception_tc(id(), "ForwardRequest", members);
}
/**
diff --git a/libjava/classpath/gnu/classpath/ByteArray.java b/libjava/classpath/gnu/classpath/ByteArray.java
deleted file mode 100644
index 6307b8a..0000000
--- a/libjava/classpath/gnu/classpath/ByteArray.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/* ByteArray.java -- wrapper around a byte array, with nice toString output.
- Copyright (C) 2005 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package gnu.classpath;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-public final class ByteArray
-{
- private final byte[] value;
-
- public ByteArray (final byte[] value)
- {
- this.value = value;
- }
-
- public byte[] getValue ()
- {
- return value;
- }
-
- public String toString ()
- {
- StringWriter str = new StringWriter ();
- PrintWriter out = new PrintWriter (str);
- int i = 0;
- int len = value.length;
- while (i < len)
- {
- out.print (formatInt (i, 16, 8));
- out.print (" ");
- int l = Math.min (16, len - i);
- String s = toHexString (value, i, l, ' ');
- out.print (s);
- for (int j = 56 - (56 - s.length ()); j < 56; j++)
- out.print (" ");
- for (int j = 0; j < l; j++)
- {
- byte b = value[i+j];
- if ((b & 0xFF) < 0x20 || (b & 0xFF) > 0x7E)
- out.print (".");
- else
- out.print ((char) (b & 0xFF));
- }
- out.println ();
- i += 16;
- }
- return str.toString ();
- }
-
- public static String toHexString (byte[] buf, int off, int len, char sep)
- {
- StringBuffer str = new StringBuffer();
- for (int i = 0; i < len; i++)
- {
- str.append (Character.forDigit (buf[i+off] >>> 4 & 0x0F, 16));
- str.append (Character.forDigit (buf[i+off] & 0x0F, 16));
- if (i < len - 1)
- str.append(sep);
- }
- return str.toString();
- }
-
- public static String formatInt (int value, int radix, int len)
- {
- String s = Integer.toString (value, radix);
- StringBuffer buf = new StringBuffer ();
- for (int j = 0; j < len - s.length(); j++)
- buf.append ("0");
- buf.append (s);
- return buf.toString();
- }
-}
diff --git a/libjava/classpath/gnu/classpath/debug/Simple1LineFormatter.java b/libjava/classpath/gnu/classpath/debug/Simple1LineFormatter.java
index 0bdf22a..9657319 100644
--- a/libjava/classpath/gnu/classpath/debug/Simple1LineFormatter.java
+++ b/libjava/classpath/gnu/classpath/debug/Simple1LineFormatter.java
@@ -38,10 +38,11 @@ exception statement from your version. */
package gnu.classpath.debug;
-import gnu.classpath.SystemProperties;
+import gnu.java.security.action.GetPropertyAction;
import java.io.PrintWriter;
import java.io.StringWriter;
+import java.security.AccessController;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
@@ -91,20 +92,27 @@ public class Simple1LineFormatter
extends Formatter
{
private static final String DAT_PATTERN = "yyyy-MM-dd HH:mm:ss.SSSS Z ";
- private static final DateFormat DAT_FORMAT = new SimpleDateFormat(DAT_PATTERN);
private static final String THREAD_PATTERN = " #########0;-#########0";
- private static final NumberFormat THREAD_FORMAT = new DecimalFormat(THREAD_PATTERN);
private static final String SPACES_32 = " ";
private static final String SPACES_6 = " ";
- private static final String LS = SystemProperties.getProperty("line.separator");
+ private static final String LS = (String) AccessController.doPrivileged
+ (new GetPropertyAction("line.separator"));
+ private DateFormat dateFormat;
+ private NumberFormat threadFormat;
// default 0-arguments constructor
public String format(LogRecord record)
{
- StringBuffer sb = new StringBuffer(180)
- .append(DAT_FORMAT.format(new Date(record.getMillis())))
- .append(THREAD_FORMAT.format(record.getThreadID()))
+ if (dateFormat == null)
+ dateFormat = new SimpleDateFormat(DAT_PATTERN);
+
+ if (threadFormat == null)
+ threadFormat = new DecimalFormat(THREAD_PATTERN);
+
+ StringBuilder sb = new StringBuilder(180)
+ .append(dateFormat.format(new Date(record.getMillis())))
+ .append(threadFormat.format(record.getThreadID()))
.append(" ");
String s = record.getSourceClassName();
if (s == null)
diff --git a/libjava/classpath/gnu/classpath/debug/SystemLogger.java b/libjava/classpath/gnu/classpath/debug/SystemLogger.java
index 94aa93f..502b488 100644
--- a/libjava/classpath/gnu/classpath/debug/SystemLogger.java
+++ b/libjava/classpath/gnu/classpath/debug/SystemLogger.java
@@ -38,7 +38,9 @@ version. */
package gnu.classpath.debug;
-import gnu.classpath.SystemProperties;
+import gnu.java.security.action.GetPropertyAction;
+
+import java.security.AccessController;
import java.util.StringTokenizer;
import java.util.logging.Logger;
@@ -49,8 +51,8 @@ public final class SystemLogger
static
{
SYSTEM.setFilter (PreciseFilter.GLOBAL);
-
- String defaults = SystemProperties.getProperty ("gnu.classpath.debug.components");
+ String defaults = (String) AccessController.doPrivileged
+ (new GetPropertyAction("gnu.classpath.debug.components"));
if (defaults != null)
{
diff --git a/libjava/classpath/gnu/classpath/debug/TeeInputStream.java b/libjava/classpath/gnu/classpath/debug/TeeInputStream.java
new file mode 100644
index 0000000..ef6b2ed
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/debug/TeeInputStream.java
@@ -0,0 +1,98 @@
+/* TeeInputStream.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+package gnu.classpath.debug;
+
+import java.io.*;
+
+/**
+ * An input stream that copies all its input to a byte sink.
+ *
+ * @author Chris Burdess
+ */
+public class TeeInputStream
+ extends InputStream
+{
+
+ private final InputStream in;
+ private final OutputStream out;
+
+ /**
+ * Constructs a tee input stream.
+ * @param in the underlying input stream
+ * @param out the output sink
+ */
+ public TeeInputStream(InputStream in, OutputStream out)
+ {
+ this.in = in;
+ this.out = out;
+ }
+
+ public int read()
+ throws IOException
+ {
+ int ret = in.read();
+ out.write(ret);
+ out.flush();
+ return ret;
+ }
+
+ public int read(byte[] b, int off, int len)
+ throws IOException
+ {
+ int ret = in.read(b, off, len);
+ if (ret != -1)
+ {
+ out.write(b, off, ret);
+ out.flush();
+ }
+ return ret;
+ }
+
+ public void close()
+ throws IOException
+ {
+ in.close();
+ out.close();
+ }
+
+ public final boolean markSupported()
+ {
+ return false;
+ }
+
+}
diff --git a/libjava/classpath/gnu/classpath/debug/TeeOutputStream.java b/libjava/classpath/gnu/classpath/debug/TeeOutputStream.java
new file mode 100644
index 0000000..cff6089
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/debug/TeeOutputStream.java
@@ -0,0 +1,93 @@
+/* TeeOutputStream.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+package gnu.classpath.debug;
+
+import java.io.*;
+
+/**
+ * An output stream that copies all its output to an additional byte sink.
+ *
+ * @author Chris Burdess
+ */
+public class TeeOutputStream
+ extends OutputStream
+{
+
+ private final OutputStream out;
+ private final OutputStream sink;
+
+ /**
+ * Constructs a tee output stream.
+ * @param out the underlying output stream
+ * @param sink the output sink
+ */
+ public TeeOutputStream(OutputStream out, OutputStream sink)
+ {
+ this.out = out;
+ this.sink = sink;
+ }
+
+ public void write(int c)
+ throws IOException
+ {
+ out.write(c);
+ sink.write(c);
+ }
+
+ public void write(byte[] b, int off, int len)
+ throws IOException
+ {
+ out.write(b, off, len);
+ sink.write(b, off, len);
+ }
+
+ public void flush()
+ throws IOException
+ {
+ out.flush();
+ sink.flush();
+ }
+
+ public void close()
+ throws IOException
+ {
+ out.close();
+ sink.close();
+ }
+
+}
diff --git a/libjava/classpath/gnu/classpath/debug/TeeReader.java b/libjava/classpath/gnu/classpath/debug/TeeReader.java
new file mode 100644
index 0000000..8fa742e
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/debug/TeeReader.java
@@ -0,0 +1,98 @@
+/* TeeReader.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+package gnu.classpath.debug;
+
+import java.io.*;
+
+/**
+ * A reader that copies all characters read to an output sink.
+ *
+ * @author Chris Burdess
+ */
+public class TeeReader
+ extends Reader
+{
+
+ private final Reader in;
+ private final Writer out;
+
+ /**
+ * Constructs a tee reader.
+ * @param in the input
+ * @param out the output sink
+ */
+ public TeeReader(Reader in, Writer out)
+ {
+ this.in = in;
+ this.out = out;
+ }
+
+ public int read()
+ throws IOException
+ {
+ int ret = in.read();
+ out.write(ret);
+ out.flush();
+ return ret;
+ }
+
+ public int read(char[] b, int off, int len)
+ throws IOException
+ {
+ int ret = in.read(b, off, len);
+ if (ret != -1)
+ {
+ out.write(b, off, ret);
+ out.flush();
+ }
+ return ret;
+ }
+
+ public void close()
+ throws IOException
+ {
+ in.close();
+ out.close();
+ }
+
+ public final boolean markSupported()
+ {
+ return false;
+ }
+
+}
diff --git a/libjava/classpath/gnu/classpath/debug/TeeWriter.java b/libjava/classpath/gnu/classpath/debug/TeeWriter.java
new file mode 100644
index 0000000..f226c21
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/debug/TeeWriter.java
@@ -0,0 +1,93 @@
+/* TeeWriter.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+package gnu.classpath.debug;
+
+import java.io.*;
+
+/**
+ * A writer that copies all its output to an additional character sink.
+ *
+ * @author Chris Burdess
+ */
+public class TeeWriter
+ extends Writer
+{
+
+ private final Writer out;
+ private final Writer sink;
+
+ /**
+ * Constructs a tee writer.
+ * @param out the underlying writer
+ * @param sink the output sink
+ */
+ public TeeWriter(Writer out, Writer sink)
+ {
+ this.out = out;
+ this.sink = sink;
+ }
+
+ public void write(int c)
+ throws IOException
+ {
+ out.write(c);
+ sink.write(c);
+ }
+
+ public void write(char[] b, int off, int len)
+ throws IOException
+ {
+ out.write(b, off, len);
+ sink.write(b, off, len);
+ }
+
+ public void flush()
+ throws IOException
+ {
+ out.flush();
+ sink.flush();
+ }
+
+ public void close()
+ throws IOException
+ {
+ out.close();
+ sink.close();
+ }
+
+}
diff --git a/libjava/classpath/gnu/classpath/jdwp/Jdwp.java b/libjava/classpath/gnu/classpath/jdwp/Jdwp.java
index 7141214..e63a9a3 100644
--- a/libjava/classpath/gnu/classpath/jdwp/Jdwp.java
+++ b/libjava/classpath/gnu/classpath/jdwp/Jdwp.java
@@ -56,6 +56,9 @@ import java.util.HashMap;
/**
* Main interface from the virtual machine to the JDWP back-end.
*
+ * The thread created by this class is only used for initialization.
+ * Once it exits, the JDWP backend is fully initialized.
+ *
* @author Keith Seitz (keiths@redhat.com)
*/
public class Jdwp
@@ -65,7 +68,8 @@ public class Jdwp
private static Jdwp _instance = null;
/**
- * Are we debugging?
+ * Are we debugging? Only true if debugging
+ * *and* initialized.
*/
public static boolean isDebugging = false;
@@ -89,13 +93,16 @@ public class Jdwp
// A thread group for the JDWP threads
private ThreadGroup _group;
+ // Initialization synchronization
+ private Object _initLock = new Object ();
+ private int _initCount = 0;
+
/**
* constructor
*/
public Jdwp ()
{
_shutdown = false;
- isDebugging = true;
_instance = this;
}
@@ -271,17 +278,52 @@ public class Jdwp
}
}
+ /**
+ * Allows subcomponents to specify that they are
+ * initialized.
+ *
+ * Subcomponents include JdwpConnection and PacketProcessor.
+ */
+ public void subcomponentInitialized ()
+ {
+ synchronized (_initLock)
+ {
+ ++_initCount;
+ _initLock.notify ();
+ }
+ }
+
public void run ()
{
try
{
_doInitialization ();
+
+ /* We need a little internal synchronization here, so that
+ when this thread dies, the back-end will be fully initialized,
+ ready to start servicing the VM and debugger. */
+ synchronized (_initLock)
+ {
+ while (_initCount != 2)
+ _initLock.wait ();
+ }
+ _initLock = null;
}
catch (Throwable t)
{
System.out.println ("Exception in JDWP back-end: " + t);
System.exit (1);
}
+
+ /* Force creation of the EventManager. If the event manager
+ has not been created when isDebugging is set, it is possible
+ that the VM will call Jdwp.notify (which uses EventManager)
+ while the EventManager is being created (or at least this is
+ a problem with gcj/gij). */
+ EventManager.getDefault();
+
+ // Now we are finally ready and initialized
+ isDebugging = true;
}
// A helper function to process the configure string "-Xrunjdwp:..."
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/BreakpointEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/BreakpointEvent.java
index be429f4..abf280d 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/BreakpointEvent.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/BreakpointEvent.java
@@ -62,18 +62,23 @@ public class BreakpointEvent
// Location where breakpoint occurred
private Location _location;
+
+ //object instance
+ private Object _instance;
/**
* Constructs a new BreakpointEvent
*
* @param thread thread in which event occurred
* @param loc location where breakpoint occurred
+ * @param instance object instance
*/
- public BreakpointEvent(Thread thread, Location loc)
+ public BreakpointEvent(Thread thread, Location loc, Object instance)
{
super(JdwpConstants.EventKind.BREAKPOINT);
_thread = thread;
_location = loc;
+ _instance = instance;
}
/**
@@ -83,12 +88,14 @@ public class BreakpointEvent
* @param type the type of parameter desired
* @returns the desired parameter or null
*/
- public Object getParameter(Class type)
+ public Object getParameter(int type)
{
- if (type == ThreadId.class)
+ if (type == EVENT_THREAD)
return _thread;
- else if (type == Location.class)
+ else if (type == EVENT_LOCATION)
return _location;
+ else if (type == EVENT_INSTANCE)
+ return _instance;
return null;
}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/ClassPrepareEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/ClassPrepareEvent.java
index 22cede0..5341daa 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/ClassPrepareEvent.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/ClassPrepareEvent.java
@@ -116,11 +116,11 @@ public class ClassPrepareEvent
* @param type the type of parameter desired
* @returns the desired parameter or GNU implementations of the Java system management beans. A global object containing build-specific properties that affect the
- * behaviour of the generated binaries from this library. Returns the string representation of the library global configuration
- * property with the designated Sets the value of a designated library global configuration property,
- * to a string representation of what should be a legal value. A convenience method that returns, as a boolean, the library global
+ * A convenience method that returns, as a boolean, the library global
* configuration property indicating if the default Pseudo Random Number
- * Generator produces, or not, the same bit stream when instantiated. A convenience method that returns, as a boolean, the library global
- * configuration property indicating if the implementations of symmetric
- * key block ciphers check, or not, for possible/potential weak and semi-weak
- * keys that may be produced in the course of generating round encryption
- * and/or decryption keys. A convenience method that returns, as a boolean, the library global
+ * A convenience method that returns, as a boolean, the library global
* configuration property indicating if RSA decryption (RSADP primitive),
- * does, or not, blinding against timing attacks. A convenience method to set the global property for reproducibility of
- * the default PRNG bit stream output. A convenience method to set the global property for checking for weak
- * and semi-weak cipher keys. A convenience method to set the global property fo adding a blinding
- * operation when executing the RSA decryption primitive. A base abstract class to facilitate hash implementations. Trivial constructor for use by concrete subclasses. Returns the byte array to use as padding before completing a hash
- * operation. Constructs the result from the contents of the current context. The block digest transformation per se. A Factory to instantiate message digest algorithm instances. Return an instance of a hash algorithm given its name. Returns a {@link Set} of names of hash algorithms supported by this
- * Factory. The HAVAL message-digest algorithm is a variable output length,
- * with variable number of rounds. By default, this implementation allows
- * HAVAL to be used as a drop-in replacement for MD5. References:
+ * References:
* Calls the constructor with two argument using {@link #HAVAL_128_BIT} as
- * the value for the output size (i.e. Calls the constructor with two arguments using the designated output
- * size, and {@link #HAVAL_3_ROUND} for the value of number of rounds. Constructs a Private constructor for cloning purposes. The basic visible methods of any hash algorithm. A hash (or message digest) algorithm produces its output by iterating a
- * basic compression function on blocks of data.
+ * A hash (or message digest) algorithm produces its output by iterating a basic
+ * compression function on blocks of data.
*/
-public interface IMessageDigest extends Cloneable
+public interface IMessageDigest
+ extends Cloneable
{
-
- // Constants
- // -------------------------------------------------------------------------
-
- // Methods
- // -------------------------------------------------------------------------
-
/**
- * Returns the canonical name of this algorithm. Returns the output length in bytes of this message digest algorithm. Returns the algorithm's (inner) block size in bytes. Continues a message digest operation using the input byte. Continues a message digest operation, by filling the buffer, processing
+ * Continues a message digest operation, by filling the buffer, processing
* data in the algorithm's HASH_SIZE-bit block(s), updating the context and
- * count, and buffering the remaining bytes in buffer for the next
- * operation. Continues a message digest operation, by filling the buffer, processing
+ * Continues a message digest operation, by filling the buffer, processing
* data in the algorithm's HASH_SIZE-bit block(s), updating the context and
- * count, and buffering the remaining bytes in buffer for the next
- * operation. Completes the message digest by performing final operations such as
- * padding and resetting the instance. Resets the current context of this instance clearing any eventually cached
- * intermediary values. A basic test. Ensures that the digest of a pre-determined message is equal
- * to a known pre-computed value. Returns a clone copy of this instance. An implementation of the MD2 message digest algorithm. MD2 is not widely used. Unless it is needed for compatibility with
- * existing systems, it is not recommended for use in new applications. References:
+ * MD2 is not widely used. Unless it is needed for compatibility with
+ * existing systems, it is not recommended for use in new applications.
+ *
+ * References:
* Private constructor used for cloning. Generates an array of padding bytes. The padding is defined as
+ * Generates an array of padding bytes. The padding is defined as
* Adds An implementation of Ron Rivest's MD4 message digest algorithm. MD4 was the precursor to the stronger {@link gnu.crypto.hash.MD5}
+ * An implementation of Ron Rivest's MD4 message digest algorithm.
+ *
+ * MD4 was the precursor to the stronger {@link gnu.java.security.hash.MD5}
* algorithm, and while not considered cryptograpically secure itself, MD4 is
- * in use in various applications. It is slightly faster than MD5. References:
+ * References:
* Public constructor. Initializes the chaining variables, sets the byte
+ * Public constructor. Initializes the chaining variables, sets the byte
* count to Trivial private constructor for cloning purposes. The MD5 message-digest algorithm takes as input a message of arbitrary
+ * The MD5 message-digest algorithm takes as input a message of arbitrary
* length and produces as output a 128-bit "fingerprint" or "message digest" of
* the input. It is conjectured that it is computationally infeasible to
* produce two messages having the same message digest, or to produce any
- * message having a given prespecified target message digest. References:
+ * References:
* Private constructor for cloning purposes. RIPEMD-128 is a 128-bit message digest. References:
+ * References:
* Private constructor for cloning purposes. RIPEMD-160 is a 160-bit message digest. References:
+ * References:
* Private constructor for cloning purposes. The Secure Hash Algorithm (SHA-1) is required for use with the Digital
+ * The Secure Hash Algorithm (SHA-1) is required for use with the Digital
* Signature Algorithm (DSA) as specified in the Digital Signature Standard
* (DSS) and whenever a secure hash algorithm is required for federal
* applications. For a message of length less than 2^64 bits, the SHA-1
@@ -51,15 +51,14 @@ import gnu.java.security.util.Util;
* message. The SHA-1 is also used to compute a message digest for the received
* version of the message during the process of verifying the signature. Any
* change to the message in transit will, with very high probability, result in
- * a different message digest, and the signature will fail to verify. The SHA-1 is designed to have the following properties: it is
+ * a different message digest, and the signature will fail to verify.
+ *
+ * The SHA-1 is designed to have the following properties: it is
* computationally infeasible to find a message which corresponds to a given
* message digest, or to find two different messages which produce the same
- * message digest. References:
+ * References:
* Private constructor for cloning purposes. Implementation of SHA2-1 [SHA-256] per the IETF Draft Specification. References:
+ * References:
* Private constructor for cloning purposes. Implementation of SHA2-2 [SHA-384] per the IETF Draft Specification. References:
+ * References:
* Private constructor for cloning purposes. Implementation of SHA2-3 [SHA-512] per the IETF Draft Specification. References:
+ * References:
* Private constructor for cloning purposes. Tiger processes data in 512-bit blocks and produces a 192-bit
- * digest. References:
+ * Tiger processes data in 512-bit blocks and produces a 192-bit
+ * digest.
+ *
+ * References:
* Private constructor for cloning purposes.
+ * The implementation of the HAVAL Service Provider Interface
+ * (SPI) adapter.
*/
-public class HavalSpi extends MessageDigestAdapter
+public class HavalSpi
+ extends MessageDigestAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public HavalSpi()
{
super(Registry.HAVAL_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/hash/MD2Spi.java b/libjava/classpath/gnu/java/security/jce/hash/MD2Spi.java
index 001cbaf..268f2fa 100644
--- a/libjava/classpath/gnu/java/security/jce/hash/MD2Spi.java
+++ b/libjava/classpath/gnu/java/security/jce/hash/MD2Spi.java
@@ -41,27 +41,15 @@ package gnu.java.security.jce.hash;
import gnu.java.security.Registry;
/**
- * The implementation of the MD2 Service Provider Interface
- * (SPI) adapter. The implementation of the MD4 Service Provider Interface
- * (SPI) adapter.
+ * adapter.
*/
-public class MD5Spi extends MessageDigestAdapter
+public class MD5Spi
+ extends MessageDigestAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public MD5Spi()
{
super(Registry.MD5_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/hash/MessageDigestAdapter.java b/libjava/classpath/gnu/java/security/jce/hash/MessageDigestAdapter.java
index e30beca..7342ee5 100644
--- a/libjava/classpath/gnu/java/security/jce/hash/MessageDigestAdapter.java
+++ b/libjava/classpath/gnu/java/security/jce/hash/MessageDigestAdapter.java
@@ -46,35 +46,30 @@ import java.security.MessageDigestSpi;
/**
* The implementation of a generic {@link java.security.MessageDigest} adapter
- * class to wrap gnu.crypto hash instances.
- *
- * This class defines the Service Provider Interface (SPI) for the
- * {@link java.security.MessageDigest} class, which provides the functionality
- * of a message digest algorithm, such as MD5 or SHA. Message digests are secure
- * one-way hash functions that take arbitrary-sized data and output a fixed-
- * length hash value.
- *
- * All the abstract methods in the {@link java.security.MessageDigestSpi} class
- * are implemented by this class and all its sub-classes.
- *
+ * class to wrap GNU hash instances.
+ *
+ * This class defines the Service Provider Interface (SPI) for
+ * the {@link java.security.MessageDigest} class, which provides the
+ * functionality of a message digest algorithm, such as MD5 or SHA. Message
+ * digests are secure one-way hash functions that take arbitrary-sized data and
+ * output a fixed-length hash value.
+ *
+ * All the abstract methods in the {@link MessageDigestSpi} class are
+ * implemented by this class and all its sub-classes.
+ *
* All the implementations which subclass this object, and which are serviced by
- * the GNU Crypto provider implement the {@link java.lang.Cloneable} interface.
+ * the GNU provider implement the {@link Cloneable} interface.
*/
-class MessageDigestAdapter extends MessageDigestSpi implements Cloneable
+class MessageDigestAdapter
+ extends MessageDigestSpi
+ implements Cloneable
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** Our underlying hash instance. */
private IMessageDigest adaptee;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Trivial protected constructor.
- *
+ *
* @param mdName the canonical name of the hash algorithm.
*/
protected MessageDigestAdapter(String mdName)
@@ -84,7 +79,7 @@ class MessageDigestAdapter extends MessageDigestSpi implements Cloneable
/**
* Private constructor for cloning purposes.
- *
+ *
* @param adaptee a clone of the underlying hash algorithm instance.
*/
private MessageDigestAdapter(IMessageDigest adaptee)
@@ -94,12 +89,6 @@ class MessageDigestAdapter extends MessageDigestSpi implements Cloneable
this.adaptee = adaptee;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // java.security.MessageDigestSpi interface implementation
- // -------------------------------------------------------------------------
-
public Object clone()
{
return new MessageDigestAdapter((IMessageDigest) adaptee.clone());
@@ -130,9 +119,8 @@ class MessageDigestAdapter extends MessageDigestSpi implements Cloneable
{
int result = adaptee.hashSize();
if (len < result)
- {
- throw new DigestException();
- }
+ throw new DigestException();
+
byte[] md = adaptee.digest();
System.arraycopy(md, 0, buf, offset, result);
return result;
diff --git a/libjava/classpath/gnu/java/security/jce/hash/RipeMD128Spi.java b/libjava/classpath/gnu/java/security/jce/hash/RipeMD128Spi.java
index 404214d..159a117 100644
--- a/libjava/classpath/gnu/java/security/jce/hash/RipeMD128Spi.java
+++ b/libjava/classpath/gnu/java/security/jce/hash/RipeMD128Spi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the RIPEMD-128 Service Provider Interface
- * (SPI) adapter.
+ * (SPI) adapter.
*/
-public class RipeMD128Spi extends MessageDigestAdapter
+public class RipeMD128Spi
+ extends MessageDigestAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public RipeMD128Spi()
{
super(Registry.RIPEMD128_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/hash/RipeMD160Spi.java b/libjava/classpath/gnu/java/security/jce/hash/RipeMD160Spi.java
index 841f46b..579ccb2 100644
--- a/libjava/classpath/gnu/java/security/jce/hash/RipeMD160Spi.java
+++ b/libjava/classpath/gnu/java/security/jce/hash/RipeMD160Spi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the RIPEMD-160 Service Provider Interface
- * (SPI) adapter.
+ * (SPI) adapter.
*/
-public class RipeMD160Spi extends MessageDigestAdapter
+public class RipeMD160Spi
+ extends MessageDigestAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public RipeMD160Spi()
{
super(Registry.RIPEMD160_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/hash/Sha160Spi.java b/libjava/classpath/gnu/java/security/jce/hash/Sha160Spi.java
index 4198843..901cac1 100644
--- a/libjava/classpath/gnu/java/security/jce/hash/Sha160Spi.java
+++ b/libjava/classpath/gnu/java/security/jce/hash/Sha160Spi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the SHA-1 (160-bit) Service Provider Interface
- * (SPI) adapter.
+ * (SPI) adapter.
*/
-public class Sha160Spi extends MessageDigestAdapter
+public class Sha160Spi
+ extends MessageDigestAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public Sha160Spi()
{
super(Registry.SHA160_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/hash/Sha256Spi.java b/libjava/classpath/gnu/java/security/jce/hash/Sha256Spi.java
index f07e189..9d471e6 100644
--- a/libjava/classpath/gnu/java/security/jce/hash/Sha256Spi.java
+++ b/libjava/classpath/gnu/java/security/jce/hash/Sha256Spi.java
@@ -41,26 +41,14 @@ package gnu.java.security.jce.hash;
import gnu.java.security.Registry;
/**
- * The implementation of the SHA-2-1 (256-bit) Service Provider Interface
- * (SPI) adapter. The implementation of the SHA-2-2 (384-bit) Service Provider Interface
- * (SPI) adapter. The implementation of the SHA-2-3 (512-bit) Service Provider Interface
- * (SPI) adapter. The implementation of the Tiger Service Provider Interface
- * (SPI) adapter.
+ * (SPI) adapter.
*/
-public class WhirlpoolSpi extends MessageDigestAdapter
+public class WhirlpoolSpi
+ extends MessageDigestAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public WhirlpoolSpi()
{
super(Registry.WHIRLPOOL_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/HavalRandomSpi.java b/libjava/classpath/gnu/java/security/jce/prng/HavalRandomSpi.java
index 0c39a37..c3d4b94 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/HavalRandomSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/HavalRandomSpi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the HAVAL-based SecureRandom Service Provider
- * Interface (SPI) Adapter.
+ * Interface (SPI) adapter.
*/
-public class HavalRandomSpi extends SecureRandomAdapter
+public class HavalRandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public HavalRandomSpi()
{
super(Registry.HAVAL_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/MD2RandomSpi.java b/libjava/classpath/gnu/java/security/jce/prng/MD2RandomSpi.java
index 72a7f48..8ba2868 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/MD2RandomSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/MD2RandomSpi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the MD2-based SecureRandom Service Provider
- * Interface (SPI) adapter.
+ * Interface (SPI) adapter.
*/
-public class MD2RandomSpi extends SecureRandomAdapter
+public class MD2RandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public MD2RandomSpi()
{
super(Registry.MD2_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/MD4RandomSpi.java b/libjava/classpath/gnu/java/security/jce/prng/MD4RandomSpi.java
index f5f98f8..d4d1829 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/MD4RandomSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/MD4RandomSpi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the MD4-based SecureRandom Service Provider
- * Interface (SPI) adapter.
+ * Interface (SPI) adapter.
*/
-public class MD4RandomSpi extends SecureRandomAdapter
+public class MD4RandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public MD4RandomSpi()
{
super(Registry.MD4_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/MD5RandomSpi.java b/libjava/classpath/gnu/java/security/jce/prng/MD5RandomSpi.java
index 0181247..be38add 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/MD5RandomSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/MD5RandomSpi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the MD5-based SecureRandom Service Provider
- * Interface (SPI) adapter.
+ * Interface (SPI) adapter.
*/
-public class MD5RandomSpi extends SecureRandomAdapter
+public class MD5RandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public MD5RandomSpi()
{
super(Registry.MD5_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/RipeMD128RandomSpi.java b/libjava/classpath/gnu/java/security/jce/prng/RipeMD128RandomSpi.java
index 5580716..530c3ec 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/RipeMD128RandomSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/RipeMD128RandomSpi.java
@@ -41,26 +41,14 @@ package gnu.java.security.jce.prng;
import gnu.java.security.Registry;
/**
- * The implementation of the RIPEMD128-based SecureRandom Service Provider
- * Interface (SPI) adapter.
+ * The implementation of the RIPEMD128-based SecureRandom Service Provider
+ * Interface (SPI) adapter.
*/
-public class RipeMD128RandomSpi extends SecureRandomAdapter
+public class RipeMD128RandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public RipeMD128RandomSpi()
{
super(Registry.RIPEMD128_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/RipeMD160RandomSpi.java b/libjava/classpath/gnu/java/security/jce/prng/RipeMD160RandomSpi.java
index 734fe82..6875cdf 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/RipeMD160RandomSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/RipeMD160RandomSpi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the RIPEMD160-based SecureRandom Service Provider
- * Interface (SPI) adapter.
+ * Interface (SPI) adapter.
*/
-public class RipeMD160RandomSpi extends SecureRandomAdapter
+public class RipeMD160RandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public RipeMD160RandomSpi()
{
super(Registry.RIPEMD160_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/SecureRandomAdapter.java b/libjava/classpath/gnu/java/security/jce/prng/SecureRandomAdapter.java
index 70d30f1..5be402f 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/SecureRandomAdapter.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/SecureRandomAdapter.java
@@ -45,34 +45,28 @@ import java.security.SecureRandomSpi;
import java.util.Collections;
/**
- * The implementation of a generic {@link java.security.SecureRandom} adapter
- * class to wrap gnu.crypto prng instances based on Message Digest algorithms. This class defines the Service Provider Interface (SPI) for
+ * The implementation of a generic {@link java.security.SecureRandom} adapter
+ * class to wrap GNU PRNG instances based on Message Digest algorithms.
+ *
+ * This class defines the Service Provider Interface (SPI) for
* the {@link java.security.SecureRandom} class, which provides the
- * functionality of a cryptographically strong pseudo-random number generator. All the abstract methods in the {@link SecureRandomSpi} class are
- * implemented by this class and all its sub-classes.
+ * All the abstract methods in the {@link SecureRandomSpi} class are implemented
+ * by this class and all its sub-classes.
*/
-abstract class SecureRandomAdapter extends SecureRandomSpi
+abstract class SecureRandomAdapter
+ extends SecureRandomSpi
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** Our underlying prng instance. */
private MDGenerator adaptee = new MDGenerator();
/** The name of the message digest algorithm used by the adaptee. */
private String mdName;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- * Trivial protected constructor.
+ * Interface (SPI) adapter.
*/
-public class Sha160RandomSpi extends SecureRandomAdapter
+public class Sha160RandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public Sha160RandomSpi()
{
super(Registry.SHA160_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/Sha256RandomSpi.java b/libjava/classpath/gnu/java/security/jce/prng/Sha256RandomSpi.java
index 7369964..e3999ff 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/Sha256RandomSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/Sha256RandomSpi.java
@@ -41,26 +41,14 @@ package gnu.java.security.jce.prng;
import gnu.java.security.Registry;
/**
- * The implementation of the SHA-256 based SecureRandom Service Provider
- * Interface (SPI) adapter. The implementation of the SHA-384 based SecureRandom Service Provider
- * Interface (SPI) adapter. The implementation of the SHA-512 based SecureRandom Service Provider
- * Interface (SPI) adapter.
+ * Interface (SPI) adapter.
*/
-public class TigerRandomSpi extends SecureRandomAdapter
+public class TigerRandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public TigerRandomSpi()
{
super(Registry.TIGER_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/prng/WhirlpoolRandomSpi.java b/libjava/classpath/gnu/java/security/jce/prng/WhirlpoolRandomSpi.java
index f327f9d..9d937e6 100644
--- a/libjava/classpath/gnu/java/security/jce/prng/WhirlpoolRandomSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/prng/WhirlpoolRandomSpi.java
@@ -42,25 +42,13 @@ import gnu.java.security.Registry;
/**
* The implementation of the Whirlpool-based SecureRandom Service Provider
- * Interface (SPI) adapter.
+ * Interface (SPI) adapter.
*/
-public class WhirlpoolRandomSpi extends SecureRandomAdapter
+public class WhirlpoolRandomSpi
+ extends SecureRandomAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public WhirlpoolRandomSpi()
{
super(Registry.WHIRLPOOL_HASH);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/sig/DSSKeyFactory.java b/libjava/classpath/gnu/java/security/jce/sig/DSSKeyFactory.java
index bb4d85c..7b57dba 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/DSSKeyFactory.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/DSSKeyFactory.java
@@ -61,10 +61,11 @@ import java.security.spec.X509EncodedKeySpec;
/**
* DSA key factory.
- *
+ *
* @author Casey Marshall (rsdio@metastatic.org)
*/
-public class DSSKeyFactory extends KeyFactorySpi
+public class DSSKeyFactory
+ extends KeyFactorySpi
{
// implicit 0-arguments constructor
@@ -80,7 +81,6 @@ public class DSSKeyFactory extends KeyFactorySpi
BigInteger y = spec.getY();
return new DSSPublicKey(Registry.X509_ENCODING_ID, p, q, g, y);
}
-
if (keySpec instanceof X509EncodedKeySpec)
{
X509EncodedKeySpec spec = (X509EncodedKeySpec) keySpec;
@@ -93,12 +93,9 @@ public class DSSKeyFactory extends KeyFactorySpi
}
catch (RuntimeException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
-
throw new InvalidKeySpecException("Unsupported (public) key specification");
}
@@ -114,7 +111,6 @@ public class DSSKeyFactory extends KeyFactorySpi
BigInteger x = spec.getX();
return new DSSPrivateKey(Registry.PKCS8_ENCODING_ID, p, q, g, x);
}
-
if (keySpec instanceof PKCS8EncodedKeySpec)
{
PKCS8EncodedKeySpec spec = (PKCS8EncodedKeySpec) keySpec;
@@ -127,12 +123,9 @@ public class DSSKeyFactory extends KeyFactorySpi
}
catch (RuntimeException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
-
throw new InvalidKeySpecException("Unsupported (private) key specification");
}
@@ -150,7 +143,6 @@ public class DSSKeyFactory extends KeyFactorySpi
BigInteger y = dsaKey.getY();
return new DSAPublicKeySpec(y, p, q, g);
}
-
if (keySpec.isAssignableFrom(X509EncodedKeySpec.class))
{
if (key instanceof DSSPublicKey)
@@ -159,19 +151,16 @@ public class DSSKeyFactory extends KeyFactorySpi
byte[] encoded = dssKey.getEncoded(Registry.X509_ENCODING_ID);
return new X509EncodedKeySpec(encoded);
}
-
if (Registry.X509_ENCODING_SORT_NAME.equalsIgnoreCase(key.getFormat()))
{
byte[] encoded = key.getEncoded();
return new X509EncodedKeySpec(encoded);
}
-
- throw new InvalidKeySpecException("Wrong key type or unsupported (public) key specification");
+ throw new InvalidKeySpecException(
+ "Wrong key type or unsupported (public) key specification");
}
-
throw new InvalidKeySpecException("Unsupported (public) key specification");
}
-
if (key instanceof DSAPrivateKey)
{
if (keySpec.isAssignableFrom(DSAPrivateKeySpec.class))
@@ -183,7 +172,6 @@ public class DSSKeyFactory extends KeyFactorySpi
BigInteger x = dsaKey.getX();
return new DSAPrivateKeySpec(x, p, q, g);
}
-
if (keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class))
{
if (key instanceof DSSPrivateKey)
@@ -192,19 +180,16 @@ public class DSSKeyFactory extends KeyFactorySpi
byte[] encoded = dssKey.getEncoded(Registry.PKCS8_ENCODING_ID);
return new PKCS8EncodedKeySpec(encoded);
}
-
if (Registry.PKCS8_ENCODING_SHORT_NAME.equalsIgnoreCase(key.getFormat()))
{
byte[] encoded = key.getEncoded();
return new PKCS8EncodedKeySpec(encoded);
}
-
- throw new InvalidKeySpecException("Wrong key type or unsupported (private) key specification");
+ throw new InvalidKeySpecException(
+ "Wrong key type or unsupported (private) key specification");
}
-
throw new InvalidKeySpecException("Unsupported (private) key specification");
}
-
throw new InvalidKeySpecException("Wrong key type or unsupported key specification");
}
@@ -222,7 +207,6 @@ public class DSSKeyFactory extends KeyFactorySpi
BigInteger y = dsaKey.getY();
return new DSSPublicKey(Registry.X509_ENCODING_ID, p, q, g, y);
}
-
if (key instanceof DSAPrivateKey)
{
DSAPrivateKey dsaKey = (DSAPrivateKey) key;
@@ -232,7 +216,6 @@ public class DSSKeyFactory extends KeyFactorySpi
BigInteger x = dsaKey.getX();
return new DSSPrivateKey(Registry.PKCS8_ENCODING_ID, p, q, g, x);
}
-
throw new InvalidKeyException("Wrong key type");
}
}
diff --git a/libjava/classpath/gnu/java/security/jce/sig/DSSKeyPairGeneratorSpi.java b/libjava/classpath/gnu/java/security/jce/sig/DSSKeyPairGeneratorSpi.java
index 44503b2..c445381 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/DSSKeyPairGeneratorSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/DSSKeyPairGeneratorSpi.java
@@ -52,33 +52,21 @@ import java.util.HashMap;
/**
* The implementation of a {@link java.security.KeyPairGenerator} adapter class
- * to wrap gnu.crypto DSS keypair generator instances.
- *
- * In case the client does not explicitly initialize the KeyPairGenerator (via
- * a call to an
+ * to wrap GNU DSS keypair generator instances.
+ *
+ * In case the client does not explicitly initialize the KeyPairGenerator (via a
+ * call to an
+ * The implementation of Service Provider Interface (SPI)
+ * adapter for the DSS (Digital Signature Standard) signature scheme, encoded
+ * and/or decoded in RAW format.
*/
-public class DSSRawSignatureSpi extends SignatureAdapter
+public class DSSRawSignatureSpi
+ extends SignatureAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public DSSRawSignatureSpi()
{
super(Registry.DSS_SIG, new DSSSignatureRawCodec());
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/sig/EncodedKeyFactory.java b/libjava/classpath/gnu/java/security/jce/sig/EncodedKeyFactory.java
index 60152c2..19ec088 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/EncodedKeyFactory.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/EncodedKeyFactory.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.jce.sig;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.key.dss.DSSPrivateKey;
import gnu.java.security.key.dss.DSSPublicKey;
@@ -79,11 +80,6 @@ public class EncodedKeyFactory
{
private static final Logger log = Logger.getLogger(EncodedKeyFactory.class.getName());
- // implicit 0-arguments constructor
-
- // Class methods
- // --------------------------------------------------------------------------
-
private static Object invokeConstructor(String className, Object[] params)
throws InvalidKeySpecException
{
@@ -96,21 +92,15 @@ public class EncodedKeyFactory
}
catch (InstantiationException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
catch (IllegalAccessException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(y);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
catch (InvocationTargetException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
@@ -124,9 +114,7 @@ public class EncodedKeyFactory
}
catch (ClassNotFoundException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
@@ -144,9 +132,7 @@ public class EncodedKeyFactory
}
catch (NoSuchMethodException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
@@ -162,15 +148,11 @@ public class EncodedKeyFactory
}
catch (IllegalAccessException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
catch (InvocationTargetException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
@@ -184,20 +166,15 @@ public class EncodedKeyFactory
}
catch (NoSuchMethodException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
- // Instance methods
- // --------------------------------------------------------------------------
-
protected PublicKey engineGeneratePublic(KeySpec keySpec)
throws InvalidKeySpecException
{
- log.entering(this.getClass().getName(), "engineGeneratePublic()", keySpec);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGeneratePublic()", keySpec);
PublicKey result = null;
if (keySpec instanceof DSAPublicKeySpec)
result = decodeDSSPublicKey((DSAPublicKeySpec) keySpec);
@@ -220,10 +197,10 @@ public class EncodedKeyFactory
}
catch (InvalidParameterException ignored)
{
- log.log(Level.FINE, "Exception in DSSPublicKey.valueOf(). Ignore",
- ignored);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception in DSSPublicKey.valueOf(). Ignore",
+ ignored);
}
-
if (! ok) // try RSA
try
{
@@ -232,24 +209,24 @@ public class EncodedKeyFactory
}
catch (InvalidParameterException ignored)
{
- log.log(Level.FINE,
- "Exception in GnuRSAPublicKey.valueOf(). Ignore",
- ignored);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE,
+ "Exception in GnuRSAPublicKey.valueOf(). Ignore",
+ ignored);
}
-
if (! ok) // try DH
result = decodeDHPublicKey(input);
}
-
- log.exiting(this.getClass().getName(), "engineGeneratePublic()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGeneratePublic()", result);
return result;
}
protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
throws InvalidKeySpecException
{
- log.entering(this.getClass().getName(), "engineGeneratePrivate()", keySpec);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineGeneratePrivate()", keySpec);
PrivateKey result = null;
if (keySpec instanceof DSAPrivateKeySpec)
result = decodeDSSPrivateKey((DSAPrivateKeySpec) keySpec);
@@ -272,10 +249,10 @@ public class EncodedKeyFactory
}
catch (InvalidParameterException ignored)
{
- log.log(Level.FINE, "Exception in DSSPrivateKey.valueOf(). Ignore",
- ignored);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE, "Exception in DSSPrivateKey.valueOf(). Ignore",
+ ignored);
}
-
if (! ok) // try RSA
try
{
@@ -284,16 +261,16 @@ public class EncodedKeyFactory
}
catch (InvalidParameterException ignored)
{
- log.log(Level.FINE,
- "Exception in GnuRSAPrivateKey.valueOf(). Ignore",
- ignored);
+ if (Configuration.DEBUG)
+ log.log(Level.FINE,
+ "Exception in GnuRSAPrivateKey.valueOf(). Ignore",
+ ignored);
}
-
if (! ok) // try DH
result = decodeDHPrivateKey(input);
}
-
- log.exiting(this.getClass().getName(), "engineGeneratePrivate()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineGeneratePrivate()", result);
return result;
}
@@ -321,7 +298,7 @@ public class EncodedKeyFactory
/**
* @param spec an instance of {@link DSAPublicKeySpec} to decode.
* @return an instance of {@link DSSPublicKey} constructed from the
- * information in the designated key-specification.
+ * information in the designated key-specification.
*/
private DSSPublicKey decodeDSSPublicKey(DSAPublicKeySpec spec)
{
@@ -335,7 +312,7 @@ public class EncodedKeyFactory
/**
* @param spec an instance of {@link RSAPublicKeySpec} to decode.
* @return an instance of {@link GnuRSAPublicKey} constructed from the
- * information in the designated key-specification.
+ * information in the designated key-specification.
*/
private GnuRSAPublicKey decodeRSAPublicKey(RSAPublicKeySpec spec)
{
@@ -358,7 +335,7 @@ public class EncodedKeyFactory
BigInteger p = spec.getP();
BigInteger g = spec.getG();
BigInteger y = spec.getY();
- Object[] params = new Object[] {new Integer(Registry.X509_ENCODING_ID),
+ Object[] params = new Object[] {Integer.valueOf(Registry.X509_ENCODING_ID),
null, p, g, y};
Object obj = invokeConstructor("gnu.javax.crypto.key.dh.GnuDHPublicKey",
params);
@@ -384,7 +361,7 @@ public class EncodedKeyFactory
/**
* @param spec an instance of {@link DSAPrivateKeySpec} to decode.
* @return an instance of {@link DSSPrivateKey} constructed from the
- * information in the designated key-specification.
+ * information in the designated key-specification.
*/
private PrivateKey decodeDSSPrivateKey(DSAPrivateKeySpec spec)
{
@@ -398,7 +375,7 @@ public class EncodedKeyFactory
/**
* @param spec an instance of {@link RSAPrivateCrtKeySpec} to decode.
* @return an instance of {@link GnuRSAPrivateKey} constructed from the
- * information in the designated key-specification.
+ * information in the designated key-specification.
*/
private PrivateKey decodeRSAPrivateKey(RSAPrivateCrtKeySpec spec)
{
@@ -428,7 +405,7 @@ public class EncodedKeyFactory
BigInteger p = spec.getP();
BigInteger g = spec.getG();
BigInteger x = spec.getX();
- Object[] params = new Object[] {new Integer(Registry.PKCS8_ENCODING_ID),
+ Object[] params = new Object[] {Integer.valueOf(Registry.PKCS8_ENCODING_ID),
null, p, g, x};
Object obj = invokeConstructor("gnu.javax.crypto.key.dh.GnuDHPrivateKey",
params);
diff --git a/libjava/classpath/gnu/java/security/jce/sig/KeyPairGeneratorAdapter.java b/libjava/classpath/gnu/java/security/jce/sig/KeyPairGeneratorAdapter.java
index edf19f6..bcbbe47 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/KeyPairGeneratorAdapter.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/KeyPairGeneratorAdapter.java
@@ -49,36 +49,30 @@ import java.security.spec.AlgorithmParameterSpec;
/**
* The implementation of a generic {@link java.security.KeyPairGenerator}
- * adapter class to wrap gnu.crypto keypair generator instances.
- *
- * This class defines the Service Provider Interface (SPI) for the
- * {@link java.security.KeyPairGenerator} class, which is used to generate pairs
- * of public and private keys.
- *
+ * adapter class to wrap GNU keypair generator instances.
+ *
+ * This class defines the Service Provider Interface (SPI) for
+ * the {@link java.security.KeyPairGenerator} class, which is used to generate
+ * pairs of public and private keys.
+ *
* All the abstract methods in the {@link java.security.KeyPairGeneratorSpi}
- * class are implemented by this class and all its sub-classes.
- *
- * In case the client does not explicitly initialize the KeyPairGenerator (via
- * a call to an
+ * class are implemented by this class and all its sub-classes.
+ *
+ * In case the client does not explicitly initialize the KeyPairGenerator (via a
+ * call to an
- *
- * In case the client does not explicitly initialize the KeyPairGenerator (via
- * a call to an
+ * to wrap GNU RSA keypair generator instances.
+ *
+ * In case the client does not explicitly initialize the KeyPairGenerator (via a
+ * call to an
+ * The implementation of Service Provider Interface (SPI)
+ * adapter for the RSA-PSS signature scheme, encoded and/or decoded in RAW
+ * format.
*/
-public class RSAPSSRawSignatureSpi extends SignatureAdapter
+public class RSAPSSRawSignatureSpi
+ extends SignatureAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public RSAPSSRawSignatureSpi()
{
super(Registry.RSA_PSS_SIG, new RSAPSSSignatureRawCodec());
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/jce/sig/SignatureAdapter.java b/libjava/classpath/gnu/java/security/jce/sig/SignatureAdapter.java
index 4dcbe78..a65d727 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/SignatureAdapter.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/SignatureAdapter.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.jce.sig;
+import gnu.java.security.Configuration;
import gnu.java.security.sig.BaseSignature;
import gnu.java.security.sig.ISignature;
import gnu.java.security.sig.ISignatureCodec;
@@ -57,38 +58,34 @@ import java.util.logging.Logger;
/**
* The implementation of a generic {@link java.security.Signature} adapter class
- * to wrap gnu.crypto signature instances.
- *
- * This class defines the Service Provider Interface (SPI) for the
- * {@link java.security.Signature} class, which provides the functionality of a
- * digital signature algorithm. Digital signatures are used for authentication
- * and integrity assurance of digital data.
- *
- * All the abstract methods in the {@link java.security.SignatureSpi} class are
- * implemented by this class and all its sub-classes.
- *
+ * to wrap GNU signature instances.
+ *
+ * This class defines the Service Provider Interface (SPI) for
+ * the {@link java.security.Signature} class, which provides the functionality
+ * of a digital signature algorithm. Digital signatures are used for
+ * authentication and integrity assurance of digital data.
+ *
+ * All the abstract methods in the {@link SignatureSpi} class are implemented by
+ * this class and all its sub-classes.
+ *
* All the implementations which subclass this object, and which are serviced by
- * the GNU Crypto provider implement the {@link java.lang.Cloneable} interface.
+ * the GNU provider implement the {@link Cloneable} interface.
*/
-class SignatureAdapter extends SignatureSpi implements Cloneable
+class SignatureAdapter
+ extends SignatureSpi
+ implements Cloneable
{
private static final Logger log = Logger.getLogger(SignatureAdapter.class.getName());
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** Our underlying signature instance. */
private ISignature adaptee;
/** Our underlying signature encoder/decoder engine. */
private ISignatureCodec codec;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- * Trivial protected constructor.
- *
+ * Trivial protected constructor.
+ *
* @param sigName the canonical name of the signature scheme.
* @param codec the signature codec engine to use with this scheme.
*/
@@ -98,8 +95,8 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
}
/**
- * Private constructor for cloning purposes.
- *
+ * Private constructor for cloning purposes.
+ *
* @param adaptee a clone of the underlying signature scheme instance.
* @param codec the signature codec engine to use with this scheme.
*/
@@ -111,12 +108,6 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
this.codec = codec;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // java.security.SignatureSpi interface implementation
- // -------------------------------------------------------------------------
-
public Object clone()
{
return new SignatureAdapter((ISignature) adaptee.clone(), codec);
@@ -132,7 +123,7 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
}
catch (IllegalArgumentException x)
{
- throw new InvalidKeyException(String.valueOf(x));
+ throw new InvalidKeyException(x.getMessage(), x);
}
}
@@ -146,7 +137,7 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
}
catch (IllegalArgumentException x)
{
- throw new InvalidKeyException(String.valueOf(x));
+ throw new InvalidKeyException(x.getMessage(), x);
}
}
@@ -162,7 +153,7 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
}
catch (IllegalArgumentException x)
{
- throw new InvalidKeyException(String.valueOf(x));
+ throw new InvalidKeyException(x.getMessage(), x);
}
}
@@ -174,7 +165,7 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
}
catch (IllegalStateException x)
{
- throw new SignatureException(String.valueOf(x));
+ throw new SignatureException(x.getMessage(), x);
}
}
@@ -187,7 +178,7 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
}
catch (IllegalStateException x)
{
- throw new SignatureException(String.valueOf(x));
+ throw new SignatureException(x.getMessage(), x);
}
}
@@ -200,9 +191,8 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
}
catch (IllegalStateException x)
{
- throw new SignatureException(String.valueOf(x));
+ throw new SignatureException(x.getMessage(), x);
}
-
byte[] result = codec.encodeSignature(signature);
return result;
}
@@ -213,9 +203,7 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
byte[] signature = this.engineSign();
int result = signature.length;
if (result > len)
- {
- throw new SignatureException("len");
- }
+ throw new SignatureException("Not enough room to store signature");
System.arraycopy(signature, 0, outbuf, offset, result);
return result;
@@ -223,8 +211,8 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
public boolean engineVerify(byte[] sigBytes) throws SignatureException
{
- log.entering("SignatureAdapter", "engineVerify");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "engineVerify");
Object signature = codec.decodeSignature(sigBytes);
boolean result = false;
try
@@ -233,10 +221,11 @@ class SignatureAdapter extends SignatureSpi implements Cloneable
}
catch (IllegalStateException x)
{
- throw new SignatureException(String.valueOf(x));
+ throw new SignatureException(x.getMessage(), x);
}
-
- log.exiting("SignatureAdapter", "engineVerify", new Boolean(result));
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "engineVerify",
+ Boolean.valueOf(result));
return result;
}
diff --git a/libjava/classpath/gnu/java/security/key/IKeyPairCodec.java b/libjava/classpath/gnu/java/security/key/IKeyPairCodec.java
index 965a317..f09743d 100644
--- a/libjava/classpath/gnu/java/security/key/IKeyPairCodec.java
+++ b/libjava/classpath/gnu/java/security/key/IKeyPairCodec.java
@@ -44,16 +44,13 @@ import java.security.PrivateKey;
import java.security.PublicKey;
/**
- * The visible methods of an object that knows how to encode and decode
+ * The visible methods of an object that knows how to encode and decode
* cryptographic asymmetric keypairs. Codecs are useful for (a) externalising
* public and private keys for storage and on-the-wire transmission, as well as
- * (b) re-creating their internal Java representation from external sources. Returns the unique identifier (within this library) of the format used
- * to externalise public and private keys. Encodes an instance of a public key for storage or transmission purposes. Encodes an instance of a private key for storage or transmission purposes. Decodes an instance of an external public key into its native Java
- * representation. Decodes an instance of an external private key into its native Java
- * representation.
+ * The visible methods of every asymmetric keypair generator.
*/
public interface IKeyPairGenerator
{
-
- // Constants
- // -------------------------------------------------------------------------
-
- // Methods
- // -------------------------------------------------------------------------
-
/**
- * Returns the canonical name of this keypair generator.
- *
+ * Returns the canonical name of this keypair generator.
+ *
* @return the canonical name of this instance.
*/
String name();
/**
- * [Re]-initialises this instance for use with a given set of attributes.
- *
+ * [Re]-initialises this instance for use with a given set of attributes.
+ *
* @param attributes a map of name/value pairs to use for setting up the
- * instance.
+ * instance.
* @exception IllegalArgumentException if at least one of the mandatory
- * attributes is missing or an invalid value was specified.
+ * attributes is missing or an invalid value was specified.
*/
void setup(Map attributes);
/**
* Generates a new keypair based on the attributes used to configure the
* instance.
- *
+ *
* @return a new keypair.
*/
KeyPair generate();
diff --git a/libjava/classpath/gnu/java/security/key/KeyPairCodecFactory.java b/libjava/classpath/gnu/java/security/key/KeyPairCodecFactory.java
index 1a8b8aa..e68a7d6 100644
--- a/libjava/classpath/gnu/java/security/key/KeyPairCodecFactory.java
+++ b/libjava/classpath/gnu/java/security/key/KeyPairCodecFactory.java
@@ -207,10 +207,8 @@ public class KeyPairCodecFactory
hs.add(Registry.RSA_KPG + "/" + Registry.PKCS8_ENCODING_SHORT_NAME);
hs.add(Registry.DH_KPG + "/" + Registry.RAW_ENCODING_SHORT_NAME);
hs.add(Registry.SRP_KPG + "/" + Registry.RAW_ENCODING_SHORT_NAME);
-
names = Collections.unmodifiableSet(hs);
}
-
return names;
}
diff --git a/libjava/classpath/gnu/java/security/key/KeyPairGeneratorFactory.java b/libjava/classpath/gnu/java/security/key/KeyPairGeneratorFactory.java
index 8c2f348..4872fc3 100644
--- a/libjava/classpath/gnu/java/security/key/KeyPairGeneratorFactory.java
+++ b/libjava/classpath/gnu/java/security/key/KeyPairGeneratorFactory.java
@@ -48,68 +48,48 @@ import java.util.HashSet;
import java.util.Set;
/**
- * A Factory to instantiate asymmetric keypair generators. Returns an instance of a keypair generator given its name. Returns a {@link Set} of keypair generator names supported by this
+ * Returns a {@link Set} of keypair generator names supported by this
* Factory. Those keypair generators may be used in conjunction with
- * the digital signature schemes with appendix supported by this library. A base asbtract class for both public and private DSS (Digital Signature
+ * A base asbtract class for both public and private DSS (Digital Signature
* Standard) keys. It encapsulates the three DSS numbers: According to the JDK, cryptographic Keys all have a format.
+ *
+ * According to the JDK, cryptographic Keys all have a format.
* The format used in this implementation is called Raw, and basically
* consists of the raw byte sequences of algorithm parameters. The exact order
- * of the byte sequences and the implementation details are given in each of
- * the relevant
+ * IMPORTANT: Under certain circumstances (e.g. in an X.509 certificate
+ * with inherited AlgorithmIdentifier's parameters of a SubjectPublicKeyInfo
+ * element) these three MPIs may be Returns
+ * Always returns A key-pair generator for asymetric keys to use in conjunction with the DSS
- * (Digital Signature Standard).
+ * References:
+ *
* Digital Signature
- * Standard (DSS), Federal Information Processing Standards Publication 186.
- * National Institute of Standards and Technology.
+ * Standard (DSS), Federal Information Processing Standards Publication
+ * 186. National Institute of Standards and Technology.
*/
-public class DSSKeyPairGenerator implements IKeyPairGenerator
+public class DSSKeyPairGenerator
+ implements IKeyPairGenerator
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "dss";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
+ private static final Logger log = Logger.getLogger(DSSKeyPairGenerator.class.getName());
/** The BigInteger constant 2. */
- private static final BigInteger TWO = new BigInteger("2");
+ private static final BigInteger TWO = BigInteger.valueOf(2L);
/** Property name of the length (Integer) of the modulus (p) of a DSS key. */
public static final String MODULUS_LENGTH = "gnu.crypto.dss.L";
/**
* Property name of the Boolean indicating wether or not to use default pre-
- * computed values of Configures this instance. This method applies the following algorithm described in 3.1 of
- * FIPS-186: Where Note that in this implementation, XSEED, the optional user input, is
- * always zero.
+ * Where
+ * Note that in this implementation, XSEED, the optional user input, is always
+ * zero.
*/
private synchronized BigInteger nextX()
{
byte[] xk = XKEY.toByteArray();
byte[] in = new byte[64]; // 512-bit block for SHS
System.arraycopy(xk, 0, in, 0, xk.length);
-
int[] H = Sha160.G(T_SHS[0], T_SHS[1], T_SHS[2], T_SHS[3], T_SHS[4], in, 0);
byte[] h = new byte[20];
for (int i = 0, j = 0; i < 5; i++)
{
- h[j++] = (byte) (H[i] >>> 24);
- h[j++] = (byte) (H[i] >>> 16);
- h[j++] = (byte) (H[i] >>> 8);
+ h[j++] = (byte)(H[i] >>> 24);
+ h[j++] = (byte)(H[i] >>> 16);
+ h[j++] = (byte)(H[i] >>> 8);
h[j++] = (byte) H[i];
}
BigInteger result = new BigInteger(1, h).mod(q);
XKEY = XKEY.add(result).add(BigInteger.ONE).mod(TWO_POW_160);
-
return result;
}
/**
- * Fills the designated byte array with random data. An object that implements the {@link IKeyPairCodec} operations for the
- * Raw format to use with DSS keypairs. Returns the encoded form of the designated DSS (Digital Signature
- * Standard) public key according to the Raw format supported by
- * this library. The Raw format for a DSA public key, in this implementation, is
- * a byte sequence consisting of the following:
+ * The Raw format for a DSA public key, in this implementation, is a
+ * byte sequence consisting of the following:
* Returns the encoded form of the designated DSS (Digital Signature
- * Standard) private key according to the Raw format supported by
- * this library. The Raw format for a DSA private key, in this implementation, is
- * a byte sequence consisting of the following:
+ * The Raw format for a DSA private key, in this implementation, is a
+ * byte sequence consisting of the following:
* The subjectPublicKey field, which is a BIT STRING, contains the
- * DER-encoded form of the DSA public key as an INTEGER.
+ * Note that RFC-3280 (page 79) implies that some certificates MAY have an
+ * absent, or NULL, parameters field in their AlgorithmIdentifier element,
+ * implying that those parameters MUST be inherited from another
+ * certificate. This implementation, encodes a NULL element as the DER
+ * value of the parameters field when such is the case.
+ *
+ * The subjectPublicKey field, which is a BIT STRING, contains the
+ * DER-encoded form of the DSA public key as an INTEGER.
*
* An object that embodies a DSS (Digital Signature Standard) private key. A randomly or pseudorandomly generated integer with Returns the encoded form of this private key according to the
- * designated format. Returns An object that embodies a DSS (Digital Signature Standard) public key. Returns the encoded form of this public key according to the designated
- * format. Returns An implementation of the DSA parameters generation as described in
- * FIPS-186.
+ * References:
+ *
* Digital Signature
- * Standard (DSS), Federal Information Processing Standards Publication 186.
- * National Institute of Standards and Technology.
+ * Standard (DSS), Federal Information Processing Standards Publication
+ * 186. National Institute of Standards and Technology.
*/
public class FIPS186
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final int DSA_PARAMS_SEED = 0;
public static final int DSA_PARAMS_COUNTER = 1;
@@ -73,7 +68,7 @@ public class FIPS186
public static final int DSA_PARAMS_G = 5;
/** The BigInteger constant 2. */
- private static final BigInteger TWO = new BigInteger("2");
+ private static final BigInteger TWO = BigInteger.valueOf(2L);
private static final BigInteger TWO_POW_160 = TWO.pow(160);
@@ -89,9 +84,6 @@ public class FIPS186
/** Our default source of randomness. */
private PRNG prng = null;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public FIPS186(int L, SecureRandom rnd)
{
super();
@@ -100,38 +92,31 @@ public class FIPS186
this.rnd = rnd;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
* This method generates the DSS
- *
+ *
* The DSS requires two primes , A base asbtract class for both public and private RSA keys. Returns the modulus Returns the public exponent Same as {@link #getPublicExponent()}. Returns An object that embodies an RSA private key. References:
+ * References:
* Returns An object that encapsulates an RSA public key. References:
+ * References:
* Returns the encoded form of this public key according to the designated
- * format. Returns A key-pair generator for asymetric keys to use in conjunction with the RSA
- * scheme. Reference:
+ * Reference:
* Configures this instance. The algorithm used here is described in nessie-pss-B.pdf
- * document which is part of the RSA-PSS submission to NESSIE.
+ * The algorithm used here is described in nessie-pss-B.pdf document
+ * which is part of the RSA-PSS submission to NESSIE.
+ * Fills the designated byte array with random data. The privateKey field, which is an OCTET STRING, contains the
- * DER-encoded form of the RSA private key defined as:
+ * As indicated in RFC-2459: "The parameters field shall have ASN.1 type NULL
+ * for this algorithm identifier.".
+ *
+ * The privateKey field, which is an OCTET STRING, contains the
+ * DER-encoded form of the RSA private key defined as:
* An object that implements the {@link IKeyPairCodec} interface for the
- * Raw format to use with RSA keypairs. Returns the encoded form of the designated RSA public key according to
- * the Raw format supported by this library. The Raw format for an RSA public key, in this implementation, is
- * a byte sequence consisting of the following:
+ * The Raw format for an RSA public key, in this implementation, is a
+ * byte sequence consisting of the following:
* Returns the encoded form of the designated RSA private key according to
- * the Raw format supported by this library. The Raw format for an RSA private key, in this implementation,
- * is a byte sequence consisting of the following:
+ * The Raw format for an RSA private key, in this implementation, is a
+ * byte sequence consisting of the following:
* An abstract class to facilitate implementing PRNG algorithms. Trivial constructor for use by concrete subclasses. The basic visible methods of any pseudo-random number generator. The [HAC] defines a PRNG (as implemented in this library) as follows:
+ * The [HAC] defines a PRNG (as implemented in this library) as follows:
* IMPLEMENTATION NOTE: Although all the concrete classes in this
+ *
+ * IMPLEMENTATION NOTE: Although all the concrete classes in this
* package implement the {@link Cloneable} interface, it is important to note
- * here that such an operation, for those algorithms that use an underlting
+ * here that such an operation, for those algorithms that use an underlying
* symmetric key block cipher, DOES NOT clone any session key material
* that may have been used in initialising the source PRNG (the instance to be
- * cloned). Instead a clone of an already initialised PRNG, that uses and
+ * cloned). Instead a clone of an already initialised PRNG, that uses an
* underlying symmetric key block cipher, is another instance with a clone of
- * the same cipher that operates with the same block size but without any
- * knowledge of neither key material nor key size. References:
+ * References:
* Returns the canonical name of this instance. Initialises the pseudo-random number generator scheme with the
- * appropriate attributes. Returns the next 8 bits of random data generated from this instance. Fills the designated byte array, starting from byte at index
- * Supplement, or possibly replace, the random state of this PRNG with
- * a random byte. Implementations are not required to implement this method in any
- * meaningful way; this may be a no-operation, and implementations may
- * throw an {@link UnsupportedOperationException}.
+ * Implementations are not required to implement this method in any meaningful
+ * way; this may be a no-operation, and implementations may throw an
+ * {@link UnsupportedOperationException}.
+ *
* @param b The byte to add.
*/
void addRandomByte(byte b);
/**
- * Supplement, or possibly replace, the random state of this PRNG with
- * a sequence of new random bytes. Implementations are not required to implement this method in any
- * meaningful way; this may be a no-operation, and implementations may
- * throw an {@link UnsupportedOperationException}.
+ * Implementations are not required to implement this method in any meaningful
+ * way; this may be a no-operation, and implementations may throw an
+ * {@link UnsupportedOperationException}.
+ *
* @param in The buffer of new random bytes to add.
*/
void addRandomBytes(byte[] in);
/**
- * Supplement, or possibly replace, the random state of this PRNG with
- * a sequence of new random bytes. Implementations are not required to implement this method in any
- * meaningful way; this may be a no-operation, and implementations may
- * throw an {@link UnsupportedOperationException}.
+ * Implementations are not required to implement this method in any meaningful
+ * way; this may be a no-operation, and implementations may throw an
+ * {@link UnsupportedOperationException}.
+ *
* @param in The buffer of new random bytes to add.
* @param offset The offset from whence to begin reading random bytes.
* @param length The number of random bytes to add.
- * @exception IndexOutOfBoundsException If offset, length,
- * or offset+length is out of bounds.
+ * @exception IndexOutOfBoundsException If offset, length, or
+ * offset+length is out of bounds.
*/
void addRandomBytes(byte[] in, int offset, int length);
/**
- * Returns a clone copy of this instance. A simple pseudo-random number generator that relies on a hash algorithm,
- * that (a) starts its operation by hashing a A Factory to instantiate pseudo random number generators. Returns an instance of a padding algorithm given its name. Returns a {@link Set} of names of padding algorithms supported by this
- * Factory. See RFC 3280:
- * Internet X.509 Public Key Infrastructure Certificate and
- * Certificate Revocation List (CRL) Profile.
- *
+ * An implementation of the Public Key Infrastructure's X.509 certificate path
+ * validation algorithm.
+ *
+ * See RFC 3280: Internet X.509
+ * Public Key Infrastructure Certificate and Certificate Revocation List (CRL)
+ * Profile.
+ *
* @author Casey Marshall (rsdio@metastatic.org)
*/
-public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
+public class PKIXCertPathValidatorImpl
+ extends CertPathValidatorSpi
{
-
- // Constants.
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
- private static void debug (String msg)
- {
- System.err.print (">> PKIXCertPathValidatorImpl: ");
- System.err.println (msg);
- }
+ private static final Logger log = Logger.getLogger(PKIXCertPathValidatorImpl.class.getName());
public static final String ANY_POLICY = "2.5.29.32.0";
- // Constructor.
- // -------------------------------------------------------------------------
-
public PKIXCertPathValidatorImpl()
{
super();
}
- // Instance methods.
- // -------------------------------------------------------------------------
-
public CertPathValidatorResult engineValidate(CertPath path,
CertPathParameters params)
- throws CertPathValidatorException, InvalidAlgorithmParameterException
+ throws CertPathValidatorException, InvalidAlgorithmParameterException
{
- if (!(params instanceof PKIXParameters))
+ if (! (params instanceof PKIXParameters))
throw new InvalidAlgorithmParameterException("not a PKIXParameters object");
-
// First check if the certificate path is valid.
//
// This means that:
//
- // (a) for all x in {1, ..., n-1}, the subject of certificate x is
- // the issuer of certificate x+1;
+ // (a) for all x in {1, ..., n-1}, the subject of certificate x is
+ // the issuer of certificate x+1;
//
- // (b) for all x in {1, ..., n}, the certificate was valid at the
- // time in question.
+ // (b) for all x in {1, ..., n}, the certificate was valid at the
+ // time in question.
//
// Because this is the X.509 algorithm, we also check if all
// cerificates are of type X509Certificate.
-
PolicyNodeImpl rootNode = new PolicyNodeImpl();
Set initPolicies = ((PKIXParameters) params).getInitialPolicies();
rootNode.setValidPolicy(ANY_POLICY);
@@ -160,7 +146,6 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
{
throw new CertPathValidatorException("invalid certificate path");
}
-
String sigProvider = ((PKIXParameters) params).getSigProvider();
PublicKey prevKey = null;
Date now = ((PKIXParameters) params).getDate();
@@ -178,7 +163,7 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
throw new CertPathValidatorException(ce.toString());
}
Set uce = getCritExts(p[i]);
- for (Iterator check = checks.iterator(); check.hasNext(); )
+ for (Iterator check = checks.iterator(); check.hasNext();)
{
try
{
@@ -188,23 +173,21 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
{
}
}
-
PolicyConstraint constr = null;
if (p[i] instanceof GnuPKIExtension)
{
- Extension pcx =
- ((GnuPKIExtension) p[i]).getExtension (PolicyConstraint.ID);
+ Extension pcx = ((GnuPKIExtension) p[i]).getExtension(PolicyConstraint.ID);
if (pcx != null)
constr = (PolicyConstraint) pcx.getValue();
}
else
{
- byte[] pcx = p[i].getExtensionValue (PolicyConstraint.ID.toString());
+ byte[] pcx = p[i].getExtensionValue(PolicyConstraint.ID.toString());
if (pcx != null)
{
try
{
- constr = new PolicyConstraint (pcx);
+ constr = new PolicyConstraint(pcx);
}
catch (Exception x)
{
@@ -212,14 +195,10 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
}
}
if (constr != null && constr.getRequireExplicitPolicy() >= 0)
- {
- policyConstraints.add (new int[]
- { p.length-i, constr.getRequireExplicitPolicy() });
- }
-
- updatePolicyTree(p[i], rootNode, p.length-i, (PKIXParameters) params,
- checkExplicitPolicy (p.length-i, policyConstraints));
-
+ policyConstraints.add(new int[] { p.length - i,
+ constr.getRequireExplicitPolicy() });
+ updatePolicyTree(p[i], rootNode, p.length - i, (PKIXParameters) params,
+ checkExplicitPolicy(p.length - i, policyConstraints));
// The rest of the tests involve this cert's relationship with the
// next in the path. If this cert is the end entity, we can stop.
if (i == 0)
@@ -236,36 +215,35 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
// If the DSA public key is missing its parameters, use those
// from the previous cert's key.
if (dsa == null || dsa.getP() == null || dsa.getG() == null
- || dsa.getQ() == null)
+ || dsa.getQ() == null)
{
if (prevKey == null)
throw new InvalidKeyException("DSA keys not chainable");
- if (!(prevKey instanceof DSAPublicKey))
+ if (! (prevKey instanceof DSAPublicKey))
throw new InvalidKeyException("DSA keys not chainable");
dsa = ((DSAPublicKey) prevKey).getParams();
pubKey = new DSSPublicKey(Registry.X509_ENCODING_ID,
- dsa.getP(),
- dsa.getQ(),
+ dsa.getP(), dsa.getQ(),
dsa.getG(),
((DSAPublicKey) pubKey).getY());
}
}
if (sigProvider == null)
- p[i-1].verify(pubKey);
+ p[i - 1].verify(pubKey);
else
- p[i-1].verify(pubKey, sigProvider);
+ p[i - 1].verify(pubKey, sigProvider);
prevKey = pubKey;
}
catch (Exception e)
{
throw new CertPathValidatorException(e.toString());
}
- if (!p[i].getSubjectDN().equals(p[i-1].getIssuerDN()))
+ if (! p[i].getSubjectDN().equals(p[i - 1].getIssuerDN()))
throw new CertPathValidatorException("issuer DN mismatch");
- boolean[] issuerUid = p[i-1].getIssuerUniqueID();
+ boolean[] issuerUid = p[i - 1].getIssuerUniqueID();
boolean[] subjectUid = p[i].getSubjectUniqueID();
if (issuerUid != null && subjectUid != null)
- if (!Arrays.equals(issuerUid, subjectUid))
+ if (! Arrays.equals(issuerUid, subjectUid))
throw new CertPathValidatorException("UID mismatch");
// Check the certificate against the revocation lists.
@@ -282,7 +260,7 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
}
List certStores = ((PKIXParameters) params).getCertStores();
List crls = new LinkedList();
- for (Iterator it = certStores.iterator(); it.hasNext(); )
+ for (Iterator it = certStores.iterator(); it.hasNext();)
{
CertStore cs = (CertStore) it.next();
try
@@ -297,30 +275,30 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
if (crls.isEmpty())
throw new CertPathValidatorException("no CRLs for issuer");
boolean certOk = false;
- for (Iterator it = crls.iterator(); it.hasNext(); )
+ for (Iterator it = crls.iterator(); it.hasNext();)
{
CRL crl = (CRL) it.next();
- if (!(crl instanceof X509CRL))
+ if (! (crl instanceof X509CRL))
continue;
X509CRL xcrl = (X509CRL) crl;
- if (!checkCRL(xcrl, p, now, p[i], pubKey, certStores))
+ if (! checkCRL(xcrl, p, now, p[i], pubKey, certStores))
continue;
- if (xcrl.isRevoked(p[i-1]))
+ if (xcrl.isRevoked(p[i - 1]))
throw new CertPathValidatorException("certificate is revoked");
else
certOk = true;
}
- if (!certOk)
- throw new CertPathValidatorException("certificate's validity could not be determined");
+ if (! certOk)
+ throw new CertPathValidatorException(
+ "certificate's validity could not be determined");
}
}
rootNode.setReadOnly();
-
// Now ensure that the first certificate in the chain was issued
// by a trust anchor.
Exception cause = null;
Set anchors = ((PKIXParameters) params).getTrustAnchors();
- for (Iterator i = anchors.iterator(); i.hasNext(); )
+ for (Iterator i = anchors.iterator(); i.hasNext();)
{
TrustAnchor anchor = (TrustAnchor) i.next();
X509Certificate anchorCert = null;
@@ -338,7 +316,7 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
{
if (anchorCert != null)
anchorCert.checkValidity(now);
- p[p.length-1].verify(anchorKey);
+ p[p.length - 1].verify(anchorKey);
if (anchorCert != null && anchorCert.getBasicConstraints() >= 0
&& anchorCert.getBasicConstraints() < p.length)
continue;
@@ -358,7 +336,7 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
selector.addIssuerName(anchor.getCAName());
List certStores = ((PKIXParameters) params).getCertStores();
List crls = new LinkedList();
- for (Iterator it = certStores.iterator(); it.hasNext(); )
+ for (Iterator it = certStores.iterator(); it.hasNext();)
{
CertStore cs = (CertStore) it.next();
try
@@ -372,10 +350,10 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
}
if (crls.isEmpty())
continue;
- for (Iterator it = crls.iterator(); it.hasNext(); )
+ for (Iterator it = crls.iterator(); it.hasNext();)
{
CRL crl = (CRL) it.next();
- if (!(crl instanceof X509CRL))
+ if (! (crl instanceof X509CRL))
continue;
X509CRL xcrl = (X509CRL) crl;
try
@@ -389,11 +367,10 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
Date nextUpdate = xcrl.getNextUpdate();
if (nextUpdate != null && nextUpdate.compareTo(now) < 0)
continue;
- if (xcrl.isRevoked(p[p.length-1]))
+ if (xcrl.isRevoked(p[p.length - 1]))
throw new CertPathValidatorException("certificate is revoked");
}
}
-
// The chain is valid; return the result.
return new PKIXCertPathValidatorResult(anchor, rootNode,
p[0].getPublicKey());
@@ -404,44 +381,39 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
continue;
}
}
-
// The path is not valid.
CertPathValidatorException cpve =
- new CertPathValidatorException("path validation failed");
+ new CertPathValidatorException("path validation failed");
if (cause != null)
- cpve.initCause (cause);
+ cpve.initCause(cause);
throw cpve;
}
- // Own methods.
- // -------------------------------------------------------------------------
-
/**
- * Check if a given CRL is acceptable for checking the revocation status
- * of certificates in the path being checked.
- *
- * The CRL is accepted iff:
+ * The CRL is accepted iff:
* A base abstract class to facilitate implementations of concrete
- * Signatures. Fills the designated byte array with random data. The visible methods of every signature-with-appendix scheme. The Handbook of Applied Cryptography (HAC), by A. Menezes & al. states:
+ * The visible methods of every signature-with-appendix scheme.
+ *
+ * The Handbook of Applied Cryptography (HAC), by A. Menezes & al. states:
* "Digital signature schemes which require the message as input to the
- * verification algorithm are called digital signature schemes with
- * appendix. ... They rely on cryptographic hash functions rather than
- * customised redundancy functions, and are less prone to existential forgery
- * attacks." References:
+ * References:
* Returns the canonical name of this signature scheme. Initialises this instance for signature verification. Initialises this instance for signature generation. Digests one byte of a message for signing or verification purposes. Digests a sequence of bytes from a message for signing or verification
- * purposes. Terminates a signature generation phase by digesting and processing the
- * context of the underlying message digest algorithm instance. Terminates a signature verification phase by digesting and processing
- * the context of the underlying message digest algorithm instance. Returns a clone copy of this instance. The visible methods of an object that knows how to encode and decode
+ * The visible methods of an object that knows how to encode and decode
* cryptographic signatures. Codecs are useful for (a) externalising signature
* output data for storage and on-the-wire transmission, as well as (b) re-
- * creating their internal Java representation from external sources. The DSS (Digital Signature Standard) algorithm makes use of the following
- * parameters: The integers
+ * The integers The signature of a message
+ * The signature of a message In the above, As an option, one may wish to check if The signature is transmitted along with the message to the verifier. References:
+ * In the above,
+ * As an option, one may wish to check if
+ * The signature is transmitted along with the message to the verifier.
+ *
+ * References:
*
- *
+ * Returns the output of a signature generation phase.
+ *
* @return an object encapsulating the DSS signature pair
- *
+ * Returns the output of a previously generated signature object as a pair of
+ * {@link java.math.BigInteger}.
+ *
* @return the DSS signature pair An object that implements the {@link ISignatureCodec} operations for the
- * Raw format to use with DSS signatures. Returns the encoded form of the designated DSS (Digital Signature
- * Standard) signature object according to the Raw format supported by
- * this library. The Raw format for a DSA signature, in this implementation, is a
- * byte sequence consisting of the following:
+ * The Raw format for a DSA signature, in this implementation, is a
+ * byte sequence consisting of the following:
* An implementation of the EME-PKCS1-V1.5 encoding and decoding methods. EME-PKCS1-V1.5 is parameterised by the entity References:
+ * EME-PKCS1-V1.5 is parameterised by the entity
+ * References:
* Generates an octet string The method then concatenates
+ * The method then concatenates This method uses a default PRNG to obtain the padding bytes.
+ * This method uses a default PRNG to obtain the padding bytes.
+ *
* @param M the message to encode.
* @return the encoded message Similar to {@link #encode(byte[])} method, except that the source of
+ * Similar to {@link #encode(byte[])} method, except that the source of
* randomness to use for obtaining the padding bytes (an instance of
- * {@link IRandom}) is given as a parameter. Similar to the {@link #encode(byte[], IRandom)} method, except that
- * the source of randmoness is an instance of {@link Random}.
- *
+ * Similar to the {@link #encode(byte[], IRandom)} method, except that the
+ * source of randmoness is an instance of {@link Random}.
+ *
* @param M the message to encode.
* @param rnd the {@link Random} instance to use as a source of randomness.
* @return the encoded message Separate the encoded message If the first octet of
+ * If the first octet of An implementation of the EMSA-PKCS1-V1.5 encoding scheme. EMSA-PKCS1-V1.5 is parameterised by the choice of hash function Hash and
- * hLen which denotes the length in octets of the hash function output. References:
+ * EMSA-PKCS1-V1.5 is parameterised by the choice of hash function Hash and
+ * hLen which denotes the length in octets of the hash function output.
+ *
+ * References:
* Trivial private constructor to enforce use through Factory method. Returns an instance of this object given a designated name of a hash
- * function. Frames the hash of a message, along with an ID of the hash function in
+ * Frames the hash of a message, along with an ID of the hash function in
* a DER sequence according to the specifications of EMSA-PKCS1-V1.5 as
- * described in RFC-3447 (see class documentation). An implementation of the EMSA-PSS encoding/decoding scheme. EMSA-PSS coincides with EMSA4 in IEEE P1363a D5 except that EMSA-PSS acts
- * on octet strings and not on bit strings. In particular, the bit lengths of
- * the hash and the salt must be multiples of 8 in EMSA-PSS. Moreover, EMSA4
- * outputs an integer of a desired bit length rather than an octet string. EMSA-PSS is parameterized by the choice of hash function Hash and mask
+ * An implementation of the EMSA-PSS encoding/decoding scheme.
+ *
+ * EMSA-PSS coincides with EMSA4 in IEEE P1363a D5 except that EMSA-PSS acts on
+ * octet strings and not on bit strings. In particular, the bit lengths of the
+ * hash and the salt must be multiples of 8 in EMSA-PSS. Moreover, EMSA4 outputs
+ * an integer of a desired bit length rather than an octet string.
+ *
+ * EMSA-PSS is parameterized by the choice of hash function Hash and mask
* generation function MGF. In this submission, MGF is based on a Hash
* definition that coincides with the corresponding definitions in IEEE Std
* 1363-2000, PKCS #1 v2.0, and the draft ANSI X9.44. In PKCS #1 v2.0 and the
* draft ANSI X9.44, the recommended hash function is SHA-1, while IEEE Std
- * 1363-2000 recommends SHA-1 and RIPEMD-160. References:
+ * References:
* Trivial private constructor to enforce use through Factory method. Returns an instance of this object given a designated name of a hash
- * function. The encoding operation EMSA-PSS-Encode computes the hash of a message
+ * The encoding operation EMSA-PSS-Encode computes the hash of a message
* The decoding operation EMSA-PSS-Decode recovers the message hash from
- * an encoded message A mask generation function takes an octet string of variable length
- * and a desired output length as input, and outputs an octet string of the
- * desired length. There may be restrictions on the length of the input and
- * output octet strings, but such bounds are generally very large. Mask
- * generation functions are deterministic; the octet string output is
- * completely determined by the input octet string. The output of a mask
- * generation function should be pseudorandom, that is, it should be
- * infeasible to predict, given one part of the output but not the input,
- * another part of the output. The provable security of RSA-PSS relies on
- * the random nature of the output of the mask generation function, which in
- * turn relies on the random nature of the underlying hash function. Utility methods related to the RSA algorithm. References:
+ * References:
* An implementation of the RSASP method: Assuming that the
- * designated RSA private key is a valid one, this method computes a
- * signature representative for a designated message
- * representative signed by the holder of the designated RSA private
- * key.
- *
+ * An implementation of the RSASP method: Assuming that the designated
+ * RSA private key is a valid one, this method computes a signature
+ * representative for a designated message representative signed
+ * by the holder of the designated RSA private key.
+ *
* @param K the RSA private key.
* @param m the message representative: an integer between
- * An implementation of the RSAVP method: Assuming that the
- * designated RSA public key is a valid one, this method computes a
- * message representative for the designated signature
- * representative generated by an RSA private key, for a message
- * intended for the holder of the designated RSA public key. An implementation of the An implementation of the Converts a multi-precision integer (MPI) Returns a random MPI with a random bit-length of the form The RSA-PKCS1-V1.5 signature scheme is a digital signature scheme with
+ * The RSA-PKCS1-V1.5 signature scheme is a digital signature scheme with
* appendix (SSA) combining the RSA algorithm with the EMSA-PKCS1-v1_5 encoding
- * method. References:
+ * References:
* Constructs an instance of this object using the designated message
- * digest algorithm as its underlying hash function. The RSA-PSS signature scheme is a public-key encryption scheme combining
- * the RSA algorithm with the Probabilistic Signature Scheme (PSS) encoding
- * method. The inventors of RSA are Ronald L. Rivest, Adi Shamir, and Leonard Adleman,
+ * The RSA-PSS signature scheme is a public-key encryption scheme combining the
+ * RSA algorithm with the Probabilistic Signature Scheme (PSS) encoding method.
+ *
+ * The inventors of RSA are Ronald L. Rivest, Adi Shamir, and Leonard Adleman,
* while the inventors of the PSS encoding method are Mihir Bellare and Phillip
* Rogaway. During efforts to adopt RSA-PSS into the P1363a standards effort,
* certain adaptations to the original version of RSA-PSS were made by Mihir
* Bellare and Phillip Rogaway and also by Burt Kaliski (the editor of IEEE
- * P1363a) to facilitate implementation and integration into existing protocols. References:
+ * P1363a) to facilitate implementation and integration into existing protocols.
+ *
+ * References:
* Constructs an instance of this object using the designated message
- * digest algorithm as its underlying hash function, and having 0-octet
- * salt. Constructs an instance of this object using the designated message
- * digest algorithm as its underlying hash function.
- *
- * @return the octet sequence An object that implements the {@link gnu.crypto.sig.ISignatureCodec}
- * operations for the Raw format to use with RSA-PSS signatures. Returns the encoded form of the designated RSA-PSS signature object
- * according to the Raw format supported by this library. The Raw format for an RSA-PSS signature, in this implementation,
- * is a byte sequence consisting of the following:
+ * The Raw format for an RSA-PSS signature, in this implementation, is
+ * a byte sequence consisting of the following:
* Encodes up to three bytes of the array This method does not check to make sure the arrays are large enough to
+ * specifying
+ * This method does not check to make sure the arrays are large enough to
* accomodate Decodes four bytes from array The source and destination arrays can be manipulated anywhere along
- * their length by specifying This method does not check to make sure your arrays are large enough
- * to accomodate
+ * The source and destination arrays can be manipulated anywhere along their
+ * length by specifying
+ * This method does not check to make sure your arrays are large enough to
+ * accomodate Concrete subclasses must implement the {@link doDestroy()} method
- * instead of {@link Destroyable#destroy()}; the behavior of that method
- * should match exactly the behavior desired of Note that if a {@link DestroyFailedException} occurs when the timeout
+ * destroyed after a timeout elapses. On creation, an object that extends this
+ * class will automatically be added to a {@link Timer} object that, once a
+ * timeout elapses, will automatically call the {@link Destroyable#destroy()}
+ * method.
+ *
+ * Concrete subclasses must implement the {@link #doDestroy()} method instead of
+ * {@link Destroyable#destroy()}; the behavior of that method should match
+ * exactly the behavior desired of
+ * Note that if a {@link DestroyFailedException} occurs when the timeout
* expires, it will not be reported.
- *
+ *
* @see Destroyable
*/
-public abstract class ExpirableObject implements Destroyable
+public abstract class ExpirableObject
+ implements Destroyable
{
-
- // Constants and fields.
- // -------------------------------------------------------------------------
-
/**
* The default timeout, used in the default constructor.
*/
@@ -82,9 +79,6 @@ public abstract class ExpirableObject implements Destroyable
*/
private final Destroyer destroyer;
- // Constructors.
- // -------------------------------------------------------------------------
-
/**
* Create a new expirable object that will expire after one hour.
*/
@@ -94,12 +88,11 @@ public abstract class ExpirableObject implements Destroyable
}
/**
- * Create a new expirable object that will expire after the specified
- * timeout.
- *
+ * Create a new expirable object that will expire after the specified timeout.
+ *
* @param delay The delay before expiration.
* @throws IllegalArgumentException If delay is negative, or if
- *
+ * This method MUST be used in the gnu.java.security and gnu.javax.crypto
+ * packages to ensure they would work with a version 1.4 only of the Java
+ * class library API.
+ *
+ * @param aString a string representation of an integer.
+ * @return the {@link Integer} object representing the designated string.
+ */
+ public static final Integer valueOf(String aString)
+ {
+ Integer result;
+ synchronized (cache)
+ {
+ result = (Integer) cache.get(aString);
+ if (result == null)
+ {
+ result = Integer.valueOf(aString);
+ cache.put(aString, result);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Simulates the
+ * This method MUST be used in the gnu.java.security and gnu.javax.crypto
+ * packages to ensure they would work with a version 1.4 only of the Java
+ * class library API.
+ *
+ * @param anInt a decimal integer.
+ * @return the {@link Integer} object representing the designated primitive.
+ */
+ public static final Integer valueOf(int anInt)
+ {
+ return valueOf(Integer.toString(anInt, 10));
+ }
+}
diff --git a/libjava/classpath/gnu/java/security/util/PRNG.java b/libjava/classpath/gnu/java/security/util/PRNG.java
index 138cc6b..7bb27cb 100644
--- a/libjava/classpath/gnu/java/security/util/PRNG.java
+++ b/libjava/classpath/gnu/java/security/util/PRNG.java
@@ -45,27 +45,20 @@ import gnu.java.security.prng.LimitReachedException;
import gnu.java.security.prng.MDGenerator;
/**
- * A useful hash-based (SHA) pseudo-random number generator used
- * throughout this library.
+ * A useful hash-based (SHA) pseudo-random number generator used throughout this
+ * library.
*
* @see MDGenerator
*/
public class PRNG
{
- // Constans and fields
- // --------------------------------------------------------------------------
-
/** The underlying {@link IRandom}. */
private IRandom delegate;
- // Constructor(s)
- // --------------------------------------------------------------------------
-
/**
* Private constructor to enforce using the Factory method.
*
- * @param delegate
- * the undelying {@link IRandom} object used.
+ * @param delegate the undelying {@link IRandom} object used.
*/
private PRNG(IRandom delegate)
{
@@ -74,9 +67,6 @@ public class PRNG
this.delegate = delegate;
}
- // Class methods
- // --------------------------------------------------------------------------
-
public static final PRNG getInstance()
{
IRandom delegate = new MDGenerator();
@@ -86,10 +76,10 @@ public class PRNG
// initialise it with a seed
long t = System.currentTimeMillis();
byte[] seed = new byte[] {
- (byte) (t >>> 56), (byte) (t >>> 48),
- (byte) (t >>> 40), (byte) (t >>> 32),
- (byte) (t >>> 24), (byte) (t >>> 16),
- (byte) (t >>> 8), (byte) t};
+ (byte)(t >>> 56), (byte)(t >>> 48),
+ (byte)(t >>> 40), (byte)(t >>> 32),
+ (byte)(t >>> 24), (byte)(t >>> 16),
+ (byte)(t >>> 8), (byte) t };
map.put(MDGenerator.SEEED, seed);
delegate.init(map); // default is to use SHA-1 hash
}
@@ -97,19 +87,14 @@ public class PRNG
{
throw new ExceptionInInitializerError(x);
}
-
return new PRNG(delegate);
}
- // Instance methods
- // --------------------------------------------------------------------------
-
/**
* Completely fills the designated A collection of prime number related utilities used in this library. Trial division for the first 1000 small primes. Returns Java port of Colin Plumb primality test (Euler Criterion)
- * implementation for a base of 2 --from bnlib-1.1 release, function
- * primeTest() in prime.c. this is his comments. "Now, check that bn is prime. If it passes to the base 2, it's prime
- * beyond all reasonable doubt, and everything else is just gravy, but it
- * gives people warm fuzzies to do it. This starts with verifying Euler's criterion for a base of 2. This is
- * the fastest pseudoprimality test that I know of, saving a modular squaring
- * over a Fermat test, as well as being stronger. 7/8 of the time, it's as
- * strong as a strong pseudoprimality test, too. (The exception being when
- * The remaining case is We could back that down another step, looking at span can be negative, resulting in a decresing sequence.
- *
- * If span is 0, then the sequence will contain {start,
+ *
+ * span can be negative, resulting in a decresing sequence.
+ *
+ * If span is 0, then the sequence will contain {start,
* end} if start != end, or just the singleton
* start if start == end.
- *
+ *
* @param start The starting value.
* @param end The ending value.
* @param span The increment value.
@@ -104,36 +98,26 @@ public final class Sequence extends AbstractList
if (span == 0)
{
if (start != end)
- {
- sequence = new Integer[] { new Integer(start), new Integer(end) };
- }
+ sequence = new Integer[] { Integer.valueOf(start),
+ Integer.valueOf(end) };
else
- {
- sequence = new Integer[] { new Integer(start) };
- }
+ sequence = new Integer[] { Integer.valueOf(start) };
}
else
{
LinkedList l = new LinkedList();
for (int i = start; i != end; i += span)
- {
- l.add(new Integer(i));
- }
- l.add(new Integer(end));
+ l.add(Integer.valueOf(i));
+
+ l.add(Integer.valueOf(end));
sequence = (Integer[]) l.toArray(new Integer[l.size()]);
}
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
public Object get(int index)
{
if (index < 0 || index >= size())
- {
- throw new IndexOutOfBoundsException("index=" + index + ", size="
- + size());
- }
+ throw new IndexOutOfBoundsException("index=" + index + ", size=" + size());
return sequence[index];
}
diff --git a/libjava/classpath/gnu/java/security/util/SimpleList.java b/libjava/classpath/gnu/java/security/util/SimpleList.java
index b2525c4..74f3baf 100644
--- a/libjava/classpath/gnu/java/security/util/SimpleList.java
+++ b/libjava/classpath/gnu/java/security/util/SimpleList.java
@@ -43,25 +43,19 @@ import java.util.Collection;
import java.util.Iterator;
/**
- * A simple way to create immutable n-tuples. This class can be created with
- * up to four elements specified via one of the constructors, or with a
- * collection of arbitrary size.
+ * A simple way to create immutable n-tuples. This class can be created with up
+ * to four elements specified via one of the constructors, or with a collection
+ * of arbitrary size.
*/
-public final class SimpleList extends AbstractList
+public final class SimpleList
+ extends AbstractList
{
-
- // Fields.
- // ------------------------------------------------------------------------
-
private final Object[] elements;
- // Constructors.
- // ------------------------------------------------------------------------
-
/**
* Create a singleton list.
- *
- * @param e1 The first element.
+ *
+ * @param element The first element.
*/
public SimpleList(final Object element)
{
@@ -71,7 +65,7 @@ public final class SimpleList extends AbstractList
/**
* Create an ordered pair (2-tuple).
- *
+ *
* @param e1 The first element.
* @param e2 The second element.
*/
@@ -84,7 +78,7 @@ public final class SimpleList extends AbstractList
/**
* Create a 3-tuple.
- *
+ *
* @param e1 The first element.
* @param e2 The second element.
* @param e3 The third element.
@@ -99,7 +93,7 @@ public final class SimpleList extends AbstractList
/**
* Create a 4-tuple.
- *
+ *
* @param e1 The first element.
* @param e2 The second element.
* @param e3 The third element.
@@ -124,10 +118,10 @@ public final class SimpleList extends AbstractList
}
/**
- * Create an n-tuple of arbitrary size. Even if the supplied collection has
- * no natural order, the created n-tuple will have the order that the
- * elements are returned by the collection's iterator.
- *
+ * Create an n-tuple of arbitrary size. Even if the supplied collection has no
+ * natural order, the created n-tuple will have the order that the elements
+ * are returned by the collection's iterator.
+ *
* @param c The collection.
*/
public SimpleList(Collection c)
@@ -135,14 +129,9 @@ public final class SimpleList extends AbstractList
elements = new Object[c.size()];
int i = 0;
for (Iterator it = c.iterator(); it.hasNext() && i < elements.length;)
- {
- elements[i++] = it.next();
- }
+ elements[i++] = it.next();
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
public int size()
{
if (elements == null)
@@ -153,14 +142,9 @@ public final class SimpleList extends AbstractList
public Object get(int index)
{
if (elements == null)
- {
- throw new IndexOutOfBoundsException("list is empty");
- }
+ throw new IndexOutOfBoundsException("list is empty");
if (index < 0 || index >= elements.length)
- {
- throw new IndexOutOfBoundsException("index=" + index + ", size="
- + size());
- }
+ throw new IndexOutOfBoundsException("index=" + index + ", size=" + size());
return elements[index];
}
diff --git a/libjava/classpath/gnu/java/security/util/Util.java b/libjava/classpath/gnu/java/security/util/Util.java
index f39afb9..c7a6810f 100644
--- a/libjava/classpath/gnu/java/security/util/Util.java
+++ b/libjava/classpath/gnu/java/security/util/Util.java
@@ -41,47 +41,37 @@ package gnu.java.security.util;
import java.math.BigInteger;
/**
- * A collection of utility methods used throughout this project. Returns a string of hexadecimal digits from a byte array. Each byte is
- * converted to 2 hex symbols; zero(es) included. This method calls the method with same name and three arguments as:
+ * This method calls the method with same name and three arguments as:
* Returns a string of hexadecimal digits from a byte array, starting at
- * Returns a string of hexadecimal digits from a byte array. Each byte is
- * converted to 2 hex symbols; zero(es) included. The argument is
- * treated as a large little-endian integer and is returned as a
- * large big-endian integer. This method calls the method with same name and three arguments as:
+ * This method calls the method with same name and three arguments as:
* Returns a string of hexadecimal digits from a byte array, starting at
- * The byte array is treated as a large little-endian integer, and
- * is returned as a large big-endian integer.
+ * The byte array is treated as a large little-endian integer, and is returned
+ * as a large big-endian integer.
+ *
* @param ba the byte array to convert.
* @param offset the index from which to start considering the bytes to
- * convert.
+ * convert.
* @param length the count of bytes, starting from the designated offset to
- * convert.
- * @return a string of hexadecimal characters (two for each byte)
- * representing the designated input byte sub-array.
+ * convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte sub-array.
*/
public static final String toReversedString(byte[] ba, int offset, int length)
{
@@ -157,14 +145,16 @@ public class Util
{
k = ba[offset + i--];
buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
- buf[j++] = HEX_DIGITS[k & 0x0F];
+ buf[j++] = HEX_DIGITS[ k & 0x0F];
}
return new String(buf);
}
/**
- * Returns a byte array from a string of hexadecimal digits.
+ * Returns a byte array from a string of hexadecimal digits.
+ * Returns a byte array from a string of hexadecimal digits, interpreting
- * them as a large big-endian integer and returning it as a large
- * little-endian integer. Returns a number from Returns a string of 8 hexadecimal digits (most significant digit first)
- * corresponding to the unsigned integer Returns a string of hexadecimal digits from an integer array. Each int
- * is converted to 4 hex symbols. Returns a string of 16 hexadecimal digits (most significant digit first)
- * corresponding to the unsigned long Similar to the Similar to the Similar to the Dumps a byte array as a string, in a format that is easy to read for
+ * Dumps a byte array as a string, in a format that is easy to read for
* debugging. The string If
+ * If Returns a string of 2 hexadecimal digits (most significant digit first)
- * corresponding to the lowest 8 bits of Converts a designated byte array to a Base-64 representation, with the
+ * Converts a designated byte array to a Base-64 representation, with the
* exceptions that (a) leading 0-byte(s) are ignored, and (b) the character
- * '.' (dot) shall be used instead of "+' (plus). Used by SASL password file manipulation primitives.
+ * Used by SASL password file manipulation primitives.
+ *
* @param buffer an arbitrary sequence of bytes to represent in Base-64.
* @return unpadded (without the '=' character(s)) Base-64 representation of
- * the input.
+ * the input.
*/
public static final String toBase64(byte[] buffer)
{
@@ -535,9 +496,7 @@ public class Util
notleading = true;
}
if (pos >= len)
- {
- break;
- }
+ break;
else
{
try
@@ -555,44 +514,38 @@ public class Util
while (true);
if (notleading)
- {
- return sb.toString();
- }
+ return sb.toString();
return "0";
}
/**
- * The inverse function of the above. Converts a string representing the encoding of some bytes in Base-64
- * to their original form.
+ * Converts a string representing the encoding of some bytes in Base-64 to
+ * their original form.
+ *
* @param str the Base-64 encoded representation of some byte(s).
* @return the bytes represented by the Treats the input as the MSB representation of a number, and discards
+ * Treats the input as the MSB representation of a number, and discards
* leading zero elements. For efficiency, the input is simply returned if no
- * leading zeroes are found. Returns a hexadecimal dump of the trimmed bytes of a {@link BigInteger}.
- *
+ * 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,
+ *
+ * Once compiled, a regular expression object is reusable as well as
+ * threadsafe: multiple threads can use the RE instance simultaneously
+ * to match against different input text.
+ *
+ * Various methods attempt to match input text against a compiled
+ * regular expression. These methods are:
+ *
+ *
+ * These methods all have similar argument lists. The input can be a
+ * CharIndexed, String, a character array, a StringBuffer, or an
+ * InputStream of some sort. Note that when using an
+ * 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.
+ *
+ * Although the input object can be of various types, it is recommended
+ * that it should be a CharIndexed because {@link CharIndexed#getLastMatch()}
+ * can show the last match found on this input, which helps the expression
+ * \G work as the end of the previous match.
+ *
+ *
+ *
+ * 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 an InputStream, this means an
+ * offset from the current read position, so subsequent calls with the
+ * same index argument on 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.
+ *
+ *
+ * You can optionally affect the execution environment by using a
+ * combination of execution flags (constants listed below).
+ *
+ *
+ * All operations on a regular expression are performed in a
+ * thread-safe manner.
+ *
+ * @author Wes Biggs
+ * @version 1.1.5-dev, to be released
+ */
+
+public class RE extends REToken {
+
+ private static final class IntPair implements Serializable {
+ public int first, second;
+ }
+
+ private static final class CharUnit implements Serializable {
+ public char ch;
+ public boolean bk;
+ }
+
+ // This String will be returned by getVersion()
+ private static final String VERSION = "1.1.5-dev";
+
+ // The localized strings are kept in a separate file
+ private static ResourceBundle messages = PropertyResourceBundle.getBundle("gnu/java/util/regex/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;
+ private int maximumLength;
+
+ /**
+ * Compilation flag. Do not differentiate case. Subsequent
+ * searches using this RE will be case insensitive.
+ */
+ public static final int REG_ICASE = 0x02;
+
+ /**
+ * 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 = 0x04;
+
+ /**
+ * 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 = 0x08;
+
+ /**
+ * 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.
+ *
+ * This example demonstrates the results of various ways of matching on
+ * a substring.
+ *
+ *
+ * // Results:
+ *
+ *
+ * can be viewed (given that myMatch is not null) by creating
+ *
+ *
+ * But you can save yourself that work, since the
+ *
+ * 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
+ *
+ *
+ * The enumerated type is especially useful when searching on a Reader
+ * or InputStream, because the InputStream read position cannot be
+ * guaranteed after calling
+ * 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 Wes Biggs
+ * @see gnu.java.util.regex.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());
+ }
+ }
+}
+
+
diff --git a/libjava/classpath/gnu/javax/crypto/RSACipherImpl.java b/libjava/classpath/gnu/javax/crypto/RSACipherImpl.java
index 0a4c29d..60504ec 100644
--- a/libjava/classpath/gnu/javax/crypto/RSACipherImpl.java
+++ b/libjava/classpath/gnu/javax/crypto/RSACipherImpl.java
@@ -1,5 +1,5 @@
-/* DiffieHellmanImpl.java -- implementation of the Diffie-Hellman key agreement.
- Copyright (C) 2005 Free Software Foundation, Inc.
+/* RSACipherImpl.java --
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,26 +38,21 @@ exception statement from your version. */
package gnu.javax.crypto;
-import gnu.classpath.ByteArray;
import gnu.classpath.debug.Component;
import gnu.classpath.debug.SystemLogger;
+import gnu.java.security.util.ByteArray;
import java.math.BigInteger;
-
import java.security.AlgorithmParameters;
-import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
-
import java.security.interfaces.RSAKey;
-import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
+import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
-
import java.security.spec.AlgorithmParameterSpec;
-
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
@@ -67,10 +62,10 @@ import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
-public class RSACipherImpl extends CipherSpi
+public class RSACipherImpl
+ extends CipherSpi
{
private static final Logger logger = SystemLogger.SYSTEM;
-
private static final byte[] EMPTY = new byte[0];
private int opmode = -1;
private RSAPrivateKey decipherKey = null;
@@ -80,48 +75,44 @@ public class RSACipherImpl extends CipherSpi
private byte[] dataBuffer = null;
private int pos = 0;
- protected void engineSetMode (String mode) throws NoSuchAlgorithmException
+ protected void engineSetMode(String mode) throws NoSuchAlgorithmException
{
- throw new NoSuchAlgorithmException ("only one mode available");
+ throw new NoSuchAlgorithmException("only one mode available");
}
- protected void engineSetPadding (String pad) throws NoSuchPaddingException
+ protected void engineSetPadding(String pad) throws NoSuchPaddingException
{
- throw new NoSuchPaddingException ("only one padding available");
+ throw new NoSuchPaddingException("only one padding available");
}
- protected int engineGetBlockSize ()
+ protected int engineGetBlockSize()
{
return 1;
}
- protected int engineGetOutputSize (int inputLen)
+ protected int engineGetOutputSize(int inputLen)
{
int outputLen = 0;
if (decipherKey != null)
- {
- outputLen = (decipherKey.getModulus ().bitLength () + 7) / 8;
- }
+ outputLen = (decipherKey.getModulus().bitLength() + 7) / 8;
else if (encipherKey != null)
- {
- outputLen = (encipherKey.getModulus ().bitLength () + 7) / 8;
- }
+ outputLen = (encipherKey.getModulus().bitLength() + 7) / 8;
else
- throw new IllegalStateException ("not initialized");
+ throw new IllegalStateException("not initialized");
if (inputLen > outputLen)
- throw new IllegalArgumentException ("not configured to encode " + inputLen
- + "bytes; at most " + outputLen);
+ throw new IllegalArgumentException("not configured to encode " + inputLen
+ + "bytes; at most " + outputLen);
return outputLen;
}
- protected int engineGetKeySize (final Key key) throws InvalidKeyException
+ protected int engineGetKeySize(final Key key) throws InvalidKeyException
{
- if (!(key instanceof RSAKey))
- throw new InvalidKeyException ("not an RSA key");
- return ((RSAKey) key).getModulus ().bitLength ();
+ if (! (key instanceof RSAKey))
+ throw new InvalidKeyException("not an RSA key");
+ return ((RSAKey) key).getModulus().bitLength();
}
- protected byte[] engineGetIV ()
+ protected byte[] engineGetIV()
{
return null;
}
@@ -131,18 +122,18 @@ public class RSACipherImpl extends CipherSpi
return null;
}
- protected void engineInit (int opmode, Key key, SecureRandom random)
- throws InvalidKeyException
+ protected void engineInit(int opmode, Key key, SecureRandom random)
+ throws InvalidKeyException
{
int outputLen = 0;
if (opmode == Cipher.ENCRYPT_MODE)
{
- if (!(key instanceof RSAPublicKey))
- throw new InvalidKeyException ("expecting a RSAPublicKey");
+ if (! (key instanceof RSAPublicKey))
+ throw new InvalidKeyException("expecting a RSAPublicKey");
encipherKey = (RSAPublicKey) key;
decipherKey = null;
blindingKey = null;
- outputLen = (encipherKey.getModulus ().bitLength () + 7) / 8;
+ outputLen = (encipherKey.getModulus().bitLength() + 7) / 8;
}
else if (opmode == Cipher.DECRYPT_MODE)
{
@@ -151,74 +142,78 @@ public class RSACipherImpl extends CipherSpi
decipherKey = (RSAPrivateKey) key;
encipherKey = null;
blindingKey = null;
- outputLen = (decipherKey.getModulus ().bitLength () + 7) / 8;
+ outputLen = (decipherKey.getModulus().bitLength() + 7) / 8;
}
else if (key instanceof RSAPublicKey)
{
if (decipherKey == null)
- throw new IllegalStateException ("must configure decryption key first");
- if (!decipherKey.getModulus ().equals (((RSAPublicKey) key).getModulus ()))
- throw new InvalidKeyException ("blinding key is not compatible");
+ throw new IllegalStateException("must configure decryption key first");
+ if (! decipherKey.getModulus().equals(((RSAPublicKey) key).getModulus()))
+ throw new InvalidKeyException("blinding key is not compatible");
blindingKey = (RSAPublicKey) key;
return;
}
else
- throw new InvalidKeyException ("expecting either an RSAPrivateKey or an RSAPublicKey (for blinding)");
+ throw new InvalidKeyException(
+ "expecting either an RSAPrivateKey or an RSAPublicKey (for blinding)");
}
else
- throw new IllegalArgumentException ("only encryption and decryption supported");
+ throw new IllegalArgumentException("only encryption and decryption supported");
this.random = random;
this.opmode = opmode;
pos = 0;
dataBuffer = new byte[outputLen];
}
- protected void engineInit (int opmode, Key key, AlgorithmParameterSpec spec, SecureRandom random)
- throws InvalidKeyException
+ protected void engineInit(int opmode, Key key, AlgorithmParameterSpec spec,
+ SecureRandom random) throws InvalidKeyException
{
- engineInit (opmode, key, random);
+ engineInit(opmode, key, random);
}
- protected void engineInit (int opmode, Key key, AlgorithmParameters params, SecureRandom random)
- throws InvalidKeyException
+ protected void engineInit(int opmode, Key key, AlgorithmParameters params,
+ SecureRandom random) throws InvalidKeyException
{
- engineInit (opmode, key, random);
+ engineInit(opmode, key, random);
}
- protected byte[] engineUpdate (byte[] in, int offset, int length)
+ protected byte[] engineUpdate(byte[] in, int offset, int length)
{
if (opmode != Cipher.ENCRYPT_MODE && opmode != Cipher.DECRYPT_MODE)
- throw new IllegalStateException ("not initialized");
- System.arraycopy (in, offset, dataBuffer, pos, length);
+ throw new IllegalStateException("not initialized");
+ System.arraycopy(in, offset, dataBuffer, pos, length);
pos += length;
return EMPTY;
}
- protected int engineUpdate (byte[] in, int offset, int length, byte[] out, int outOffset)
+ protected int engineUpdate(byte[] in, int offset, int length, byte[] out,
+ int outOffset)
{
- engineUpdate (in, offset, length);
+ engineUpdate(in, offset, length);
return 0;
}
- protected byte[] engineDoFinal (byte[] in, int offset, int length)
- throws IllegalBlockSizeException, BadPaddingException
+ protected byte[] engineDoFinal(byte[] in, int offset, int length)
+ throws IllegalBlockSizeException, BadPaddingException
{
- engineUpdate (in, offset, length);
+ engineUpdate(in, offset, length);
if (opmode == Cipher.DECRYPT_MODE)
{
if (pos < dataBuffer.length)
- throw new IllegalBlockSizeException ("expecting exactly " + dataBuffer.length + " bytes");
- BigInteger enc = new BigInteger (1, dataBuffer);
- byte[] dec = rsaDecrypt (enc);
- logger.log (Component.CRYPTO, "RSA: decryption produced\n{0}",
- new ByteArray (dec));
+ throw new IllegalBlockSizeException("expecting exactly "
+ + dataBuffer.length + " bytes");
+ BigInteger enc = new BigInteger(1, dataBuffer);
+ byte[] dec = rsaDecrypt(enc);
+ logger.log(Component.CRYPTO, "RSA: decryption produced\n{0}",
+ new ByteArray(dec));
if (dec[0] != 0x02)
- throw new BadPaddingException ("expected padding type 2");
+ throw new BadPaddingException("expected padding type 2");
int i;
- for (i = 1; i < dec.length && dec[i] != 0x00; i++);
- int len = dec.length - i;
+ for (i = 1; i < dec.length && dec[i] != 0x00; i++)
+ ; // keep incrementing i
+ int len = dec.length - i - 1; // skip the 0x00 byte
byte[] result = new byte[len];
- System.arraycopy (dec, i, result, 0, len);
+ System.arraycopy(dec, i + 1, result, 0, len);
pos = 0;
return result;
}
@@ -226,29 +221,29 @@ public class RSACipherImpl extends CipherSpi
{
offset = dataBuffer.length - pos;
if (offset < 3)
- throw new IllegalBlockSizeException ("input is too large to encrypt");
+ throw new IllegalBlockSizeException("input is too large to encrypt");
byte[] dec = new byte[dataBuffer.length];
dec[0] = 0x02;
if (random == null)
- random = new SecureRandom ();
- byte[] pad = new byte[offset - 2];
- random.nextBytes (pad);
- for (int i = 0; i < pad.length; i++)
- if (pad[i] == 0)
- pad[i] = 1;
- System.arraycopy (pad, 0, dec, 1, pad.length);
+ random = new SecureRandom();
+ byte[] pad = new byte[offset - 2];
+ random.nextBytes(pad);
+ for (int i = 0; i < pad.length; i++)
+ if (pad[i] == 0)
+ pad[i] = 1;
+ System.arraycopy(pad, 0, dec, 1, pad.length);
dec[dec.length - pos] = 0x00;
- System.arraycopy (dataBuffer, 0, dec, offset, pos);
- logger.log (Component.CRYPTO, "RSA: produced padded plaintext\n{0}",
- new ByteArray (dec));
- BigInteger x = new BigInteger (1, dec);
- BigInteger y = x.modPow (encipherKey.getPublicExponent (),
- encipherKey.getModulus ());
- byte[] enc = y.toByteArray ();
+ System.arraycopy(dataBuffer, 0, dec, offset, pos);
+ logger.log(Component.CRYPTO, "RSA: produced padded plaintext\n{0}",
+ new ByteArray(dec));
+ BigInteger x = new BigInteger(1, dec);
+ BigInteger y = x.modPow(encipherKey.getPublicExponent(),
+ encipherKey.getModulus());
+ byte[] enc = y.toByteArray();
if (enc[0] == 0x00)
{
byte[] tmp = new byte[enc.length - 1];
- System.arraycopy (enc, 1, tmp, 0, tmp.length);
+ System.arraycopy(enc, 1, tmp, 0, tmp.length);
enc = tmp;
}
pos = 0;
@@ -256,56 +251,54 @@ public class RSACipherImpl extends CipherSpi
}
}
- protected int engineDoFinal (byte[] out, int offset)
- throws ShortBufferException, IllegalBlockSizeException, BadPaddingException
+ protected int engineDoFinal(byte[] out, int offset)
+ throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException
{
- byte[] result = engineDoFinal (EMPTY, 0, 0);
+ byte[] result = engineDoFinal(EMPTY, 0, 0);
if (out.length - offset < result.length)
- throw new ShortBufferException ("need " + result.length + ", have "
- + (out.length - offset));
- System.arraycopy (result, 0, out, offset, result.length);
+ throw new ShortBufferException("need " + result.length + ", have "
+ + (out.length - offset));
+ System.arraycopy(result, 0, out, offset, result.length);
return result.length;
}
- protected int engineDoFinal (final byte[] input, final int offset, final int length,
- final byte[] output, final int outputOffset)
- throws ShortBufferException, IllegalBlockSizeException, BadPaddingException
+ protected int engineDoFinal(final byte[] input, final int offset,
+ final int length, final byte[] output,
+ final int outputOffset)
+ throws ShortBufferException, IllegalBlockSizeException,
+ BadPaddingException
{
- byte[] result = engineDoFinal (input, offset, length);
+ byte[] result = engineDoFinal(input, offset, length);
if (output.length - outputOffset < result.length)
- throw new ShortBufferException ("need " + result.length + ", have "
- + (output.length - outputOffset));
- System.arraycopy (result, 0, output, outputOffset, result.length);
+ throw new ShortBufferException("need " + result.length + ", have "
+ + (output.length - outputOffset));
+ System.arraycopy(result, 0, output, outputOffset, result.length);
return result.length;
}
/**
* Decrypts the ciphertext, employing RSA blinding if possible.
*/
- private byte[] rsaDecrypt (BigInteger enc)
+ private byte[] rsaDecrypt(BigInteger enc)
{
if (random == null)
- random = new SecureRandom ();
- BigInteger n = decipherKey.getModulus ();
+ random = new SecureRandom();
+ BigInteger n = decipherKey.getModulus();
BigInteger r = null;
BigInteger pubExp = null;
if (blindingKey != null)
- pubExp = blindingKey.getPublicExponent ();
+ pubExp = blindingKey.getPublicExponent();
if (pubExp != null && (decipherKey instanceof RSAPrivateCrtKey))
- pubExp = ((RSAPrivateCrtKey) decipherKey).getPublicExponent ();
+ pubExp = ((RSAPrivateCrtKey) decipherKey).getPublicExponent();
if (pubExp != null)
{
- r = new BigInteger (n.bitLength () - 1, random);
- enc = r.modPow (pubExp, n).multiply (enc).mod (n);
+ r = new BigInteger(n.bitLength() - 1, random);
+ enc = r.modPow(pubExp, n).multiply(enc).mod(n);
}
-
- BigInteger dec = enc.modPow (decipherKey.getPrivateExponent (), n);
-
+ BigInteger dec = enc.modPow(decipherKey.getPrivateExponent(), n);
if (pubExp != null)
- {
- dec = dec.multiply (r.modInverse (n)).mod (n);
- }
-
- return dec.toByteArray ();
+ dec = dec.multiply(r.modInverse(n)).mod(n);
+ return dec.toByteArray();
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/assembly/Assembly.java b/libjava/classpath/gnu/javax/crypto/assembly/Assembly.java
index 2d5bba3..4977067 100644
--- a/libjava/classpath/gnu/javax/crypto/assembly/Assembly.java
+++ b/libjava/classpath/gnu/javax/crypto/assembly/Assembly.java
@@ -41,23 +41,19 @@ package gnu.javax.crypto.assembly;
import java.util.Map;
/**
- * An Once constructed, and correctly initialised, the bulk of the methods
- * available on the
+ * Once constructed, and correctly initialised, the bulk of the methods
+ * available on the A Cascade Cipher is the concatenation of two or more block ciphers
+ * A Cascade Cipher is the concatenation of two or more block ciphers
* each with independent keys. Plaintext is input to the first stage; the output
- * of stage In the simplest case, all stages in a
+ * In the simplest case, all stages in a The term "block ciphers" used above refers to implementations of
- * {@link gnu.crypto.mode.IMode}, including the {@link gnu.crypto.mode.ECB}
- * mode which basically exposes a symmetric-key block cipher algorithm as a
- * Mode of Operations. References:
+ * The term "block ciphers" used above refers to implementations of
+ * {@link gnu.javax.crypto.mode.IMode}, including the
+ * {@link gnu.javax.crypto.mode.ECB} mode which basically exposes a
+ * symmetric-key block cipher algorithm as a Mode of Operations.
+ *
+ * References:
* A Cascade Stage in a Cascade Cipher. A {@link Transformer} Adapter allowing inclusion of a DEFLATE compression
+ * A {@link Transformer} Adapter allowing inclusion of a DEFLATE compression
* algorithm in an {@link Assembly} chain. The {@link Direction#FORWARD}
* transformation is a compression (deflate) of input data, while the
- * {@link Direction#REVERSED} one is a decompression (inflate) that restores
- * the original data. This {@link Transformer} uses a {@link Deflater} instance to carry on the
- * compression, and an {@link Inflater} to do the decompression. When using such a {@link Transformer}, in an {@link Assembly}, there must
+ * {@link Direction#REVERSED} one is a decompression (inflate) that restores the
+ * original data.
+ *
+ * This {@link Transformer} uses a {@link Deflater} instance to carry on the
+ * compression, and an {@link Inflater} to do the decompression.
+ *
+ * When using such a {@link Transformer}, in an {@link Assembly}, there must
* be at least one element behind this instance in the constructed chain;
- * otherwise, a {@link TransformerException} is thrown at initialisation time. An enumeration type for wiring {@link Stage} instances into {@link
- * Cascade} Cipher chains, as well as for operating a {@link Cascade} in a
- * given direction. The possible values for this type are two:
+ * The possible values for this type are two:
* An {@link IMode} {@link Stage} in a {@link Cascade} Cipher chain. Such a stage wraps an implementation of a Block Cipher Mode of Operation
+ * An {@link IMode} {@link Stage} in a {@link Cascade} Cipher chain.
+ *
+ * Such a stage wraps an implementation of a Block Cipher Mode of Operation
* ({@link IMode}) to allow inclusion of such an instance in a cascade of block
- * ciphers. An enumeration type for specifying the operation type of a
- * {@link Transformer}. The possible values for this type are two:
+ * The possible values for this type are two:
* An Adapter to use any {@link IPad} as a {@link Transformer} in an
- * {@link Assembly}. When using such a {@link Transformer}, in an {@link Assembly}, there must
+ * An Adapter to use any {@link IPad} as a {@link Transformer} in an
+ * {@link Assembly}.
+ *
+ * When using such a {@link Transformer}, in an {@link Assembly}, there must
* be at least one element behind this instance in the constructed chain;
- * otherwise, a {@link TransformerException} is thrown at initialisation time. A Stage in a Cascade Cipher. Each stage may be either an implementation of a Block Cipher Mode of
- * Operation ({@link IMode}) or another Cascade Cipher ({@link Cascade}). Each
- * stage has also a natural operational direction when constructed for
- * inclusion within a {@link Cascade}. This natural direction dictates
- * how data flows from one stage into another when stages are chained together
- * in a cascade. One can think of a stage and its natural direction as the
- * specification of how to wire the stage into the chain. The following diagrams
- * may help understand the paradigme. The first shows two stages chained each
- * with a {@link Direction#FORWARD} direction.
+ * Each stage may be either an implementation of a Block Cipher Mode of
+ * Operation ({@link IMode}) or another Cascade Cipher ({@link Cascade}).
+ * Each stage has also a natural operational direction when constructed
+ * for inclusion within a {@link Cascade}. This natural direction
+ * dictates how data flows from one stage into another when stages are chained
+ * together in a cascade. One can think of a stage and its natural direction as
+ * the specification of how to wire the stage into the chain. The following
+ * diagrams may help understand the paradigme. The first shows two stages
+ * chained each with a {@link Direction#FORWARD} direction.
+ *
* The second diagram shows two stages, one in a {@link Direction#FORWARD}
+ *
+ *
+ * The second diagram shows two stages, one in a {@link Direction#FORWARD}
* direction, while the other is wired in a {@link Direction#REVERSED}
- * direction. A A
+ *
+ * A To allow wiring
+ * To allow wiring Anubis is a 128-bit block cipher that accepts a variable-length key. The
+ * Anubis is a 128-bit block cipher that accepts a variable-length key. The
* cipher is a uniform substitution-permutation network whose inverse only
* differs from the forward operation in the key schedule. The design of both
* the round transformation and the key schedule is based upon the Wide Trail
- * strategy and permits a wide variety of implementation trade-offs. References:
+ * References:
* Expands a user-supplied key material into a session key for a
- * designated block size. A basic abstract class to facilitate implementing symmetric key block
- * ciphers. Trivial constructor for use by concrete subclasses. References:
+ * References:
* An implmenetation of the In this RFC, Carlisle Adams (the CA in CAST, ST stands for
- * Stafford Tavares) describes CAST5 as:
+ * In this RFC, Carlisle Adams (the CA in CAST, ST stands for
+ * Stafford Tavares) describes CAST5 as:
*
+ * The
+ * The References:
+ * References:
* The full encryption algorithm is given in the following four steps. Decryption is identical to the encryption algorithm given above, except
+ *
+ * Decryption is identical to the encryption algorithm given above, except
* that the rounds (and therefore the subkey pairs) are used in reverse order
- * to compute (L0,R0) from (R16,L16). Looking at the iterations/rounds in pairs we have:
+ * Looking at the iterations/rounds in pairs we have:
* A Factory to instantiate symmetric block cipher instances. Returns an instance of a block cipher given its name. Returns a {@link Set} of symmetric key block cipher implementation
- * names supported by this Factory. The Data Encryption Standard. DES is a 64-bit block cipher with a 56-bit
+ * The Data Encryption Standard. DES is a 64-bit block cipher with a 56-bit
* key, developed by IBM in the 1970's for the standardization process begun by
- * the National Bureau of Standards (now NIST). New applications should not use DES except for compatibility. This version is based upon the description and sample implementation in
- * [1]. References:
+ * New applications should not use DES except for compatibility.
+ *
+ * This version is based upon the description and sample implementation in
+ * [1].
+ *
+ * References:
* Adjust the parity for a raw key array. This essentially means that each
+ * Adjust the parity for a raw key array. This essentially means that each
* byte in the array will have an odd number of '1' bits (the last bit in
- * each byte is unused. Test if a byte array, which must be at least 8 bytes long, is parity
- * adjusted. Test if a key is a weak key. Test if a key is a semi-weak key. Test if the designated byte array represents a possibly weak key. The core DES function. This is used for both encryption and decryption,
- * the only difference being the key. The basic visible methods of any symmetric key block cipher. A symmetric key block cipher is a function that maps n-bit plaintext
- * blocks to n-bit ciphertext blocks; n being the cipher's block size.
- * This encryption function is parameterised by a k-bit key, and is invertible.
- * Its inverse is the decryption function. Possible initialisation values for an instance of this type are:
+ * A symmetric key block cipher is a function that maps n-bit plaintext blocks
+ * to n-bit ciphertext blocks; n being the cipher's block size. This
+ * encryption function is parameterised by a k-bit key, and is invertible. Its
+ * inverse is the decryption function.
+ *
+ * Possible initialisation values for an instance of this type are:
* IMPLEMENTATION NOTE: Although all the concrete classes in this
+ *
+ * IMPLEMENTATION NOTE: Although all the concrete classes in this
* package implement the {@link Cloneable} interface, it is important to note
* here that such an operation DOES NOT clone any session key material
* that may have been used in initialising the source cipher (the instance to be
* cloned). Instead a clone of an already initialised cipher is another instance
* that operates with the same block size but without any knowledge of
- * neither key material nor key size. Property name of the block size in which to operate a block cipher.
- * The value associated with this property name is taken to be an
- * {@link Integer}. Property name of the user-supplied key material. The value associated
- * to this property name is taken to be a byte array. Returns the canonical name of this instance. Returns the default value, in bytes, of the algorithm's block size. Returns the default value, in bytes, of the algorithm's key size. Returns an {@link Iterator} over the supported block sizes. Each
- * element returned by this object is an {@link Integer}. Returns an {@link Iterator} over the supported key sizes. Each element
- * returned by this object is an {@link Integer}. Returns a clone of this instance. Initialises the algorithm with designated attributes. Permissible names
- * and values are described in the class documentation above. Returns the currently set block size for this instance. Resets the algorithm instance for re-initialisation and use with other
- * characteristics. This method always succeeds. Encrypts exactly one block of plaintext. Decrypts exactly one block of ciphertext. A correctness test that consists of basic symmetric encryption /
+ * A correctness test that consists of basic symmetric encryption /
* decryption test(s) for all supported block and key sizes, as well as one
- * (1) variable key Known Answer Test (KAT). Package-private interface exposing mandatory methods to be implemented by
- * concrete {@link gnu.crypto.cipher.BaseCipher} sub-classes. Returns an {@link java.util.Iterator} over the supported block sizes.
- * Each element returned by this object is a {@link java.lang.Integer}. Returns an {@link java.util.Iterator} over the supported key sizes.
- * Each element returned by this object is a {@link java.lang.Integer}. Expands a user-supplied key material into a session key for a
- * designated block size. Encrypts exactly one block of plaintext. Decrypts exactly one block of ciphertext. A correctness test that consists of basic symmetric encryption /
+ * A correctness test that consists of basic symmetric encryption /
* decryption test(s) for all supported block and key sizes, as well as one
- * (1) variable key Known Answer Test (KAT). Khazad is a 64-bit (legacy-level) block cipher that accepts a 128-bit key.
+ * Khazad is a 64-bit (legacy-level) block cipher that accepts a 128-bit key.
* The cipher is a uniform substitution-permutation network whose inverse only
* differs from the forward operation in the key schedule. The overall cipher
* design follows the Wide Trail strategy, favours component reuse, and permits
- * a wide variety of implementation trade-offs. References:
+ * References:
* Expands a user-supplied key material into a session key for a
- * designated block size. The implementation of a Null block cipher. This cipher does not alter its input at all, claims to process block sizes
+ * The implementation of a Null block cipher.
+ *
+ * This cipher does not alter its input at all, claims to process block sizes
* 128-, 192- and 256-bit long, and key sizes from 64- to 512-bit in 8-bit
- * increments. Rijndael --pronounced Reindaal-- is the AES. It is a variable block-size
+ * Rijndael --pronounced Reindaal-- is the AES. It is a variable block-size
* (128-, 192- and 256-bit), variable key-size (128-, 192- and 256-bit)
- * symmetric key block cipher. References:
+ * References:
* Returns the number of rounds for a given Rijndael's key and block
- * sizes. Serpent is a 32-round substitution-permutation network block cipher,
+ * Serpent is a 32-round substitution-permutation network block cipher,
* operating on 128-bit blocks and accepting keys of 128, 192, and 256 bits in
* length. At each round the plaintext is XORed with a 128 bit portion of the
* session key -- a 4224 bit key computed from the input key -- then one of
* eight S-boxes are applied, and finally a simple linear transformation is
* done. Decryption does the exact same thing in reverse order, and using the
- * eight inverses of the S-boxes. Serpent was designed by Ross Anderson, Eli Biham, and Lars Knudsen as a
- * proposed cipher for the Advanced Encryption Standard. Serpent can be sped up greatly by replacing S-box substitution with a
- * sequence of binary operations, and the optimal implementation depends
- * upon finding the fastest sequence of binary operations that reproduce this
- * substitution. This implementation uses the S-boxes discovered by
- * Dag Arne Osvik, which are
- * optimized for the Pentium family of processors. References:
+ * Serpent was designed by Ross Anderson, Eli Biham, and Lars Knudsen as a
+ * proposed cipher for the Advanced Encryption Standard.
+ *
+ * Serpent can be sped up greatly by replacing S-box substitution with a
+ * sequence of binary operations, and the optimal implementation depends upon
+ * finding the fastest sequence of binary operations that reproduce this
+ * substitution. This implementation uses the S-boxes discovered by Dag Arne Osvik, which are optimized
+ * for the Pentium family of processors.
+ *
+ * References:
* Square is a 128-bit key, 128-bit block cipher algorithm developed by Joan
- * Daemen, Lars Knudsen and Vincent Rijmen. References:
+ * References:
* Applies the Theta function to an input in in order to produce in
- * out an internal session sub-key. Both in and out are arrays of four ints. Pseudo-code is:
+ * Both in and out are arrays of four ints.
+ *
+ * Pseudo-code is:
* Left rotate a 32-bit chunk. Right rotate a 32-bit chunk. Returns the product of two binary numbers a and b, using the generator
- * ROOT as the modulus: p = (a * b) mod ROOT. ROOT Generates a suitable
- * Galois Field in GF(2**8). For best performance call it with abs(b) < abs(a).
+ * For best performance call it with abs(b) < abs(a).
+ *
* @param a operand for multiply.
* @param b operand for multiply.
* @return the result of (a * b) % ROOT.
@@ -369,35 +307,22 @@ public final class Square extends BaseCipher
private static final int mul(int a, int b)
{
if (a == 0)
- {
- return 0;
- }
-
+ return 0;
a &= 0xFF;
b &= 0xFF;
int result = 0;
while (b != 0)
{
if ((b & 0x01) != 0)
- {
- result ^= a;
- }
-
+ result ^= a;
b >>>= 1;
a <<= 1;
if (a > 0xFF)
- {
- a ^= ROOT;
- }
+ a ^= ROOT;
}
return result & 0xFF;
}
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.lang.Cloneable interface implementation ----------------------------
-
public Object clone()
{
Square result = new Square();
@@ -406,12 +331,10 @@ public final class Square extends BaseCipher
return result;
}
- // IBlockCipherSpi interface implementation --------------------------------
-
public Iterator blockSizes()
{
ArrayList al = new ArrayList();
- al.add(new Integer(DEFAULT_BLOCK_SIZE));
+ al.add(Integer.valueOf(DEFAULT_BLOCK_SIZE));
return Collections.unmodifiableList(al).iterator();
}
@@ -419,7 +342,7 @@ public final class Square extends BaseCipher
public Iterator keySizes()
{
ArrayList al = new ArrayList();
- al.add(new Integer(DEFAULT_KEY_SIZE));
+ al.add(Integer.valueOf(DEFAULT_KEY_SIZE));
return Collections.unmodifiableList(al).iterator();
}
@@ -427,36 +350,35 @@ public final class Square extends BaseCipher
public Object makeKey(byte[] uk, int bs) throws InvalidKeyException
{
if (bs != DEFAULT_BLOCK_SIZE)
- {
- throw new IllegalArgumentException();
- }
+ throw new IllegalArgumentException();
if (uk == null)
- {
- throw new InvalidKeyException("Empty key");
- }
+ throw new InvalidKeyException("Empty key");
if (uk.length != DEFAULT_KEY_SIZE)
- {
- throw new InvalidKeyException("Key is not 128-bit.");
- }
-
+ throw new InvalidKeyException("Key is not 128-bit.");
int[][] Ke = new int[ROUNDS + 1][4];
int[][] Kd = new int[ROUNDS + 1][4];
int[][] tK = new int[ROUNDS + 1][4];
int i = 0;
-
- Ke[0][0] = (uk[i++] & 0xFF) << 24 | (uk[i++] & 0xFF) << 16
- | (uk[i++] & 0xFF) << 8 | (uk[i++] & 0xFF);
+ Ke[0][0] = (uk[i++] & 0xFF) << 24
+ | (uk[i++] & 0xFF) << 16
+ | (uk[i++] & 0xFF) << 8
+ | (uk[i++] & 0xFF);
tK[0][0] = Ke[0][0];
- Ke[0][1] = (uk[i++] & 0xFF) << 24 | (uk[i++] & 0xFF) << 16
- | (uk[i++] & 0xFF) << 8 | (uk[i++] & 0xFF);
+ Ke[0][1] = (uk[i++] & 0xFF) << 24
+ | (uk[i++] & 0xFF) << 16
+ | (uk[i++] & 0xFF) << 8
+ | (uk[i++] & 0xFF);
tK[0][1] = Ke[0][1];
- Ke[0][2] = (uk[i++] & 0xFF) << 24 | (uk[i++] & 0xFF) << 16
- | (uk[i++] & 0xFF) << 8 | (uk[i++] & 0xFF);
+ Ke[0][2] = (uk[i++] & 0xFF) << 24
+ | (uk[i++] & 0xFF) << 16
+ | (uk[i++] & 0xFF) << 8
+ | (uk[i++] & 0xFF);
tK[0][2] = Ke[0][2];
- Ke[0][3] = (uk[i++] & 0xFF) << 24 | (uk[i++] & 0xFF) << 16
- | (uk[i++] & 0xFF) << 8 | (uk[i] & 0xFF);
+ Ke[0][3] = (uk[i++] & 0xFF) << 24
+ | (uk[i++] & 0xFF) << 16
+ | (uk[i++] & 0xFF) << 8
+ | (uk[i ] & 0xFF);
tK[0][3] = Ke[0][3];
-
int j;
for (i = 1, j = 0; i < ROUNDS + 1; i++, j++)
{
@@ -464,41 +386,28 @@ public final class Square extends BaseCipher
tK[i][1] = tK[j][1] ^ tK[i][0];
tK[i][2] = tK[j][2] ^ tK[i][1];
tK[i][3] = tK[j][3] ^ tK[i][2];
-
System.arraycopy(tK[i], 0, Ke[i], 0, 4);
-
transform(Ke[j], Ke[j]);
}
-
for (i = 0; i < ROUNDS; i++)
- {
- System.arraycopy(tK[ROUNDS - i], 0, Kd[i], 0, 4);
- }
-
+ System.arraycopy(tK[ROUNDS - i], 0, Kd[i], 0, 4);
transform(tK[0], Kd[ROUNDS]);
-
return new Object[] { Ke, Kd };
}
public void encrypt(byte[] in, int i, byte[] out, int j, Object k, int bs)
{
if (bs != DEFAULT_BLOCK_SIZE)
- {
- throw new IllegalArgumentException();
- }
-
- int[][] K = (int[][]) ((Object[]) k)[0];
+ throw new IllegalArgumentException();
+ int[][] K = (int[][])((Object[]) k)[0];
square(in, i, out, j, K, Te, Se);
}
public void decrypt(byte[] in, int i, byte[] out, int j, Object k, int bs)
{
if (bs != DEFAULT_BLOCK_SIZE)
- {
- throw new IllegalArgumentException();
- }
-
- int[][] K = (int[][]) ((Object[]) k)[1];
+ throw new IllegalArgumentException();
+ int[][] K = (int[][])((Object[]) k)[1];
square(in, i, out, j, K, Td, Sd);
}
@@ -508,9 +417,7 @@ public final class Square extends BaseCipher
{
boolean result = super.selfTest(); // do symmetry tests
if (result)
- {
- result = testKat(KAT_KEY, KAT_CT);
- }
+ result = testKat(KAT_KEY, KAT_CT);
valid = Boolean.valueOf(result);
}
return valid.booleanValue();
diff --git a/libjava/classpath/gnu/javax/crypto/cipher/TripleDES.java b/libjava/classpath/gnu/javax/crypto/cipher/TripleDES.java
index 9b44c9c..1e98bfc 100644
--- a/libjava/classpath/gnu/javax/crypto/cipher/TripleDES.java
+++ b/libjava/classpath/gnu/javax/crypto/cipher/TripleDES.java
@@ -40,54 +40,50 @@ package gnu.javax.crypto.cipher;
import gnu.java.security.Registry;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.security.InvalidKeyException;
/**
- * Triple-DES, 3DES, or DESede is a combined cipher that uses
- * three iterations of the Data Encryption Standard cipher to improve
- * the security (at the cost of speed) of plain DES.
- *
- * Triple-DES runs the DES algorithm three times with three
- * independent 56 bit keys. To encrypt: And to decrypt: (The "ede" comes from the encryption operation, which runs
- * Encrypt-Decrypt-Encrypt) References:
+ * Triple-DES runs the DES algorithm three times with one, two or three
+ * independent 56-bit (DES) keys. When used with one DES key, the cipher behaves
+ * exactly like a (slower) DES.
+ *
+ * To encrypt:
+ *
+ * And to decrypt:
+ *
+ * (The "ede" comes from the encryption operation, which runs
+ * Encrypt-Decrypt-Encrypt)
+ *
+ * References:
* Twofish is a balanced 128-bit Feistel cipher, consisting of 16 rounds. In
+ * Twofish is a balanced 128-bit Feistel cipher, consisting of 16 rounds. In
* each round, a 64-bit S-box value is computed from 64 bits of the block, and
* this value is xored into the other half of the block. The two half-blocks are
* then exchanged, and the next round begins. Before the first round, all input
* bits are xored with key-dependent "whitening" subkeys, and after the final
* round the output bits are xored with other key-dependent whitening subkeys;
- * these subkeys are not used anywhere else in the algorithm. Twofish is designed by Bruce Schneier, Doug Whiting, John Kelsey, Chris
- * Hall, David Wagner and Niels Ferguson. References:
+ * Twofish is designed by Bruce Schneier, Doug Whiting, John Kelsey, Chris
+ * Hall, David Wagner and Niels Ferguson.
+ *
+ * References:
* Expands a user-supplied key material into a session key for a designated
- * block size. Checked exception thrown to indicate that a weak key has been generated
- * and or specified instead of a valid non-weak value. The GNU Crypto implementation of the Java Cryptographic Extension (JCE)
- * Provider. The GNU Crypto
- * Provider. Returns a {@link Set} of names of symmetric key block cipher algorithms
- * available from this {@link Provider}. Returns a {@link Set} of names of MAC algorithms available from
- * this {@link Provider}. Returns a {@link Set} of names of SASL Client mechanisms available from
- * this {@link Provider}. Returns a {@link Set} of names of SASL Server mechanisms available from
- * this {@link Provider}.
+ * In wrapping, the number of 8-byte output blocks is ALWAYS one block longer
+ * than the input.
+ *
+ * @param inputLength the size of the plain text.
+ * @return the size in bytes of
+ * In unwrapping, the number of 8-byte output blocks is ALWAYS one block
+ * shorter than the input.
+ *
+ * @param inputLength the size of the cipher text.
+ * @return the size in bytes of The implementation of a generic {@link Cipher} Adapter class to
- * wrap GNU Crypto cipher instances. This class defines the Service Provider Interface (SPI) for
+ * The implementation of a generic {@link Cipher} Adapter class to wrap
+ * GNU cipher instances.
+ *
+ * This class defines the Service Provider Interface (SPI) for
* the {@link Cipher} class, which provides the functionality of symmetric-key
- * block ciphers, such as the AES.
- *
- * This base class defines all of the abstract methods in {@link CipherSpi},
+ * block ciphers, such as the AES.
+ *
+ * This base class defines all of the abstract methods in {@link CipherSpi},
* but does not define the (non-abstract) key wrapping functions that extended
* the base cipher SPI, and these methods thus immediately throw an
* {@link UnsupportedOperationException}. If a cipher implementation provides
* this functionality, or if it in fact accepts parameters other than the key
* and the initialization vector, the subclass should override those methods.
* Otherwise a subclass need only call the {@link #CipherAdapter(String)}
- * constructor with the name of the cipher. Protected constructor to be called by subclasses. The cipher name
- * argument should be the appropriate one listed in {@link gnu.crypto.Registry}.
- * The basic cipher instance is created, along with an instance of the
- * {@link gnu.crypto.mode.ECB} mode and no padding. Creates a new cipher adapter with the default block size.
+ * This default implementation ALWAYS returns the smallest multiple of the
+ *
+ * This default implementation ALWAYS returns the smallest multiple of the
+ * . The implementation of the HMAC-SHA-256 Service Provider Interface
- * (SPI) adapter. The implementation of the HMAC-SHA-384 Service Provider Interface
- * (SPI) adapter. The implementation of the HMAC-SHA-512 Service Provider Interface
- * (SPI) adapter. The implementation of a generic {@link javax.crypto.Mac} adapter class
- * to wrap GNU Crypto MAC instances. This class defines the Service Provider Interface (SPI) for
+ * The implementation of a generic {@link javax.crypto.Mac} adapter class to
+ * wrap GNU MAC instances.
+ *
+ * This class defines the Service Provider Interface (SPI) for
* the {@link javax.crypto.Mac} class, which provides the functionality of a
* message authentication code algorithm, such as the Hashed Message
- * Authentication Code (HMAC) algorithms. Creates a new Mac instance for the given name. For GNU Crypto block ciphers we will define these parameters as
- *
- *
+ * For GNU block ciphers we will define these parameters as
+ *
+ * The implementation of the continuously-seeded SecureRandom Service
+ * Provider Interface (SPI) adapter.
*/
-public class CSPRNGSpi extends SecureRandomSpi
+public class CSPRNGSpi
+ extends SecureRandomSpi
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private final IRandom adaptee;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public CSPRNGSpi() throws ClassNotFoundException, MalformedURLException,
NumberFormatException
{
@@ -69,20 +62,13 @@ public class CSPRNGSpi extends SecureRandomSpi
adaptee = CSPRNG.getSystemInstance();
}
- // Instance methods
- // -------------------------------------------------------------------------
-
protected byte[] engineGenerateSeed(final int count)
{
if (count < 0)
- {
- throw new IllegalArgumentException("count must be nonnegative");
- }
+ throw new IllegalArgumentException("count must be nonnegative");
byte[] buf = new byte[count];
if (count == 0)
- {
- return buf;
- }
+ return buf;
engineNextBytes(buf);
return buf;
}
@@ -90,9 +76,7 @@ public class CSPRNGSpi extends SecureRandomSpi
protected void engineNextBytes(final byte[] buffer)
{
if (buffer == null)
- {
- throw new NullPointerException();
- }
+ throw new NullPointerException();
try
{
adaptee.nextBytes(buffer, 0, buffer.length);
@@ -106,9 +90,7 @@ public class CSPRNGSpi extends SecureRandomSpi
protected void engineSetSeed(final byte[] seed)
{
if (seed == null)
- {
- throw new NullPointerException();
- }
+ throw new NullPointerException();
adaptee.addRandomBytes(seed, 0, seed.length);
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/prng/FortunaImpl.java b/libjava/classpath/gnu/javax/crypto/jce/prng/FortunaImpl.java
index 7006bbb..8e3782e 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/prng/FortunaImpl.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/prng/FortunaImpl.java
@@ -40,24 +40,26 @@ package gnu.javax.crypto.jce.prng;
import gnu.java.security.prng.LimitReachedException;
import gnu.javax.crypto.prng.Fortuna;
+
import java.security.SecureRandomSpi;
import java.util.Collections;
-public final class FortunaImpl extends SecureRandomSpi
+public final class FortunaImpl
+ extends SecureRandomSpi
{
private final Fortuna adaptee;
- public FortunaImpl ()
+ public FortunaImpl()
{
- adaptee = new Fortuna ();
- adaptee.init (Collections.singletonMap (Fortuna.SEED, new byte[0]));
+ adaptee = new Fortuna();
+ adaptee.init(Collections.singletonMap(Fortuna.SEED, new byte[0]));
}
-
- protected void engineSetSeed (byte[] seed)
+
+ protected void engineSetSeed(byte[] seed)
{
synchronized (adaptee)
{
- adaptee.addRandomBytes (seed);
+ adaptee.addRandomBytes(seed);
}
}
@@ -67,19 +69,19 @@ public final class FortunaImpl extends SecureRandomSpi
{
try
{
- adaptee.nextBytes (buffer);
+ adaptee.nextBytes(buffer);
}
catch (LimitReachedException shouldNotHappen)
{
- throw new Error (shouldNotHappen);
+ throw new Error(shouldNotHappen);
}
}
}
- protected byte[] engineGenerateSeed (int numbytes)
+ protected byte[] engineGenerateSeed(int numbytes)
{
byte[] seed = new byte[numbytes];
- engineNextBytes (seed);
+ engineNextBytes(seed);
return seed;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/prng/ICMRandomSpi.java b/libjava/classpath/gnu/javax/crypto/jce/prng/ICMRandomSpi.java
index d04b782..9855f95 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/prng/ICMRandomSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/prng/ICMRandomSpi.java
@@ -38,44 +38,27 @@ exception statement from your version. */
package gnu.javax.crypto.jce.prng;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
+import gnu.java.security.prng.LimitReachedException;
import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.prng.ICMGenerator;
-import gnu.java.security.prng.LimitReachedException;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.SecureRandomSpi;
import java.util.HashMap;
import java.util.Random;
+import java.util.logging.Logger;
/**
- * An Adapter class around {@link ICMGenerator} to allow using this
- * algorithm as a JCE {@link java.security.SecureRandom}. An Adapter class around {@link UMacGenerator} to allow using this
- * algorithm as a JCE {@link java.security.SecureRandom}. This class is little more than a container for the key stream, tag
- * length, and prefix parameters for the TMMH algorithm.
+ * {@link gnu.javax.crypto.mac.TMMH16}.
+ *
+ * This class is little more than a container for the key stream, tag length,
+ * and prefix parameters for the TMMH algorithm.
*/
-public class TMMHParameterSpec implements AlgorithmParameterSpec
+public class TMMHParameterSpec
+ implements AlgorithmParameterSpec
{
-
- // Constants and variables.
- // -----------------------------------------------------------------------
-
/** The keystream. */
protected IRandom keystream;
-
/** The tag length. */
protected Integer tagLength;
-
/** The prefix. */
protected byte[] prefix;
- // Constructors.
- // -----------------------------------------------------------------------
-
/**
* Create a new parameter specification.
- *
+ *
* @param keystream The (PRNG) key stream.
* @param tagLength The tag length.
- * @param prefix The prefix.
+ * @param prefix The prefix.
*/
public TMMHParameterSpec(IRandom keystream, Integer tagLength, byte[] prefix)
{
@@ -84,7 +76,7 @@ public class TMMHParameterSpec implements AlgorithmParameterSpec
/**
* Create a new parameter specification with no prefix.
- *
+ *
* @param keystream The (PRNG) key stream.
* @param tagLength The tag length.
*/
@@ -93,12 +85,9 @@ public class TMMHParameterSpec implements AlgorithmParameterSpec
this(keystream, tagLength, null);
}
- // Instance methods.
- // -----------------------------------------------------------------------
-
/**
* Return the key stream this specification was initialized with.
- *
+ *
* @return The key stream.
*/
public IRandom getKeystream()
@@ -108,7 +97,7 @@ public class TMMHParameterSpec implements AlgorithmParameterSpec
/**
* Return the tag length this specification was initialized with.
- *
+ *
* @return The tag length.
*/
public Integer getTagLength()
@@ -117,13 +106,12 @@ public class TMMHParameterSpec implements AlgorithmParameterSpec
}
/**
- * Return the prefix, or A base abstract class to facilitate implementations of concrete key
- * agreement protocol handlers. The visible methods of an key agreement protocol participating party. Returns the canonical name of the key agreement protocol. Sets up the instance to operate with specific attributes. Processes an incoming message at one end, generating a message that
- * will be processed by the other party(ies). Returns Returns the byte array containing the shared secret as generated by
- * this party. An implementation of an incoming message for use with key agreement
- * protocols. Constructs an incoming message given the message's encoded form,
- * including its header bytes. Returns an instance of a message given its encoded contents, excluding
- * the message's header bytes. Calls the method with the same name and three arguments as:
+ * Returns an instance of a message given its encoded contents, excluding the
+ * message's header bytes.
+ *
+ * Calls the method with the same name and three arguments as:
* Returns an instance of a message given its encoded contents, excluding
- * the message's header bytes. Converts two octets into the number that they represent. Converts four octets into the number that they represent. Decodes an MPI from the current message's contents. Constructs a new instance of Constructs a new instance of Constructs a new instance of Returns the cause of this throwable or Prints this exception's stack trace to Prints this exception's stack trace to a print stream. If this
- * exception has a root exception; the stack trace of the root
- * exception is also printed to the print stream. Prints this exception's stack trace to a print writer. If this
- * exception has a root exception; the stack trace of the root
- * exception is also printed to the print writer. Returns the string representation of this exception. The string
- * representation contains this exception's class name, its detailed
- * messsage, and if it has a root exception, the string representation
- * of the root exception. This string representation is meant for debugging
- * and is not meant to be interpreted programmatically. A Factory class to generate key agreement protocol handlers. Returns an instance of a key agreeent protocol handler, for party
+ * Returns an instance of a key agreeent protocol handler, for party
* Returns an instance of a key agreeent protocol handler, for party
+ * Returns an instance of a key agreeent protocol handler, for party
* Returns a {@link Set} of key agreement protocol names supported by this
- * Factory. An implementation of outgoing messages for use with key agreement
- * protocols. Returns the encoded form of the current message including the 4-byte
- * length header. Returns the encoded form of the current message excluding the 4-byte
- * length header. Encodes an MPI into the message. Encodes a string into the message.
+ * IMPORTANT: with RI's {@link javax.crypto.spec.DHGenParameterSpec}
+ * and {@link javax.crypto.spec.DHParameterSpec} classes, we may end up with
+ * Diffie-Hellman keys that have a An object that implements the {@link IKeyPairCodec} operations for the
- * Raw format to use with Diffie-Hellman keypairs. Returns the encoded form of the designated Diffie-Hellman public key
- * according to the Raw format supported by this library. The Raw format for a DH public key, in this implementation, is
- * a byte sequence consisting of the following:
+ * The Raw format for a DH public key, in this implementation, is a
+ * byte sequence consisting of the following:
* Returns the encoded form of the designated Diffie-Hellman private key
- * according to the Raw format supported by this library. The Raw format for a DH private key, in this implementation, is
- * a byte sequence consisting of the following:
+ * The Raw format for a DH private key, in this implementation, is a
+ * byte sequence consisting of the following:
*
+ * IMPORTANT: with RI's {@link javax.crypto.spec.DHGenParameterSpec}
+ * and {@link javax.crypto.spec.DHParameterSpec} classes, we may end up with
+ * Diffie-Hellman keys that have a The basic version of the Diffie-Hellman key agreement is described in the
- * Handbook of Applied Cryptography [HAC] as follows: RFC-2631 describes a Static-Static Mode of operations with
- * Diffie-Hellman keypairs as follows:
+ * RFC-2631 describes a Static-Static Mode of operations with
+ * Diffie-Hellman keypairs as follows:
* Reference:
+ * Reference:
* This implementation is the receiver's part of the basic version of the
- * Diffie-Hellman key agreement exchange (B in [HAC]). This implementation is the sender's part of the basic version of the
- * Diffie-Hellman key agreement exchange (A in [HAC]). The ElGamal key agreement, also known as the half-certified Diffie-Hellman
+ * The ElGamal key agreement, also known as the half-certified Diffie-Hellman
* key agreement, is described in the Handbook of Applied Cryptography [HAC] as
- * follows: RFC-2631 describes an Ephemeral-Static Mode of operations with
- * Diffie-Hellman keypairs as follows:
+ * RFC-2631 describes an Ephemeral-Static Mode of operations with
+ * Diffie-Hellman keypairs as follows:
* Reference:
+ * Reference:
* This implementation is the receiver's part of the ElGamal key agreement
- * exchange (B in [HAC]). This implementation is the sender's part of the ElGamal key agreement
- * exchange (A in [HAC]). A base asbtract class for both public and private Diffie-Hellman keys. It
- * encapsulates the two DH numbers: According to the JDK, cryptographic Keys all have a format.
+ * A base asbtract class for both public and private Diffie-Hellman keys. It
+ * encapsulates the two DH numbers:
+ * According to the JDK, cryptographic Keys all have a format.
* The format used in this implementation is called Raw, and basically
* consists of the raw byte sequences of algorithm parameters. The exact order
- * of the byte sequences and the implementation details are given in each of
- * the relevant Reference:
+ * Reference:
* Returns An implementation of a Diffie-Hellman keypair generator. Reference:
+ * Reference:
* Fills the designated byte array with random data. An implementation of the Diffie-Hellman private key. Reference:
+ * Reference:
* A class method that takes the output of the Returns the encoded form of this private key according to the
- * designated format. An implementation of the Diffie-Hellman public key. Reference:
+ * Reference:
* A class method that takes the output of the Returns the encoded form of this public key according to the designated
- * format. An implementation of the Diffie-Hellman parameter generation as defined in
- * RFC-2631. Reference:
+ * Reference:
* Fills the designated byte array with random data. The implementation of the Host in the SRP-6 key agreement protocol. Reference:
+ * Reference:
* The Secure Remote Password (SRP) key agreement protocol, also known as
- * SRP-6, is designed by Thomas J. Wu (see references). The protocol, and its
- * elements are described as follows: Reference:
+ * Reference:
* A variation of the SRP-6 protocol as used in the SASL-SRP mechanism, for
- * the User (client side). In this alternative, the exchange goes as follows:
+ * In this alternative, the exchange goes as follows:
+ *
* All elements are computed the same way as in the standard version. Reference:
+ * All elements are computed the same way as in the standard version.
+ *
+ * Reference:
* A variation of the SRP-6 protocol as used in the SASL-SRP mechanism, for
- * the Host (server side). In this alternative, the exchange goes as follows:
+ * In this alternative, the exchange goes as follows:
+ *
* All elements are computed the same way as in the standard version. Reference:
+ * All elements are computed the same way as in the standard version.
+ *
+ * Reference:
* A variation of the SRP6 key agreement protocol, for the client-side as
- * proposed in
- * Using
+ * A variation of the SRP6 key agreement protocol, for the client-side as
+ * proposed in Using
* SRP for TLS Authentication. The only difference between it and the SASL
* variant is that the shared secret is the entity A variation of the SRP6 key agreement protocol, for the server-side as
- * proposed in
- * Using
+ * A variation of the SRP6 key agreement protocol, for the server-side as
+ * proposed in Using
* SRP for TLS Authentication. The only difference between it and the SASL
* variant is that the shared secret is the entity The implementation of the User in the SRP-6 protocol. Reference:
+ * Reference:
* Utilities for use with SRP-6 based methods and protocols. Reference:
+ * Reference:
* An abstract representation of a base SRP ephemeral key. This object encapsulates the two numbers:
+ * This object encapsulates the two numbers:
* Note that in SRP, all arithmetic is done modulo N. Reference:
+ * Note that in SRP, all arithmetic is done modulo N.
+ *
+ * Reference:
* Returns the standard algorithm name for this key. Returns the public shared modulus. Returns the generator. Returns Reference: An object that implements the {@link IKeyPairCodec} operations for the
- * Raw format to use with SRP keypairs. Reference:
+ * Reference:
* Returns the encoded form of the designated SRP public key according to
- * the Raw format supported by this library. The Raw format for an SRP public key, in this implementation, is
- * a byte sequence consisting of the following:
+ * The Raw format for an SRP public key, in this implementation, is a
+ * byte sequence consisting of the following:
* Returns the encoded form of the designated SRP private key according to
- * the Raw format supported by this library. The Raw format for an SRP private key, in this implementation,
- * is a byte sequence consisting of the following:
+ * The Raw format for an SRP private key, in this implementation, is a
+ * byte sequence consisting of the following:
* A representation of an SRP ephemeral private key. Reference:
+ * Reference:
* Public constructor for use from outside this package. Public constructor for use from outside this package. Default constructor. Assumes N and g are already validated. A class method that takes the output of the Returns the private exponent of the key as a {@link BigInteger}. Returns the user's verifier as a {@link BigInteger}. Returns the encoded form of this private key according to the
- * designated format. Returns A representation of an SRP ephemeral public key. Reference:
+ * Reference:
* Public constructor for use from outside this package. Default constructor. Assumes that N and g are already validated. A class method that takes the output of the Returns the public exponent of the key as a {@link BigInteger}. Returns the encoded form of this public key according to the designated
- * format. Returns An immutable class representing a trusted certificate entry. . The top-level interface to a keyring: a file that is used to
- * store and protect public and private cryptographic keys. A keyring is modelled as a mapping of one alias to one or
- * more entries (optionally of different types). See also the sub-interfaces {@link IPublicKeyring} and
- * {@link IPrivateKeyring} for special types of keyrings --the difference
- * being in the type of entries they contain.
+ * A keyring is modelled as a mapping of one alias to one or
+ * more entries (optionally of different types).
+ *
+ * See also the sub-interfaces {@link IPublicKeyring} and
+ * {@link IPrivateKeyring} for special types of keyrings --the
+ * difference being in the type of entries they contain.
*/
public interface IKeyring
{
-
/**
- * Property name for the source of data to load the keyring from. The
- * value mapped must be a {@link java.io.InputStream}. Property name for the data sink to store the keyring to. The value
- * mapped must be a {@link java.io.OutputStream}. Property name for the keyring's top-level password, used to
- * authenticate and/or transform the store itself. The mapped value must be a
- * char array. Loads a keyring into memory. What happens to the current contents of this keyring? are the new ones
- * merged with the current ones or do they simply replace them?
+ * What happens to the current contents of this keyring? are the new ones
+ * merged with the current ones or do they simply replace them?
+ *
* @param attributes The attributes that designate the source where the store
- * is to be loaded from. What happens
+ * is to be loaded from. What happens
* @throws IllegalArgumentException If the attributes are inappropriate.
* @throws IOException If the keyring file cannot be read.
* @throws SecurityException If the given password is incorrect, or if the
- * top-level authentication or decryption fails.
+ * top-level authentication or decryption fails.
*/
void load(Map attributes) throws IOException;
/**
- * Stores the contents of this keyring to persistent storage as specified
- * by the designated Resets this keyring, clearing all sensitive data. This method always
- * suceeds. Returns the number of entries in this keyring. Returns an {@link Enumeration} of all aliases (instances of
- * {@link String}) in this keyring. Returns a {@link List} of entries (instances of {@link Entry}) for the
+ * Returns a {@link List} of entries (instances of {@link Entry}) for the
* given Adds a designated {@link Entry} to this keyring. What happens if there is already an entry with the same alias?
+ * What happens if there is already an entry with the same alias?
+ *
* @param entry The entry to put in this keyring.
*/
void add(Entry entry);
/**
- * Removes an entry with the designated What happens if there are more than one?
+ * What happens if there are more than one?
+ *
* @param alias The alias of the entry to remove.
*/
void remove(String alias);
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/IPrivateKeyring.java b/libjava/classpath/gnu/javax/crypto/keyring/IPrivateKeyring.java
index 66bbd84..9e2ceab 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/IPrivateKeyring.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/IPrivateKeyring.java
@@ -44,41 +44,41 @@ import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
/**
- * An interface to private, or "personal", keyrings, which contain private
+ * An interface to private, or "personal", keyrings, which contain private
* credentials. The contract is that each such entry is known by a unique
- * alias. What about public keys? and certificate-path?
+ * What about public keys? and certificate-path?
*/
-public interface IPrivateKeyring extends IKeyring
+public interface IPrivateKeyring
+ extends IKeyring
{
-
/**
- * Tests if this keyring contains a private key entry with the given
- * Returns the private key with the given Adds a private key to this keyring. Checks if this keyring contains a public key with the given
- * Returns the public key with the given Sets a public key entry. Checks if this keyring contains a certificate path with the given
- * Returns the certificate path with the given Sets a certificate path entry. An interface for keyrings that contain trusted (by the owner) public
- * credentials (incl. certificates). Tests if this keyring contains a certificate entry with the specified
- * Returns a certificate that has the given Adds a certificate in this keyring, with the given What happens if there is already a certificate entry with this alias?
+ * What happens if there is already a certificate entry with this alias?
+ *
* @param alias The alias of this certificate entry.
* @param cert The certificate.
*/
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/MalformedKeyringException.java b/libjava/classpath/gnu/javax/crypto/keyring/MalformedKeyringException.java
index 44c9539..0dab3a7 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/MalformedKeyringException.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/MalformedKeyringException.java
@@ -40,12 +40,9 @@ package gnu.javax.crypto.keyring;
import java.io.IOException;
-public class MalformedKeyringException extends IOException
+public class MalformedKeyringException
+ extends IOException
{
-
- // Constructors.
- // ------------------------------------------------------------------------
-
public MalformedKeyringException()
{
super();
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java b/libjava/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java
index 7fed7c4..5206a5e 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/MaskableEnvelopeEntry.java
@@ -43,21 +43,15 @@ import java.util.List;
/**
* An envelope entry that can be "masked" -- placed in a state where the
- * envelope's contents cannot be accessed, due to the envelope not being
- * fully decoded, for example.
+ * envelope's contents cannot be accessed, due to the envelope not being fully
+ * decoded, for example.
*/
-public abstract class MaskableEnvelopeEntry extends EnvelopeEntry
+public abstract class MaskableEnvelopeEntry
+ extends EnvelopeEntry
{
-
- // Fields.
- // ------------------------------------------------------------------------
-
/** The masked state. */
protected boolean masked;
- // Constructors.
- // ------------------------------------------------------------------------
-
public MaskableEnvelopeEntry(int type, Properties properties)
{
super(type, properties);
@@ -68,12 +62,9 @@ public abstract class MaskableEnvelopeEntry extends EnvelopeEntry
super(type);
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
/**
* Sets the masked state to the specified value.
- *
+ *
* @param masked The new masked state.
*/
protected final void setMasked(boolean masked)
@@ -84,7 +75,7 @@ public abstract class MaskableEnvelopeEntry extends EnvelopeEntry
/**
* Gets the masked state of this object. Certain operations on this object
* will fail if it is masked.
- *
+ *
* @return The current masked state.
*/
public boolean isMasked()
@@ -95,54 +86,50 @@ public abstract class MaskableEnvelopeEntry extends EnvelopeEntry
public void add(Entry entry)
{
if (isMasked())
- {
- throw new IllegalStateException("masked envelope");
- }
+ throw new IllegalStateException("masked envelope");
super.add(entry);
}
public boolean containsEntry(Entry entry)
{
if (isMasked())
- {
- throw new IllegalStateException("masked envelope");
- }
+ throw new IllegalStateException("masked envelope");
return super.containsEntry(entry);
}
public List getEntries()
{
if (isMasked())
- {
- throw new IllegalStateException("masked envelope");
- }
+ throw new IllegalStateException("masked envelope");
return new ArrayList(entries);
}
public List get(String alias)
{
if (isMasked())
- {
- throw new IllegalStateException("masked envelope");
- }
+ throw new IllegalStateException("masked envelope");
return super.get(alias);
}
public boolean remove(Entry entry)
{
if (isMasked())
- {
- throw new IllegalStateException("masked envelope");
- }
+ throw new IllegalStateException("masked envelope");
return super.remove(entry);
}
- public void remove(String alias)
+ public boolean remove(String alias)
{
if (isMasked())
- {
- throw new IllegalStateException("masked envelope");
- }
- super.remove(alias);
+ throw new IllegalStateException("masked envelope");
+ return super.remove(alias);
+ }
+
+ public String toString()
+ {
+ return new StringBuilder("MaskableEnvelope{")
+ .append(super.toString())
+ .append(", masked=").append(masked)
+ .append("}").toString();
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/MeteredInputStream.java b/libjava/classpath/gnu/javax/crypto/keyring/MeteredInputStream.java
index fcf2be7..330e4b2 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/MeteredInputStream.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/MeteredInputStream.java
@@ -39,22 +39,15 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
import java.io.FilterInputStream;
-import java.io.InputStream;
import java.io.IOException;
+import java.io.InputStream;
-final class MeteredInputStream extends FilterInputStream
+final class MeteredInputStream
+ extends FilterInputStream
{
-
- // Fields.
- // ------------------------------------------------------------------------
-
private int count;
-
private final int limit;
- // Constructor.
- // ------------------------------------------------------------------------
-
MeteredInputStream(InputStream in, int limit)
{
super(in);
@@ -64,12 +57,9 @@ final class MeteredInputStream extends FilterInputStream
count = 0;
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
/**
* Tests if the number of bytes read has reached the limit.
- *
+ *
* @return True if the limit has been reached.
*/
public boolean limitReached()
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java b/libjava/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java
index 2e3a0d1..be10029 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/PasswordAuthenticatedEntry.java
@@ -38,9 +38,11 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;
+import gnu.java.security.util.PRNG;
import gnu.java.security.util.Util;
import gnu.javax.crypto.mac.IMac;
import gnu.javax.crypto.mac.MacFactory;
@@ -55,35 +57,27 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
-import java.security.SecureRandom;
import java.util.Arrays;
-import java.util.Iterator;
import java.util.HashMap;
+import java.util.Iterator;
+import java.util.logging.Logger;
/**
- * An entry authenticated with a password-based MAC. An immutable class representing a private or secret key entry. Creates a new key entry. Returns this entry's key.
+ * References:
+ *
+ * IMPORTANT: This class is NOT thread safe.
+ *
+ * References:
+ * A base abstract class to facilitate MAC (Message Authentication
- * Code) implementations. Trivial constructor for use by concrete subclasses. Trivial constructor for use by concrete subclasses. The implementation of the HMAC (Keyed-Hash Message Authentication
- * Code). HMAC can be used in combination with any iterated cryptographic
- * hash function. HMAC also uses a secret key for calculation and
+ * The implementation of the HMAC (Keyed-Hash Message Authentication
+ * Code).
+ *
+ * HMAC can be used in combination with any iterated cryptographic hash
+ * function. HMAC also uses a secret key for calculation and
* verification of the message authentication values. The main goals behind this
- * construction are References:
+ * References:
* Trivial constructor for use by concrete subclasses. A Factory to instantiate Keyed-Hash Message Authentication Code
- * (HMAC) algorithm instances. Return an instance of a HMAC algorithm given the name of its
+ * Return an instance of a HMAC algorithm given the name of its
* underlying hash function, prefixed with the literal defined in
- * {@link Registry#HMAC_NAME_PREFIX}. Returns a {@link java.util.Set} of names of HMAC algorithms
- * supported by this Factory.
+ * Returns a {@link java.util.Set} of names of HMAC algorithms
+ * supported by this Factory.
+ * The basic visible methods of any MAC (Message Authentication Code)
- * algorithm. A MAC provides a way to check the integrity of information
+ * The basic visible methods of any MAC (Message Authentication Code) algorithm.
+ *
+ * A MAC provides a way to check the integrity of information
* transmitted over, or stored in, an unreliable medium, based on a secret key.
* Typically, MACs are used between two parties, that share a common
- * secret key, in order to validate information transmitted between them. When a MAC algorithm is based on a cryptographic hash function, it
- * is then called to a HMAC (Hashed Message Authentication Code) --see
- * RFC-2104.
+ * When a MAC algorithm is based on a cryptographic hash function, it is
+ * then called to a HMAC (Hashed Message Authentication Code) --see RFC-2104.
+ *
* Another type of MAC algorithms exist: UMAC or Universal Message
- * Authentication Code, described in
- *
- * draft-krovetz-umac-01.txt. With UMACs, the sender and receiver share a common secret key (the
- * MAC key) which determines:
+ * With UMACs, the sender and receiver share a common secret key (the
+ * MAC key) which determines:
* References:
+ * References:
* Property name of the desired truncated output size in bytes. The value
- * associated to this property name is taken to be an integer. If no value
- * is specified in the attributes map at initialisation time, then all bytes
- * of the underlying hash algorithm's output are emitted. This implementation, follows the recommendation of the RFC 2104
- * authors; specifically:
+ * This implementation, follows the recommendation of the RFC 2104
+ * authors; specifically:
* Returns the canonical name of this algorithm. Returns the output length in bytes of this MAC algorithm. Initialises the algorithm with designated attributes. Permissible names
- * and values are described in the class documentation above. Continues a MAC operation using the input byte. Continues a MAC operation, by filling the buffer, processing
- * data in the algorithm's MAC_SIZE-bit block(s), updating the context and
- * count, and buffering the remaining bytes in buffer for the next
- * operation. Completes the MAC by performing final operations such as
- * padding and resetting the instance. Resets the algorithm instance for re-initialisation and use with other
- * characteristics. This method always succeeds. A basic test. Ensures that the MAC of a pre-determined message is equal
- * to a known pre-computed value. Returns a clone copy of this instance. A Factory that instantiates instances of every supported Message
- * Authentication Code algorithms, including all HMAC algorithms. Returns an instance of a MAC algorithm given its name. Returns a {@link java.util.Set} of names of MAC algorithms
- * supported by this Factory. A filtering output stream that computes a MAC (message authentication
- * code) over all data written to the stream. Creates a new Returns the MAC this stream is updating. Sets the MAC this stream is updating, which must have already been
- * initialized. The argument is not cloned by this method. Turns the digesting state on or off. When off, the MAC will not be
- * updated when data is written to the stream. The One-Key CBC MAC, OMAC. This message authentication code is based on
- * a block cipher in CBC mode. References:
+ * References:
* TMMH is a universal hash function suitable for message
+ * TMMH is a universal hash function suitable for message
* authentication in the Wegman-Carter paradigm, as in the Stream Cipher
* Security Transform. It is simple, quick, and especially appropriate for
* Digital Signal Processors and other processors with a fast multiply
* operation, though a straightforward implementation requires storage equal in
- * length to the largest message to be hashed. TMMH is a simple hash function which maps a key and a message to a
+ * length to the largest message to be hashed.
+ *
+ * TMMH is a simple hash function which maps a key and a message to a
* hash value. There are two versions of TMMH: TMMH/16 and TMMH/32. TMMH
* can be used as a message authentication code, as described in Section 5 (see
- * References). The key, message, and hash value are all octet strings, and the lengths of
+ * References).
+ *
+ * The key, message, and hash value are all octet strings, and the lengths of
* these quantities are denoted as The parameter
+ * The parameter References:
+ * References:
* Similar to the same method with one argument, but uses the designated
- * random number generator to compute needed keying material. Similar to the same method with three arguments, but uses the
- * designated random number generator to compute needed keying material. Similar to the same method with no arguments, but uses the designated
- * random number generator to compute needed keying material. UHASH is a keyed hash function, which takes as input a string of
+ * UHASH is a keyed hash function, which takes as input a string of
* arbitrary length, and produces as output a string of fixed length (such as 8
- * bytes). The actual output length depends on the parameter UMAC-OUTPUT-LEN. UHASH has been shown to be epsilon-ASU ("Almost Strongly
+ * bytes). The actual output length depends on the parameter UMAC-OUTPUT-LEN.
+ *
+ * UHASH has been shown to be epsilon-ASU ("Almost Strongly
* Universal"), where epsilon is a small (parameter-dependent) real number.
* Informally, saying that a keyed hash function is epsilon-ASU means
* that for any two distinct fixed input strings, the two outputs of the hash
* function with a random key "look almost like a pair of random strings". The
- * number epsilon measures how non-random the output strings may be.
+ * UHASH has been designed to be fast by exploiting several
+ * architectural features of modern commodity processors. It was specifically
+ * designed for use in UMAC. But UHASH is useful beyond that
+ * domain, and can be easily adopted for other purposes.
+ *
* UHASH does its work in three layers. First, a hash function called
* References:
+ * References:
* Private constructor for cloning purposes. The prime numbers used in UMAC are: Private constructor for cloning purposes. Second hash stage of the UHash32 algorithm.
+ * Second hash stage of the UHash32 algorithm.
+ *
+ * 5.4 L2-HASH-32: Second-layer hash.
* The implementation of the UMAC (Universal Message Authentication
- * Code). The UMAC algorithms described are parameterized. This means
+ * The implementation of the UMAC (Universal Message Authentication
+ * Code).
+ *
+ * The UMAC algorithms described are parameterized. This means
* that various low-level choices, like the endian convention and the underlying
* cryptographic primitive, have not been fixed. One must choose values for
* these parameters before the authentication tag generated by UMAC (for
- * a given message, key, and nonce) becomes fully-defined. In this document
- * we provide two collections of parameter settings, and have named the sets
- * UMAC16 and UMAC32. The parameter sets have been chosen based on
- * experimentation and provide good performance on a wide variety of processors.
- * UMAC16 is designed to excel on processors which provide small-scale
- * SIMD parallelism of the type found in Intel's MMX and Motorola's AltiVec
- * instruction sets, while UMAC32 is designed to do well on processors
- * with good 32- and 64- bit support. UMAC32 may take advantage of SIMD
- * parallelism in future processors. UMAC has been designed to allow implementations which accommodate
- * on-line authentication. This means that pieces of the message may
- * be presented to UMAC at different times (but in correct order) and an
+ * a given message, key, and nonce) becomes fully-defined. In this document we
+ * provide two collections of parameter settings, and have named the sets
+ * UMAC16 and UMAC32. The parameter sets have been chosen based
+ * on experimentation and provide good performance on a wide variety of
+ * processors. UMAC16 is designed to excel on processors which provide
+ * small-scale SIMD parallelism of the type found in Intel's MMX and Motorola's
+ * AltiVec instruction sets, while UMAC32 is designed to do well on
+ * processors with good 32- and 64- bit support. UMAC32 may take
+ * advantage of SIMD parallelism in future processors.
+ *
+ * UMAC has been designed to allow implementations which accommodate
+ * on-line authentication. This means that pieces of the message may be
+ * presented to UMAC at different times (but in correct order) and an
* on-line implementation will be able to process the message correctly without
* the need to buffer more than a few dozen bytes of the message. For
* simplicity, the algorithms in this specification are presented as if the
- * entire message being authenticated were available at once. To authenticate a message,
+ * To authenticate a message, Here
+ * Here The universal hash function that we use is called
+ * The universal hash function that we use is called For the pseudorandom function we use the block cipher of the Advanced
- * Encryption Standard (AES). The UMAC32 parameters, considered in this implementation are:
+ * For the pseudorandom function we use the block cipher of the Advanced
+ * Encryption Standard (AES).
+ *
+ * The UMAC32 parameters, considered in this implementation are:
* Please note that this UMAC32 differs from the one described in the paper
- * by the ENDIAN-FAVORITE value. References:
+ * Please note that this UMAC32 differs from the one described in the paper by
+ * the ENDIAN-FAVORITE value.
+ *
+ * References:
* Private constructor for cloning purposes. Initialising a UMAC instance consists of defining values for
- * the following parameters: For convenience, this implementation accepts that not both parameters
- * be always specified.
+ * For convenience, this implementation accepts that not both parameters be
+ * always specified.
* This method throws an exception if no Key Material is specified
- * in the input map, and there is no previously set/defined Key Material
+ *
+ * This method throws an exception if no Key Material is specified in
+ * the input map, and there is no previously set/defined Key Material
* (from an earlier invocation of this method). If a Key Material can
- * be used, but no Nonce Material is defined or previously set/defined,
- * then a default value of all-zeroes shall be used. A basic abstract class to facilitate implementing block cipher modes of
- * operations. Trivial constructor for use by concrete subclasses. Returns the default value, in bytes, of the mode's block size. This
- * value is part of the construction arguments passed to the Factory methods
- * in {@link ModeFactory}. Unless changed by an invocation of any of the
+ * Returns the default value, in bytes, of the mode's block size. This value
+ * is part of the construction arguments passed to the Factory methods in
+ * {@link ModeFactory}. Unless changed by an invocation of any of the
* Returns the default value, in bytes, of the underlying block cipher
- * key size. Returns an {@link Iterator} over the supported block sizes. Each
- * element returned by this object is an {@link Integer}. The default behaviour is to return an iterator with just one value,
- * which is that currently configured for the underlying block cipher.
- * Concrete implementations may override this behaviour to signal their
- * ability to support other values.
+ * The default behaviour is to return an iterator with just one value, which
+ * is that currently configured for the underlying block cipher. Concrete
+ * implementations may override this behaviour to signal their ability to
+ * support other values.
+ *
* @return an {@link Iterator} over the supported block sizes.
*/
public Iterator blockSizes()
{
ArrayList al = new ArrayList();
- al.add(new Integer(cipherBlockSize));
-
+ al.add(Integer.valueOf(cipherBlockSize));
return Collections.unmodifiableList(al).iterator();
}
/**
- * Returns an {@link Iterator} over the supported underlying block cipher
- * key sizes. Each element returned by this object is an instance of
- * {@link Integer}.null
*/
- public Object getParameter (Class type)
+ public Object getParameter (int type)
{
- if (type == ThreadId.class)
+ if (type == EVENT_THREAD)
return _thread;
- else if (type == ReferenceTypeId.class)
+ else if (type == EVENT_CLASS)
return _class;
return null;
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/ClassUnloadEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/ClassUnloadEvent.java
new file mode 100644
index 0000000..4ba8bc8
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/jdwp/event/ClassUnloadEvent.java
@@ -0,0 +1,96 @@
+/* ClassUnloadEvent.java -- event generated when a class is unloaded
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+ This file is part of GNU Classpath.
+
+ GNU Classpath is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ GNU Classpath is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Classpath; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+ Linking this library statically or dynamically with other modules is
+ making a combined work based on this library. Thus, the terms and
+ conditions of the GNU General Public License cover the whole
+ combination.
+
+ As a special exception, the copyright holders of this library give you
+ permission to link this library with independent modules to produce an
+ executable, regardless of the license terms of these independent
+ modules, and to copy and distribute the resulting executable under
+ terms of your choice, provided that you also meet, for each linked
+ independent module, the terms and conditions of the license of that
+ module. An independent module is a module which is not derived from
+ or based on this library. If you modify this library, you may extend
+ this exception to your version of the library, but you are not
+ obligated to do so. If you do not wish to do so, delete this
+ exception statement from your version. */
+
+
+package gnu.classpath.jdwp.event;
+
+import gnu.classpath.jdwp.JdwpConstants;
+import gnu.classpath.jdwp.VMIdManager;
+import gnu.classpath.jdwp.util.JdwpString;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+/**
+ * "Notification of a class unload in the target VM" -- JDWP 1.4.2
+ *
+ * @author Kyle Galloway (kgallowa@redhat.com)
+ */
+public class ClassUnloadEvent
+ extends Event
+{
+ //signature directly from VM
+ private String _signature;
+
+ /**
+ * Constructs a new ClassUnloadEvent
+ *
+ * @param signature the signature reported from the VM
+ */
+ public ClassUnloadEvent(String signature)
+ {
+ super(JdwpConstants.EventKind.CLASS_UNLOAD);
+ _signature = signature;
+ }
+
+ /**
+ * Returns a specific filtering parameter for this event. Class is the only
+ * valid type.
+ *
+ * @param type the type of parameter desired
+ * @returns the desired parameter or null
+ */
+ public Object getParameter(int type)
+ {
+
+ return null;
+ }
+
+ /**
+ * Writes the event to the given stream
+ *
+ * @param outStream the output stream to write the event to
+ */
+ protected void _writeData(DataOutputStream outStream)
+ throws IOException
+ {
+ VMIdManager idm = VMIdManager.getDefault();
+
+ JdwpString.writeString(outStream, _signature);
+ }
+
+}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/Event.java b/libjava/classpath/gnu/classpath/jdwp/event/Event.java
index 14e5b78..e91108a 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/Event.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/Event.java
@@ -54,6 +54,41 @@ import java.io.IOException;
*/
public abstract class Event
{
+ /**
+ * The class of the object in which the event occurred
+ */
+ public static final int EVENT_CLASS = 1;
+
+ /**
+ * The thread where the event occurred
+ */
+ public static final int EVENT_THREAD = 2;
+
+ /**
+ * The location where an event occurred
+ */
+ public static final int EVENT_LOCATION = 3;
+
+ /**
+ * The instance of the class where the event occurred
+ */
+ public static final int EVENT_INSTANCE = 4;
+
+ /**
+ * The field acted on by an event
+ */
+ public static final int EVENT_FIELD = 5;
+
+ /**
+ * The class of the exception for ExceptionEvent
+ */
+ public static final int EVENT_EXCEPTION_CLASS = 6;
+
+ /**
+ * Whether this exception was caught (only valid for ExceptionEvents)
+ */
+ public static final int EVENT_EXCEPTION_CAUGHT = 7;
+
// The kind of event represented by this event
private byte _eventKind;
@@ -97,7 +132,7 @@ public abstract class Event
* @returns the parameter (not the ID) or null
if none is
* is defined for this event
*/
- public abstract Object getParameter (Class type);
+ public abstract Object getParameter (int type);
/**
* Converts this event into to a JDWP packet
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/EventManager.java b/libjava/classpath/gnu/classpath/jdwp/event/EventManager.java
index eb0c3dd..54a7b08 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/EventManager.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/EventManager.java
@@ -1,5 +1,5 @@
/* EventManager.java -- event management and notification infrastructure
- Copyright (C) 2005 Free Software Foundation
+ Copyright (C) 2005, 2006 Free Software Foundation
This file is part of GNU Classpath.
@@ -69,7 +69,7 @@ import java.util.Iterator;
public class EventManager
{
// Single instance
- private static EventManager _instance = new EventManager ();
+ private static EventManager _instance = null;
// maps event (EVENT_*) to lists of EventRequests
private Hashtable _requests = null;
@@ -79,8 +79,11 @@ public class EventManager
*
* @return the event manager
*/
- public static EventManager getDefault ()
+ public static EventManager getDefault()
{
+ if (_instance == null)
+ _instance = new EventManager();
+
return _instance;
}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/ExceptionEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/ExceptionEvent.java
new file mode 100644
index 0000000..1303c09
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/jdwp/event/ExceptionEvent.java
@@ -0,0 +1,157 @@
+/* ExceptionEvent.java -- an event specifying an exception has been thrown
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+ This file is part of GNU Classpath.
+
+ GNU Classpath is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ GNU Classpath is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Classpath; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+ Linking this library statically or dynamically with other modules is
+ making a combined work based on this library. Thus, the terms and
+ conditions of the GNU General Public License cover the whole
+ combination.
+
+ As a special exception, the copyright holders of this library give you
+ permission to link this library with independent modules to produce an
+ executable, regardless of the license terms of these independent
+ modules, and to copy and distribute the resulting executable under
+ terms of your choice, provided that you also meet, for each linked
+ independent module, the terms and conditions of the license of that
+ module. An independent module is a module which is not derived from
+ or based on this library. If you modify this library, you may extend
+ this exception to your version of the library, but you are not
+ obligated to do so. If you do not wish to do so, delete this
+ exception statement from your version. */
+
+
+package gnu.classpath.jdwp.event;
+
+import gnu.classpath.jdwp.JdwpConstants;
+import gnu.classpath.jdwp.VMIdManager;
+import gnu.classpath.jdwp.id.ObjectId;
+import gnu.classpath.jdwp.id.ThreadId;
+import gnu.classpath.jdwp.util.Location;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+/**
+ * Notification from the VM that an exception has occurred along with where it
+ * occurred, and if and where it was caught.
+ *
+ * @author Kyle Galloway (kgallowa@redhat.com)
+ */
+public class ExceptionEvent
+ extends Event
+{
+ //object instance
+ private Object _instance;
+
+ // the exception thrown
+ private Throwable _exception;
+
+ // the thread in which the exception occurred
+ private Thread _thread;
+
+ // the location where the exception was thrown
+ private Location _location;
+
+ //the location where the exception was caught
+ private Location _catchLocation;
+
+ //the class where the exeption was thrown
+ private Class _klass;
+
+ /**
+ * Constructs a new ExceptionEvent
where the exception was
+ * caught.
+ *
+ * @param exception the throwable object that generated the event
+ * @param thread the thread where the exception occurred
+ * @param location the location where the exception was thrown
+ * @param catchLocation the location where the exception was caught
+ * @param instance the instance that threw the exception
+ */
+ public ExceptionEvent(Throwable exception, Thread thread, Location location,
+ Location catchLocation, Class clazz, Object instance)
+ {
+ super(JdwpConstants.EventKind.EXCEPTION);
+ _exception = exception;
+ _thread = thread;
+ _location = location;
+ _catchLocation = catchLocation;
+ _klass = clazz;
+ _instance = instance;
+ }
+
+ /**
+ * Returns a specific filtering parameter for this event. Valid types are
+ * thread, location, and catchLocation.
+ *
+ * @param type the type of parameter desired
+ * @returns the desired parameter or null
+ */
+ public Object getParameter(int type)
+ {
+ if (type == EVENT_THREAD)
+ return _thread;
+ else if (type == EVENT_LOCATION)
+ return _location;
+ else if (type == EVENT_INSTANCE)
+ return _instance;
+ else if (type == EVENT_CLASS)
+ return _klass;
+ else if (type == EVENT_EXCEPTION_CLASS)
+ return _exception.getClass();
+ else if (type == EVENT_EXCEPTION_CAUGHT)
+ if (_catchLocation.getMethod() != null)
+ return new Boolean(true);
+ else
+ return new Boolean(false);
+
+ return null;
+ }
+
+ /**
+ * Sets the catchLocation, used for exceptions that are caught in different
+ * stack frames from where they are thrown.
+ *
+ * @param catchLoc the location of the catch
+ */
+ public void setCatchLoc(Location catchLoc)
+ {
+ _catchLocation = catchLoc;
+ }
+
+ /**
+ * Writes the event to the given stream
+ *
+ * @param outStream the output stream to write the event to
+ * @throws IOException
+ */
+ protected void _writeData(DataOutputStream outStream)
+ throws IOException
+ {
+ VMIdManager idm = VMIdManager.getDefault();
+ ThreadId tid = (ThreadId) idm.getObjectId(_thread);
+ ObjectId oid = idm.getObjectId(_exception);
+
+ tid.write(outStream);
+ _location.write(outStream);
+ oid.writeTagged(outStream);
+ _catchLocation.write(outStream);
+
+ }
+}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/MethodEntryEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/MethodEntryEvent.java
new file mode 100644
index 0000000..40c0516
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/jdwp/event/MethodEntryEvent.java
@@ -0,0 +1,118 @@
+/* MethodEntryEvent.java -- an event specifying that a method has been invoked
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+ This file is part of GNU Classpath.
+
+ GNU Classpath is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ GNU Classpath is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Classpath; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+ Linking this library statically or dynamically with other modules is
+ making a combined work based on this library. Thus, the terms and
+ conditions of the GNU General Public License cover the whole
+ combination.
+
+ As a special exception, the copyright holders of this library give you
+ permission to link this library with independent modules to produce an
+ executable, regardless of the license terms of these independent
+ modules, and to copy and distribute the resulting executable under
+ terms of your choice, provided that you also meet, for each linked
+ independent module, the terms and conditions of the license of that
+ module. An independent module is a module which is not derived from
+ or based on this library. If you modify this library, you may extend
+ this exception to your version of the library, but you are not
+ obligated to do so. If you do not wish to do so, delete this
+ exception statement from your version. */
+
+
+package gnu.classpath.jdwp.event;
+
+import gnu.classpath.jdwp.JdwpConstants;
+import gnu.classpath.jdwp.VMIdManager;
+import gnu.classpath.jdwp.id.ThreadId;
+import gnu.classpath.jdwp.util.Location;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+/**
+ * Notification from the VM that that a method has been invoked
+ *
+ * @author Kyle Galloway (kgallowa@redhat.com)
+ */
+public class MethodEntryEvent
+ extends Event
+{
+ // The thread where the event occurred
+ private Thread _thread;
+
+ // the location where the event occurred
+ private Location _location;
+
+ //object instance
+ private Object _instance;
+
+ /**
+ * Constructs a new MethodEntryEvent
+ *
+ * @param thread the thread where the exception occurred
+ * @param location the location single stepped to
+ * @param instance instance from which the method was called
+ */
+ public MethodEntryEvent(Thread thread, Location location, Object instance)
+ {
+ super(JdwpConstants.EventKind.METHOD_ENTRY);
+ _thread = thread;
+ _location = location;
+ _instance = instance;
+ }
+
+ /**
+ * Returns a specific filtering parameter for this event. Valid types are
+ * thread and location
+ *
+ * @param type the type of parameter desired
+ * @returns the desired parameter or null
+ */
+ public Object getParameter(int type)
+ {
+ if (type == EVENT_THREAD)
+ return _thread;
+ else if (type == EVENT_LOCATION)
+ return _location;
+ else if (type == EVENT_INSTANCE)
+ return _instance;
+ else if (type == EVENT_CLASS)
+ return _instance.getClass();
+
+ return null;
+ }
+
+ /**
+ * Writes the event to the given stream
+ *
+ * @param outStream the output stream to write the event to
+ * @throws IOException
+ */
+ protected void _writeData(DataOutputStream outStream)
+ throws IOException
+ {
+ VMIdManager idm = VMIdManager.getDefault();
+ ThreadId tid = (ThreadId) idm.getObjectId(_thread);
+
+ tid.write(outStream);
+ _location.write(outStream);
+ }
+
+}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/MethodExitEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/MethodExitEvent.java
new file mode 100644
index 0000000..ce03dd2
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/jdwp/event/MethodExitEvent.java
@@ -0,0 +1,115 @@
+/* MethodExitEvent.java -- an event specifying that a method has returned
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+ This file is part of GNU Classpath.
+
+ GNU Classpath is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ GNU Classpath is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Classpath; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+ Linking this library statically or dynamically with other modules is
+ making a combined work based on this library. Thus, the terms and
+ conditions of the GNU General Public License cover the whole
+ combination.
+
+ As a special exception, the copyright holders of this library give you
+ permission to link this library with independent modules to produce an
+ executable, regardless of the license terms of these independent
+ modules, and to copy and distribute the resulting executable under
+ terms of your choice, provided that you also meet, for each linked
+ independent module, the terms and conditions of the license of that
+ module. An independent module is a module which is not derived from
+ or based on this library. If you modify this library, you may extend
+ this exception to your version of the library, but you are not
+ obligated to do so. If you do not wish to do so, delete this
+ exception statement from your version. */
+
+
+package gnu.classpath.jdwp.event;
+
+import gnu.classpath.jdwp.JdwpConstants;
+import gnu.classpath.jdwp.VMIdManager;
+import gnu.classpath.jdwp.id.ThreadId;
+import gnu.classpath.jdwp.util.Location;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+/**
+ * Notification from the VM that that a method has returned
+ *
+ * @author Kyle Galloway (kgallowa@redhat.com)
+ */
+public class MethodExitEvent
+ extends Event
+{
+ // The thread where the event occurred
+ private Thread _thread;
+
+ // the location where the event occurred
+ private Location _location;
+
+ // object instance
+ private Object _instance;
+
+ /**
+ * Constructs a new MethodExitEvent
+ *
+ * @param thread the thread where the exception occurred
+ * @param location the location single stepped to
+ * @param instance the instance from which the method was called
+ */
+ public MethodExitEvent(Thread thread, Location location, Object instance)
+ {
+ super(JdwpConstants.EventKind.METHOD_EXIT);
+ _thread = thread;
+ _location = location;
+ _instance = instance;
+ }
+
+ /**
+ * Returns a specific filtering parameter for this event. Valid types are
+ * thread and location
+ *
+ * @param type the type of parameter desired
+ * @returns the desired parameter or null
+ */
+ public Object getParameter(int type)
+ {
+ if (type == EVENT_THREAD)
+ return _thread;
+ else if (type == EVENT_LOCATION)
+ return _location;
+ else if (type == EVENT_CLASS)
+ return _instance.getClass();
+
+ return null;
+ }
+
+ /**
+ * Writes the event to the given stream
+ *
+ * @param outStream the output stream to write the event to
+ * @throws IOException
+ */
+ protected void _writeData(DataOutputStream outStream)
+ throws IOException
+ {
+ VMIdManager idm = VMIdManager.getDefault();
+ ThreadId tid = (ThreadId) idm.getObjectId(_thread);
+
+ tid.write(outStream);
+ _location.write(outStream);
+ }
+}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/SingleStepEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/SingleStepEvent.java
new file mode 100644
index 0000000..cd69dd9
--- /dev/null
+++ b/libjava/classpath/gnu/classpath/jdwp/event/SingleStepEvent.java
@@ -0,0 +1,121 @@
+/* SingleStepEvent.java -- an event specifying that a single step has
+ compleated
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+ This file is part of GNU Classpath.
+
+ GNU Classpath is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ GNU Classpath is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Classpath; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+ Linking this library statically or dynamically with other modules is
+ making a combined work based on this library. Thus, the terms and
+ conditions of the GNU General Public License cover the whole
+ combination.
+
+ As a special exception, the copyright holders of this library give you
+ permission to link this library with independent modules to produce an
+ executable, regardless of the license terms of these independent
+ modules, and to copy and distribute the resulting executable under
+ terms of your choice, provided that you also meet, for each linked
+ independent module, the terms and conditions of the license of that
+ module. An independent module is a module which is not derived from
+ or based on this library. If you modify this library, you may extend
+ this exception to your version of the library, but you are not
+ obligated to do so. If you do not wish to do so, delete this
+ exception statement from your version. */
+
+
+package gnu.classpath.jdwp.event;
+
+import gnu.classpath.jdwp.JdwpConstants;
+import gnu.classpath.jdwp.VMIdManager;
+import gnu.classpath.jdwp.id.ThreadId;
+import gnu.classpath.jdwp.util.Location;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+
+
+/**
+ * Notification from the VM that a single step has compleated including the
+ * thread and location stepped to
+ *
+ * @author Kyle Galloway (kgallowa@redhat.com)
+ */
+public class SingleStepEvent
+ extends Event
+{
+ // the thread where the event occurred
+ private Thread _thread;
+
+ // the location where the event occurred
+ private Location _location;
+
+ //object instance
+ private Object _instance;
+
+ /**
+ * Constructs a new SingleStepEvent
+ *
+ * @param thread the thread where the exception occurred
+ * @param location the location single stepped to
+ * @param instance the instance in which the single step occurred
+ */
+ public SingleStepEvent(Thread thread, Location location, Object instance)
+ {
+ super(JdwpConstants.EventKind.SINGLE_STEP);
+ _thread = thread;
+ _location = location;
+ _instance = instance;
+ }
+
+ /**
+ * Returns a specific filtering parameter for this event. Valid types are
+ * thread and location
+ *
+ * @param type the type of parameter desired
+ * @returns the desired parameter or null
+ */
+ public Object getParameter(int type)
+ {
+ if (type == EVENT_THREAD)
+ return _thread;
+ else if (type == EVENT_LOCATION)
+ return _location;
+ else if (type == EVENT_INSTANCE)
+ return _instance;
+ else if (type == EVENT_CLASS)
+ return _instance.getClass();
+
+ return null;
+ }
+
+ /**
+ * Writes the event to the given stream
+ *
+ * @param outStream the output stream to write the event to
+ * @throws IOException
+ */
+ protected void _writeData(DataOutputStream outStream)
+ throws IOException
+ {
+ VMIdManager idm = VMIdManager.getDefault();
+ ThreadId tid = (ThreadId) idm.getObjectId(_thread);
+
+ tid.write(outStream);
+ _location.write(outStream);
+ }
+
+}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/ThreadEndEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/ThreadEndEvent.java
index 768b216..c665428 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/ThreadEndEvent.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/ThreadEndEvent.java
@@ -81,9 +81,9 @@ public class ThreadEndEvent
* @param type the type of parameter desired
* @returns the desired parameter or null
*/
- public Object getParameter (Class type)
+ public Object getParameter (int type)
{
- if (type == ThreadId.class)
+ if (type == EVENT_THREAD)
return _thread;
return null;
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/ThreadStartEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/ThreadStartEvent.java
index 2fa2079..f9c507d 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/ThreadStartEvent.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/ThreadStartEvent.java
@@ -86,9 +86,9 @@ public class ThreadStartEvent
* @param type the type of parameter desired
* @returns the desired parameter or null
*/
- public Object getParameter (Class type)
+ public Object getParameter (int type)
{
- if (type == ThreadId.class)
+ if (type == EVENT_THREAD)
return _thread;
return null;
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/VmDeathEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/VmDeathEvent.java
index 160ef6a..a729bd4 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/VmDeathEvent.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/VmDeathEvent.java
@@ -67,7 +67,7 @@ public class VmDeathEvent
* @param type the type of parameter desired
* @returns the desired parameter or null
*/
- public Object getParameter (Class type)
+ public Object getParameter (int type)
{
return null;
}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/VmInitEvent.java b/libjava/classpath/gnu/classpath/jdwp/event/VmInitEvent.java
index dd228e9..1ed63b2 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/VmInitEvent.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/VmInitEvent.java
@@ -76,7 +76,7 @@ public class VmInitEvent
* @param type the type of parameter desired
* @returns the desired parameter or null
*/
- public Object getParameter (Class type)
+ public Object getParameter (int type)
{
return null;
}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/filters/ClassMatchFilter.java b/libjava/classpath/gnu/classpath/jdwp/event/filters/ClassMatchFilter.java
index 62a3a74..a898431 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/filters/ClassMatchFilter.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/filters/ClassMatchFilter.java
@@ -41,7 +41,6 @@ package gnu.classpath.jdwp.event.filters;
import gnu.classpath.jdwp.event.Event;
import gnu.classpath.jdwp.exception.InvalidStringException;
-import gnu.classpath.jdwp.id.ReferenceTypeId;
/**
* An event filter which includes events matching a
@@ -91,7 +90,7 @@ public class ClassMatchFilter
*/
public boolean matches (Event event)
{
- Object type = event.getParameter (ReferenceTypeId.class);
+ Object type = event.getParameter (Event.EVENT_CLASS);
if (type != null)
{
Class eventClass = (Class) type;
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/filters/ClassOnlyFilter.java b/libjava/classpath/gnu/classpath/jdwp/event/filters/ClassOnlyFilter.java
index e4bf06c..455cac6 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/filters/ClassOnlyFilter.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/filters/ClassOnlyFilter.java
@@ -87,7 +87,7 @@ public class ClassOnlyFilter
*/
public boolean matches (Event event)
{
- Object type = event.getParameter (ReferenceTypeId.class);
+ Object type = event.getParameter (Event.EVENT_CLASS);
if (type != null)
{
try
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/filters/ExceptionOnlyFilter.java b/libjava/classpath/gnu/classpath/jdwp/event/filters/ExceptionOnlyFilter.java
index cf6c070..8bb56ed 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/filters/ExceptionOnlyFilter.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/filters/ExceptionOnlyFilter.java
@@ -1,5 +1,5 @@
-/* ExceptionOnlyFilter.java --
- Copyright (C) 2005 Free Software Foundation
+/* ExceptionOnlyFilter.java -- filter for excetions by caught/uncaught and type
+ Copyright (C) 2005, 2006 Free Software Foundation
This file is part of GNU Classpath.
@@ -61,7 +61,7 @@ public class ExceptionOnlyFilter
/**
* Constructs a new ExceptionOnlyFilter
*
- * @param refId ID of the exception to report
+ * @param refId ID of the exception to report(null for all exceptions)
* @param caught Report caught exceptions
* @param uncaught Report uncaught exceptions
* @throws InvalidClassException if refid is invalid
@@ -70,8 +70,8 @@ public class ExceptionOnlyFilter
boolean uncaught)
throws InvalidClassException
{
- if (refId == null || refId.getReference().get () == null)
- throw new InvalidClassException (refId.getId ());
+ if (refId != null && refId.getReference().get() == null)
+ throw new InvalidClassException(refId.getId());
_refId = refId;
_caught = caught;
@@ -88,34 +88,36 @@ public class ExceptionOnlyFilter
return _refId;
}
- /**
- * Report caught exceptions?
- *
- * @return whether to report caught exceptions
- */
- public boolean forCaught ()
- {
- return _caught;
- }
-
- /**
- * Report uncaught exceptions?
- *
- * @return whether to report uncaught exceptions
- */
- public boolean forUncaught ()
- {
- return _uncaught;
- }
-
+
/**
* Does the given event match the filter?
- *
- * @param event the Event
to scrutinize
+ *
+ * @param event the Event
to scrutinize
*/
- public boolean matches (Event event)
+ public boolean matches(Event event)
{
- // FIXME
- throw new RuntimeException ("ExceptionOnlyFilter.matches not implemented");
+ boolean classMatch = true;
+
+ // if not allowing all exceptions check if the exception matches
+ if (_refId != null)
+ {
+ try
+ {
+ Class klass
+ = (Class) event.getParameter(Event.EVENT_EXCEPTION_CLASS);
+ classMatch = klass == _refId.getType();
+ }
+ catch (InvalidClassException ex)
+ {
+ classMatch = false;
+ }
+ }
+
+ // check against the caught and uncaught options
+ Boolean caught
+ = (Boolean) event.getParameter(Event.EVENT_EXCEPTION_CAUGHT);
+
+ return classMatch && ((caught.booleanValue()) ? _caught : _uncaught);
}
+
}
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/filters/InstanceOnlyFilter.java b/libjava/classpath/gnu/classpath/jdwp/event/filters/InstanceOnlyFilter.java
index 130749b..bda5b27 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/filters/InstanceOnlyFilter.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/filters/InstanceOnlyFilter.java
@@ -89,7 +89,7 @@ public class InstanceOnlyFilter
*/
public boolean matches (Event event)
{
- Object eventInstance = event.getParameter (ObjectId.class);
+ Object eventInstance = event.getParameter (Event.EVENT_INSTANCE);
if (eventInstance != null)
{
Object myInstance = _instance.getReference().get ();
diff --git a/libjava/classpath/gnu/classpath/jdwp/event/filters/ThreadOnlyFilter.java b/libjava/classpath/gnu/classpath/jdwp/event/filters/ThreadOnlyFilter.java
index 2c7a0f1..bc1eab8 100644
--- a/libjava/classpath/gnu/classpath/jdwp/event/filters/ThreadOnlyFilter.java
+++ b/libjava/classpath/gnu/classpath/jdwp/event/filters/ThreadOnlyFilter.java
@@ -65,7 +65,7 @@ public class ThreadOnlyFilter
public ThreadOnlyFilter (ThreadId tid)
throws InvalidThreadException
{
- if (tid.getReference().get () == null)
+ if (tid == null || tid.getReference().get () == null)
throw new InvalidThreadException (tid.getId ());
_tid = tid;
@@ -88,7 +88,7 @@ public class ThreadOnlyFilter
*/
public boolean matches (Event event)
{
- Object thread = event.getParameter (ThreadId.class);
+ Object thread = event.getParameter (Event.EVENT_THREAD);
if (thread != null)
{
Thread eventThread = (Thread) thread;
diff --git a/libjava/classpath/gnu/classpath/jdwp/processor/ClassTypeCommandSet.java b/libjava/classpath/gnu/classpath/jdwp/processor/ClassTypeCommandSet.java
index f60da7b..a3a7ca0 100644
--- a/libjava/classpath/gnu/classpath/jdwp/processor/ClassTypeCommandSet.java
+++ b/libjava/classpath/gnu/classpath/jdwp/processor/ClassTypeCommandSet.java
@@ -106,8 +106,12 @@ public class ClassTypeCommandSet
Class clazz = refId.getType();
Class superClazz = clazz.getSuperclass();
- ReferenceTypeId clazzId = idMan.getReferenceTypeId(superClazz);
- clazzId.write(os);
+ if (superClazz == null) {
+ os.writeLong(0L);
+ } else {
+ ReferenceTypeId clazzId = idMan.getReferenceTypeId(superClazz);
+ clazzId.write(os);
+ }
}
private void executeSetValues(ByteBuffer bb, DataOutputStream os)
diff --git a/libjava/classpath/gnu/classpath/jdwp/processor/EventRequestCommandSet.java b/libjava/classpath/gnu/classpath/jdwp/processor/EventRequestCommandSet.java
index e4b1b60..59cfb94 100644
--- a/libjava/classpath/gnu/classpath/jdwp/processor/EventRequestCommandSet.java
+++ b/libjava/classpath/gnu/classpath/jdwp/processor/EventRequestCommandSet.java
@@ -147,7 +147,7 @@ public class EventRequestCommandSet
if (id == 0)
refId = null;
else
- refId = idMan.readReferenceTypeId(bb);
+ refId = idMan.getReferenceType(id);
boolean caught = (bb.get() == 0) ? false : true;
boolean unCaught = (bb.get() == 0) ? false : true;
filter = new ExceptionOnlyFilter(refId, caught, unCaught);
diff --git a/libjava/classpath/gnu/classpath/jdwp/processor/PacketProcessor.java b/libjava/classpath/gnu/classpath/jdwp/processor/PacketProcessor.java
index 9e281f2..4df3f47 100644
--- a/libjava/classpath/gnu/classpath/jdwp/processor/PacketProcessor.java
+++ b/libjava/classpath/gnu/classpath/jdwp/processor/PacketProcessor.java
@@ -1,6 +1,6 @@
/* PacketProcessor.java -- a thread which processes command packets
from the debugger
- Copyright (C) 2005 Free Software Foundation
+ Copyright (C) 2005, 2006 Free Software Foundation
This file is part of GNU Classpath.
@@ -137,6 +137,10 @@ public class PacketProcessor
*/
public Object run ()
{
+ // Notify initialization thread (gnu.classpath.jdwp.Jdwp) that
+ // the PacketProcessor thread is ready.
+ Jdwp.getDefault().subcomponentInitialized ();
+
try
{
while (!_shutdown)
@@ -144,7 +148,7 @@ public class PacketProcessor
_processOnePacket ();
}
}
- catch (IOException ex)
+ catch (Exception ex)
{
ex.printStackTrace();
}
diff --git a/libjava/classpath/gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java b/libjava/classpath/gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java
index ba36251..103199a 100644
--- a/libjava/classpath/gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java
+++ b/libjava/classpath/gnu/classpath/jdwp/processor/ThreadGroupReferenceCommandSet.java
@@ -103,8 +103,12 @@ public class ThreadGroupReferenceCommandSet
ObjectId oid = idMan.readObjectId(bb);
ThreadGroup group = (ThreadGroup) oid.getObject();
ThreadGroup parent = group.getParent();
- ObjectId parentId = idMan.getObjectId(parent);
- parentId.write(os);
+ if (parent == null) {
+ os.writeLong(0L);
+ } else {
+ ObjectId parentId = idMan.getObjectId(parent);
+ parentId.write(os);
+ }
}
private void executeChildren(ByteBuffer bb, DataOutputStream os)
diff --git a/libjava/classpath/gnu/classpath/jdwp/transport/JdwpConnection.java b/libjava/classpath/gnu/classpath/jdwp/transport/JdwpConnection.java
index f008bbd..82a2380 100644
--- a/libjava/classpath/gnu/classpath/jdwp/transport/JdwpConnection.java
+++ b/libjava/classpath/gnu/classpath/jdwp/transport/JdwpConnection.java
@@ -1,5 +1,5 @@
/* JdwpConnection.java -- A JDWP-speaking connection
- Copyright (C) 2005 Free Software Foundation
+ Copyright (C) 2005, 2006 Free Software Foundation
This file is part of GNU Classpath.
@@ -165,6 +165,10 @@ public class JdwpConnection
*/
public void run ()
{
+ // Notify initialization thread (gnu.classpath.jdwp.Jdwp) that
+ // the JdwpConnection thread is ready.
+ Jdwp.getDefault().subcomponentInitialized ();
+
while (!_shutdown)
{
try
diff --git a/libjava/classpath/gnu/classpath/jdwp/util/Location.java b/libjava/classpath/gnu/classpath/jdwp/util/Location.java
index 005b12c..89e81e5 100644
--- a/libjava/classpath/gnu/classpath/jdwp/util/Location.java
+++ b/libjava/classpath/gnu/classpath/jdwp/util/Location.java
@@ -94,18 +94,40 @@ public class Location
* @param os stream to write to
* @throws IOException when an error occurs writing to the stream
*/
- public void write(DataOutputStream os)
+ public void write(DataOutputStream os)
throws IOException
{
- VMIdManager idm = VMIdManager.getDefault();
- ClassReferenceTypeId crti = (ClassReferenceTypeId)
- idm.getReferenceTypeId(method.getDeclaringClass());
-
- crti.writeTagged(os);
- method.writeId(os);
- os.writeLong(index);
+ // check if this is an empty location
+ if (method != null)
+ {
+ VMIdManager idm = VMIdManager.getDefault();
+ ClassReferenceTypeId crti =
+ (ClassReferenceTypeId)
+ idm.getReferenceTypeId(method.getDeclaringClass());
+
+ crti.writeTagged(os);
+ method.writeId(os);
+ os.writeLong(index);
+ }
+ else
+ {
+ os.writeByte(1);
+ os.writeLong((long) 0);
+ os.writeLong((long) 0);
+ os.writeLong((long) 0);
+ }
}
-
+
+ /**
+ * Sets up an empty location
+ *
+ * @return new Location (setup as empty)
+ */
+ public static Location getEmptyLocation()
+ {
+ return new Location(null, 0);
+ }
+
/**
* Gets the method of this location
*
diff --git a/libjava/classpath/gnu/java/awt/ClasspathToolkit.java b/libjava/classpath/gnu/java/awt/ClasspathToolkit.java
index 1ec5664..968cc3b 100644
--- a/libjava/classpath/gnu/java/awt/ClasspathToolkit.java
+++ b/libjava/classpath/gnu/java/awt/ClasspathToolkit.java
@@ -1,5 +1,5 @@
/* ClasspathToolkit.java -- Abstract superclass for Classpath toolkits.
- Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+ Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -41,7 +41,6 @@ package gnu.java.awt;
import gnu.java.awt.EmbeddedWindow;
import gnu.java.awt.peer.ClasspathFontPeer;
import gnu.java.awt.peer.EmbeddedWindowPeer;
-import gnu.java.awt.peer.ClasspathTextLayoutPeer;
import gnu.java.security.action.SetAccessibleAction;
import java.awt.AWTException;
@@ -53,6 +52,7 @@ import java.awt.FontMetrics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
+import java.awt.Point;
import java.awt.Toolkit;
import java.awt.font.FontRenderContext;
import java.awt.image.ColorModel;
@@ -120,10 +120,6 @@ public abstract class ClasspathToolkit
*/
public abstract ClasspathFontPeer getClasspathFontPeer (String name, Map attrs);
- public abstract ClasspathTextLayoutPeer
- getClasspathTextLayoutPeer (AttributedString str, FontRenderContext frc);
-
-
/**
* Creates a {@link Font}, in a platform-specific manner.
*
@@ -193,6 +189,9 @@ public abstract class ClasspathToolkit
*/
public abstract Font createFont(int format, InputStream stream);
+ /**
+ * Creates a RobotPeer on a given GraphicsDevice.
+ */
public abstract RobotPeer createRobot (GraphicsDevice screen)
throws AWTException;
@@ -206,8 +205,24 @@ public abstract class ClasspathToolkit
/**
* Used to register ImageIO SPIs provided by the toolkit.
+ *
+ * Our default implementation does nothing.
*/
public void registerImageIOSpis(IIORegistry reg)
{
}
+
+ /**
+ * Returns the number of mouse buttons.
+ * (used by java.awt.MouseInfo).
+ *
+ * This dummy implementation returns -1 (no mouse).
+ * toolkit implementors should overload this method if possible.
+ * @since 1.5
+ */
+ public int getMouseNumberOfButtons()
+ {
+ return -1;
+ }
}
+
diff --git a/libjava/classpath/gnu/java/awt/dnd/GtkMouseDragGestureRecognizer.java b/libjava/classpath/gnu/java/awt/dnd/GtkMouseDragGestureRecognizer.java
new file mode 100644
index 0000000..1f0c3ad
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/dnd/GtkMouseDragGestureRecognizer.java
@@ -0,0 +1,172 @@
+/* GtkMouseDragGestureRecognizer.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.dnd;
+
+import java.awt.Component;
+import java.awt.Point;
+import java.awt.dnd.DnDConstants;
+import java.awt.dnd.DragGestureListener;
+import java.awt.dnd.DragSource;
+import java.awt.dnd.MouseDragGestureRecognizer;
+import java.awt.event.MouseEvent;
+
+public class GtkMouseDragGestureRecognizer
+ extends MouseDragGestureRecognizer
+{
+
+ public GtkMouseDragGestureRecognizer (DragSource ds)
+ {
+ this(ds, null, 0, null);
+ }
+
+ public GtkMouseDragGestureRecognizer (DragSource ds, Component c)
+ {
+ this (ds, c, 0, null);
+ }
+
+ public GtkMouseDragGestureRecognizer (DragSource ds, Component c, int act)
+ {
+ this(ds, c, act, null);
+ }
+
+ public GtkMouseDragGestureRecognizer (DragSource ds, Component c, int act,
+ DragGestureListener dgl)
+ {
+ super(ds, c, act, dgl);
+ }
+
+ public void registerListeners ()
+ {
+ super.registerListeners();
+ }
+
+ public void unregisterListeners ()
+ {
+ super.unregisterListeners();
+ }
+
+ public void mouseClicked (MouseEvent e)
+ {
+ // Nothing to do here.
+ }
+
+ public void mousePressed (MouseEvent e)
+ {
+ events.clear();
+ if (getDropActionFromEvent(e) != DnDConstants.ACTION_NONE)
+ appendEvent(e);
+ }
+
+ public void mouseReleased (MouseEvent e)
+ {
+ events.clear();
+ }
+
+ public void mouseEntered (MouseEvent e)
+ {
+ events.clear();
+ }
+
+ public void mouseExited(MouseEvent e)
+ {
+ if (!events.isEmpty())
+ if (getDropActionFromEvent(e) == DnDConstants.ACTION_NONE)
+ events.clear();
+ }
+
+ public void mouseDragged(MouseEvent e)
+ {
+ if (!events.isEmpty())
+ {
+ int act = getDropActionFromEvent(e);
+
+ if (act == DnDConstants.ACTION_NONE)
+ return;
+
+ Point origin = ((MouseEvent) events.get(0)).getPoint();
+ Point current = e.getPoint();
+ int dx = Math.abs(origin.x - current.x);
+ int dy = Math.abs(origin.y - current.y);
+ int threshold = DragSource.getDragThreshold();
+
+ if (dx > threshold || dy > threshold)
+ fireDragGestureRecognized(act, origin);
+ else
+ appendEvent(e);
+ }
+ }
+
+ public void mouseMoved (MouseEvent e)
+ {
+ // Nothing to do here.
+ }
+
+ private int getDropActionFromEvent(MouseEvent e)
+ {
+ int modEx = e.getModifiersEx();
+ int buttons = modEx & (MouseEvent.BUTTON1_DOWN_MASK
+ | MouseEvent.BUTTON2_DOWN_MASK | MouseEvent.BUTTON3_DOWN_MASK);
+ if (!(buttons == MouseEvent.BUTTON1_DOWN_MASK ||
+ buttons == MouseEvent.BUTTON2_DOWN_MASK))
+ return DnDConstants.ACTION_NONE;
+
+ // Convert modifier to a drop action
+ int sourceActions = getSourceActions();
+ int mod = modEx
+ & (MouseEvent.SHIFT_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK);
+ switch (mod)
+ {
+ case MouseEvent.SHIFT_DOWN_MASK | MouseEvent.CTRL_DOWN_MASK:
+ return DnDConstants.ACTION_LINK & sourceActions;
+ case MouseEvent.CTRL_DOWN_MASK:
+ return DnDConstants.ACTION_COPY & sourceActions;
+ case MouseEvent.SHIFT_DOWN_MASK:
+ return DnDConstants.ACTION_MOVE & sourceActions;
+ default:
+ if ((sourceActions & DnDConstants.ACTION_MOVE) != 0)
+ return DnDConstants.ACTION_MOVE & sourceActions;
+ else if ((sourceActions & DnDConstants.ACTION_COPY) != 0)
+ return DnDConstants.ACTION_COPY & sourceActions;
+ else if ((sourceActions & DnDConstants.ACTION_LINK) != 0)
+ return DnDConstants.ACTION_LINK & sourceActions;
+ }
+
+ return DnDConstants.ACTION_NONE & sourceActions;
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDragSourceContextPeer.java b/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDragSourceContextPeer.java
new file mode 100644
index 0000000..4f92298
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDragSourceContextPeer.java
@@ -0,0 +1,174 @@
+/* GtkDragSourceContextPeer.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.dnd.peer.gtk;
+
+import gnu.java.awt.peer.gtk.GtkGenericPeer;
+
+import java.awt.Component;
+import java.awt.Cursor;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.dnd.DragGestureEvent;
+import java.awt.dnd.DragSourceContext;
+import java.awt.dnd.DragSourceDragEvent;
+import java.awt.dnd.DragSourceDropEvent;
+import java.awt.dnd.DragSourceEvent;
+import java.awt.dnd.InvalidDnDOperationException;
+import java.awt.dnd.peer.DragSourceContextPeer;
+import java.awt.peer.ComponentPeer;
+import java.awt.peer.LightweightPeer;
+
+public class GtkDragSourceContextPeer
+ extends GtkGenericPeer
+ implements DragSourceContextPeer
+{
+ private ComponentPeer peer;
+ private Cursor cursor;
+ private DragSourceContext context;
+
+ native void nativeStartDrag(Image i, int x, int y, int action, String target);
+ native void connectSignals(ComponentPeer comp);
+ native void create(ComponentPeer comp);
+ native void nativeSetCursor(int cursor);
+
+ public GtkDragSourceContextPeer(DragGestureEvent e)
+ {
+ super(e.getComponent());
+ Component comp = e.getComponent();
+ peer = getComponentPeer(comp);
+
+ create(peer);
+ connectSignals(peer);
+ cursor = comp.getCursor();
+ }
+
+ ComponentPeer getComponentPeer(Component c)
+ {
+ Component curr = c;
+ while (curr.getPeer() instanceof LightweightPeer)
+ curr = curr.getParent();
+
+ if (curr != null)
+ return curr.getPeer();
+ return null;
+ }
+
+ public void startDrag(DragSourceContext context, Cursor c, Image i, Point p)
+ throws InvalidDnDOperationException
+ {
+ this.context = context;
+
+ if (p == null)
+ p = new Point();
+
+ // FIXME: use proper DataFlavor, not "text/plain".
+ // Also, add check to determine if dragging.
+
+ setCursor(c);
+ nativeStartDrag(i, p.x, p.y, context.getTrigger().getDragAction(),
+ "text/plain");
+ }
+
+ public Cursor getCursor()
+ {
+ return cursor;
+ }
+
+ public void setCursor(Cursor c) throws InvalidDnDOperationException
+ {
+ if (c != null)
+ {
+ nativeSetCursor(c.getType());
+ cursor = c;
+ }
+ }
+
+ public void transferablesFlavorsChanged()
+ {
+ // Nothing to do here.
+ }
+
+ /**
+ * Called from native code.
+ */
+
+ public void dragEnter(int action, int modifiers)
+ {
+ context.dragEnter(new DragSourceDragEvent(context, action,
+ action
+ & context.getSourceActions(),
+ modifiers));
+ }
+
+ public void dragExit(int action, int x, int y)
+ {
+ context.dragExit(new DragSourceEvent(context, x, y));
+ }
+
+ public void dragDropEnd(int action, boolean success, int x, int y)
+ {
+ context.dragDropEnd(new DragSourceDropEvent(context, action, success, x, y));
+ }
+
+ public void dragMouseMoved(int action, int modifiers)
+ {
+ context.dragMouseMoved(new DragSourceDragEvent(context,
+ action,
+ action
+ & context.getSourceActions(),
+ modifiers));
+ }
+
+ public void dragOver(int action, int modifiers)
+ {
+ context.dragOver(new DragSourceDragEvent(context, action,
+ action
+ & context.getSourceActions(),
+ modifiers));
+ }
+
+ public void dragActionChanged(int newAction, int modifiers)
+ {
+ context.dropActionChanged(new DragSourceDragEvent(context,
+ newAction,
+ newAction
+ & context.getSourceActions(),
+ modifiers));
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDropTargetContextPeer.java b/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDropTargetContextPeer.java
new file mode 100644
index 0000000..50cd95d
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDropTargetContextPeer.java
@@ -0,0 +1,125 @@
+/* GtkDropTargetContextPeer.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.dnd.peer.gtk;
+
+import gnu.java.awt.peer.gtk.GtkGenericPeer;
+
+import java.awt.datatransfer.DataFlavor;
+import java.awt.datatransfer.Transferable;
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.InvalidDnDOperationException;
+import java.awt.dnd.peer.DropTargetContextPeer;
+
+public class GtkDropTargetContextPeer
+ extends GtkGenericPeer
+ implements DropTargetContextPeer
+{
+
+ public GtkDropTargetContextPeer()
+ {
+ super(null);
+ }
+
+ public void setTargetActions(int actions)
+ {
+ // FIXME: Not Implemented
+
+ }
+
+ public int getTargetActions()
+ {
+ // FIXME: Not Implemented
+ return 0;
+ }
+
+ public DropTarget getDropTarget()
+ {
+ // FIXME: Not Implemented
+ return null;
+ }
+
+ public DataFlavor[] getTransferDataFlavors()
+ {
+ // FIXME: Not Implemented
+ return null;
+ }
+
+ public Transferable getTransferable() throws InvalidDnDOperationException
+ {
+ // FIXME: Not Implemented
+ return null;
+ }
+
+ public boolean isTransferableJVMLocal()
+ {
+ // FIXME: Not Implemented
+ return false;
+ }
+
+ public void acceptDrag(int dragAction)
+ {
+ // FIXME: Not Implemented
+
+ }
+
+ public void rejectDrag()
+ {
+ // FIXME: Not Implemented
+
+ }
+
+ public void acceptDrop(int dropAction)
+ {
+ // FIXME: Not Implemented
+
+ }
+
+ public void rejectDrop()
+ {
+ // FIXME: Not Implemented
+
+ }
+
+ public void dropComplete(boolean success)
+ {
+ // FIXME: Not Implemented
+
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDropTargetPeer.java b/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDropTargetPeer.java
new file mode 100644
index 0000000..88b75ad
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/dnd/peer/gtk/GtkDropTargetPeer.java
@@ -0,0 +1,68 @@
+/* GtkDropTargetPeer.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.dnd.peer.gtk;
+
+import gnu.java.awt.peer.gtk.GtkGenericPeer;
+
+import java.awt.dnd.DropTarget;
+import java.awt.dnd.peer.DropTargetPeer;
+
+public class GtkDropTargetPeer
+ extends GtkGenericPeer
+ implements DropTargetPeer
+{
+
+ public GtkDropTargetPeer()
+ {
+ super(null);
+ }
+
+ public void addDropTarget(DropTarget target)
+ {
+ // FIXME: Not Implemented
+
+ }
+
+ public void removeDropTarget(DropTarget target)
+ {
+ // FIXME: Not Implemented
+
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/awt/java2d/AbstractGraphics2D.java b/libjava/classpath/gnu/java/awt/java2d/AbstractGraphics2D.java
index f057d8b..9d01724 100644
--- a/libjava/classpath/gnu/java/awt/java2d/AbstractGraphics2D.java
+++ b/libjava/classpath/gnu/java/awt/java2d/AbstractGraphics2D.java
@@ -39,6 +39,7 @@ package gnu.java.awt.java2d;
import java.awt.AWTError;
import java.awt.AlphaComposite;
+import java.awt.AWTPermission;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
@@ -72,6 +73,7 @@ import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorModel;
+import java.awt.image.DataBuffer;
import java.awt.image.ImageObserver;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
@@ -144,7 +146,7 @@ public abstract class AbstractGraphics2D
/**
* The transformation for this Graphics2D instance
*/
- private AffineTransform transform;
+ protected AffineTransform transform;
/**
* The foreground.
@@ -539,6 +541,15 @@ public abstract class AbstractGraphics2D
*/
public void setComposite(Composite comp)
{
+ if (! (comp instanceof AlphaComposite))
+ {
+ // FIXME: this check is only required "if this Graphics2D
+ // context is drawing to a Component on the display screen".
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPermission(new AWTPermission("readDisplayPixels"));
+ }
+
composite = comp;
if (! (comp.equals(AlphaComposite.SrcOver)))
isOptimized = false;
@@ -2054,7 +2065,34 @@ public abstract class AbstractGraphics2D
*
* @return the destination raster
*/
- protected abstract WritableRaster getDestinationRaster();
+ protected WritableRaster getDestinationRaster()
+ {
+ // TODO: Ideally we would fetch the xdrawable's surface pixels for
+ // initialization of the raster.
+ Rectangle db = getDeviceBounds();
+ if (destinationRaster == null)
+ {
+ int[] bandMasks = new int[]{ 0xFF0000, 0xFF00, 0xFF };
+ destinationRaster = Raster.createPackedRaster(DataBuffer.TYPE_INT,
+ db.width, db.height,
+ bandMasks, null);
+ // Initialize raster with white.
+ int x0 = destinationRaster.getMinX();
+ int x1 = destinationRaster.getWidth() + x0;
+ int y0 = destinationRaster.getMinY();
+ int y1 = destinationRaster.getHeight() + y0;
+ int numBands = destinationRaster.getNumBands();
+ for (int y = y0; y < y1; y++)
+ {
+ for (int x = x0; x < x1; x++)
+ {
+ for (int b = 0; b < numBands; b++)
+ destinationRaster.setSample(x, y, b, 255);
+ }
+ }
+ }
+ return destinationRaster;
+ }
/**
* Notifies the backend that the raster has changed in the specified
diff --git a/libjava/classpath/gnu/java/awt/java2d/CubicSegment.java b/libjava/classpath/gnu/java/awt/java2d/CubicSegment.java
index 1e568f7..bf66be8 100644
--- a/libjava/classpath/gnu/java/awt/java2d/CubicSegment.java
+++ b/libjava/classpath/gnu/java/awt/java2d/CubicSegment.java
@@ -39,6 +39,7 @@ exception statement from your version. */
package gnu.java.awt.java2d;
+import java.awt.geom.CubicCurve2D;
import java.awt.geom.Point2D;
/**
@@ -78,34 +79,89 @@ public class CubicSegment extends Segment
*/
public Object clone()
{
- return new CubicSegment(P1.getX(), P1.getY(), cp1.getX(), cp1.getY(),
- cp2.getX(), cp2.getY(), P2.getX(), P2.getY());
+ CubicSegment segment = null;
+
+ try
+ {
+ segment = (CubicSegment) super.clone();
+
+ segment.P1 = (Point2D) P1.clone();
+ segment.P2 = (Point2D) P2.clone();
+ segment.cp1 = (Point2D) cp1.clone();
+ segment.cp2 = (Point2D) cp2.clone();
+ }
+ catch (CloneNotSupportedException cnse)
+ {
+ InternalError ie = new InternalError();
+ ie.initCause(cnse);
+ throw ie;
+ }
+
+ return segment;
}
/**
- * Get the "top" and "bottom" segments of this segment.
- * First array element is p0 + normal, second is p0 - normal.
+ * Get the "top" and "bottom" segments of this segment. First array element is
+ * p0 + normal, second is p0 - normal.
*/
public Segment[] getDisplacedSegments(double radius)
{
+ // It is, apparently, impossible to derive a curve parallel to a bezier
+ // curve (unless it's a straight line), so we have no choice but to
+ // approximate the displaced segments. Similar to FlattenPathIterator.
+
+ Segment segmentTop = null;
+ Segment segmentBottom = null;
this.radius = radius;
- double x0 = P1.getX();
- double y0 = P1.getY();
- double x1 = cp1.getX();
- double y1 = cp1.getY();
- double x2 = cp2.getX();
- double y2 = cp2.getY();
- double x3 = P2.getX();
- double y3 = P2.getY();
- double[] p1 = normal(x0, y0, x1, y1);
- double[] p2 = normal(x2, y2, x3, y3);
-
- // FIXME: Doesn't compile.
- // return new Segment[]{s1, s2};
- return new Segment[0];
+ CubicCurve2D[] curves = new CubicCurve2D[10];
+ curves[0] = new CubicCurve2D.Double(P1.getX(), P1.getY(), cp1.getX(),
+ cp1.getY(), cp2.getX(), cp2.getY(),
+ P2.getX(), P2.getY());
+ int numCurves = 1;
+
+ // Hard-coded a recursion limit of 10 and flatness of 1... should we make
+ // this an option somewhere?
+ while (numCurves > 0)
+ {
+ // The curve is flat enough, or we've reached our recursion limit,
+ // so take the current start/end points and add it as a line segment
+ // to our final approximated curves
+ if (curves[numCurves - 1].getFlatnessSq() <= (radius / 3) || numCurves == 10)
+ {
+ Segment[] displaced = new LineSegment(
+ curves[numCurves - 1].getP1(),
+ curves[numCurves - 1].getP2()).getDisplacedSegments(radius);
+ if (segmentTop == null)
+ {
+ segmentTop = displaced[0];
+ segmentBottom = displaced[1];
+ }
+ else
+ {
+ segmentTop.add(displaced[0]);
+ segmentBottom.add(displaced[1]);
+ }
+ numCurves--;
+ }
+
+ // Otherwise, subdivide again and continue
+ else
+ {
+ CubicCurve2D left = new CubicCurve2D.Double();
+ CubicCurve2D right = new CubicCurve2D.Double();
+ curves[numCurves - 1].subdivide(left, right);
+ curves[numCurves - 1] = right;
+ curves[numCurves] = left;
+ curves[numCurves - 1] = right;
+ curves[numCurves] = left;
+ numCurves++;
+ }
+ }
+
+ return new Segment[] { segmentTop, segmentBottom };
}
-
+
public void reverse()
{
Point2D temp = P1;
@@ -116,12 +172,12 @@ public class CubicSegment extends Segment
cp2 = temp;
}
- public double[] first()
+ public double[] cp1()
{
return new double[]{cp1.getX(), cp1.getY()};
}
- public double[] last()
+ public double[] cp2()
{
return new double[]{cp2.getX(), cp2.getY()};
}
diff --git a/libjava/classpath/gnu/java/awt/java2d/LineSegment.java b/libjava/classpath/gnu/java/awt/java2d/LineSegment.java
index 9c0bcc7..0395fd0 100644
--- a/libjava/classpath/gnu/java/awt/java2d/LineSegment.java
+++ b/libjava/classpath/gnu/java/awt/java2d/LineSegment.java
@@ -62,7 +62,22 @@ public class LineSegment extends Segment
*/
public Object clone()
{
- return new LineSegment(P1, P2);
+ LineSegment segment = null;
+
+ try
+ {
+ segment = (LineSegment) super.clone();
+ segment.P1 = (Point2D) P1.clone();
+ segment.P2 = (Point2D) P2.clone();
+ }
+ catch (CloneNotSupportedException cnse)
+ {
+ InternalError ie = new InternalError();
+ ie.initCause(cnse);
+ throw ie;
+ }
+
+ return segment;
}
/**
@@ -91,12 +106,12 @@ public class LineSegment extends Segment
P2 = p;
}
- public double[] first()
+ public double[] cp1()
{
return new double[]{P2.getX(), P2.getY()};
}
- public double[] last()
+ public double[] cp2()
{
return new double[]{P1.getX(), P1.getY()};
}
diff --git a/libjava/classpath/gnu/java/awt/java2d/QuadSegment.java b/libjava/classpath/gnu/java/awt/java2d/QuadSegment.java
index 9c15a8c..5e15fe8 100644
--- a/libjava/classpath/gnu/java/awt/java2d/QuadSegment.java
+++ b/libjava/classpath/gnu/java/awt/java2d/QuadSegment.java
@@ -88,8 +88,24 @@ public class QuadSegment extends Segment
*/
public Object clone()
{
- return new QuadSegment(P1.getX(), P1.getY(), cp.getX(), cp.getY(),
- P2.getX(), P2.getY());
+ QuadSegment segment = null;
+
+ try
+ {
+ segment = (QuadSegment) super.clone();
+
+ segment.P1 = (Point2D) P1.clone();
+ segment.P2 = (Point2D) P2.clone();
+ segment.cp = (Point2D) cp.clone();
+ }
+ catch (CloneNotSupportedException cnse)
+ {
+ InternalError ie = new InternalError();
+ ie.initCause(cnse);
+ throw ie;
+ }
+
+ return segment;
}
/**
@@ -201,12 +217,12 @@ public class QuadSegment extends Segment
P2 = p;
}
- public double[] first()
+ public double[] cp1()
{
return new double[]{cp.getX(), cp.getY()};
}
- public double[] last()
+ public double[] cp2()
{
return new double[]{cp.getX(), cp.getY()};
}
diff --git a/libjava/classpath/gnu/java/awt/java2d/Segment.java b/libjava/classpath/gnu/java/awt/java2d/Segment.java
index 9a985f6..df1f676 100644
--- a/libjava/classpath/gnu/java/awt/java2d/Segment.java
+++ b/libjava/classpath/gnu/java/awt/java2d/Segment.java
@@ -42,24 +42,38 @@ import java.awt.geom.Point2D;
public abstract class Segment implements Cloneable
{
- // segment type, PathIterator segment types are used.
+ // Start and end points of THIS segment
public Point2D P1;
public Point2D P2;
+
+ // Segments can be linked together internally as a linked list
+ public Segment first;
public Segment next;
public Segment last;
+
+ // Half the stroke width
protected double radius;
+ /**
+ * Create a new, empty segment
+ */
public Segment()
{
P1 = P2 = null;
+ first = this;
next = null;
last = this;
}
+ /**
+ * Add a segment to the polygon
+ * @param newsegment segment to add
+ */
public void add(Segment newsegment)
{
+ newsegment.first = first;
last.next = newsegment;
- last = last.next;
+ last = last.next.last;
}
/**
@@ -68,6 +82,7 @@ public abstract class Segment implements Cloneable
public void reverseAll()
{
reverse();
+ first = last;
Segment v = next;
Segment former = this;
next = null;
@@ -91,7 +106,7 @@ public abstract class Segment implements Cloneable
/**
* Get the normal vector to the slope of the line.
- * Returns: 0.5*width*(norm of derivative of the (x0,y0)-(x1,y1) vector)
+ * @return vector of length radius, normal to the (x0,y0)-(x1,y1) vector)
*/
protected double[] normal(double x0, double y0, double x1, double y1)
{
@@ -117,6 +132,9 @@ public abstract class Segment implements Cloneable
return new double[]{ dx, dy };
}
+ /**
+ * Reverse the current segment
+ */
public abstract void reverse();
/**
@@ -125,7 +143,16 @@ public abstract class Segment implements Cloneable
*/
public abstract Segment[] getDisplacedSegments(double radius);
- public abstract double[] first();
- public abstract double[] last();
+ /**
+ * Returns the coordinates of the first control point, or the start point
+ * for a line segment.
+ */
+ public abstract double[] cp1();
+
+ /**
+ * Returns the coordinates of the second control point, or the end point
+ * for a line segment.
+ */
+ public abstract double[] cp2();
}
diff --git a/libjava/classpath/gnu/java/awt/peer/ClasspathFontPeer.java b/libjava/classpath/gnu/java/awt/peer/ClasspathFontPeer.java
index 78ab3a9..dad7bb0 100644
--- a/libjava/classpath/gnu/java/awt/peer/ClasspathFontPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/ClasspathFontPeer.java
@@ -145,7 +145,8 @@ public abstract class ClasspathFontPeer
uname.equals ("SERIF") ||
uname.equals ("MONOSPACED") ||
uname.equals ("DIALOG") ||
- uname.equals ("DIALOGINPUT"));
+ uname.equals ("DIALOGINPUT") ||
+ uname.equals ("DEFAULT"));
}
protected static String logicalFontNameToFaceName (String name)
@@ -161,6 +162,8 @@ public abstract class ClasspathFontPeer
return "Helvetica";
else if (uname.equals ("DIALOGINPUT"))
return "Helvetica";
+ else if (uname.equals ("DEFAULT"))
+ return "Dialog.plain";
else
return "Helvetica";
}
@@ -233,7 +236,7 @@ public abstract class ClasspathFontPeer
family = (String) attribs.get (TextAttribute.FAMILY);
if (name == null)
- name = "SansSerif";
+ name = "Default";
if (attribs.containsKey (TextAttribute.WEIGHT))
{
diff --git a/libjava/classpath/gnu/java/awt/peer/ClasspathTextLayoutPeer.java b/libjava/classpath/gnu/java/awt/peer/ClasspathTextLayoutPeer.java
deleted file mode 100644
index 70df2ef..0000000
--- a/libjava/classpath/gnu/java/awt/peer/ClasspathTextLayoutPeer.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/* ClasspathTextLayoutPeer.java
- Copyright (C) 2003 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package gnu.java.awt.peer;
-
-import java.awt.Graphics2D;
-import java.awt.Shape;
-import java.awt.font.TextHitInfo;
-import java.awt.font.TextLayout;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.Rectangle2D;
-
-/**
- * @author Graydon Hoare
- */
-
-public interface ClasspathTextLayoutPeer
-{
- TextHitInfo getStrongCaret (TextHitInfo hit1,
- TextHitInfo hit2);
-
- void draw (Graphics2D g2, float x, float y);
-
- byte getBaseline ();
-
- boolean isLeftToRight ();
- boolean isVertical ();
-
- float getAdvance ();
- float getAscent ();
- float getDescent ();
- float getLeading ();
-
- int getCharacterCount ();
- byte getCharacterLevel (int index);
-
- float[] getBaselineOffsets ();
- Shape getBlackBoxBounds (int firstEndpoint, int secondEndpoint);
- Rectangle2D getBounds ();
-
- float[] getCaretInfo (TextHitInfo hit, Rectangle2D bounds);
- Shape getCaretShape (TextHitInfo hit, Rectangle2D bounds);
- Shape[] getCaretShapes (int offset, Rectangle2D bounds,
- TextLayout.CaretPolicy policy);
-
- Shape getLogicalHighlightShape (int firstEndpoint, int secondEndpoint,
- Rectangle2D bounds);
- int[] getLogicalRangesForVisualSelection (TextHitInfo firstEndpoint,
- TextHitInfo secondEndpoint);
-
- TextHitInfo getNextLeftHit (int offset, TextLayout.CaretPolicy policy);
- TextHitInfo getNextRightHit (int offset, TextLayout.CaretPolicy policy);
- TextHitInfo hitTestChar (float x, float y, Rectangle2D bounds);
- TextHitInfo getVisualOtherHit (TextHitInfo hit);
-
- float getVisibleAdvance ();
- Shape getOutline (AffineTransform tx);
- Shape getVisualHighlightShape (TextHitInfo firstEndpoint,
- TextHitInfo secondEndpoint,
- Rectangle2D bounds);
-
- TextLayout getJustifiedLayout (float justificationWidth);
- void handleJustify (float justificationWidth);
-
- Object clone ();
- int hashCode ();
- boolean equals (ClasspathTextLayoutPeer tl);
- String toString ();
-}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/BufferedImageGraphics.java b/libjava/classpath/gnu/java/awt/peer/gtk/BufferedImageGraphics.java
index d9d300d..6a74eab 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/BufferedImageGraphics.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/BufferedImageGraphics.java
@@ -40,10 +40,8 @@ package gnu.java.awt.peer.gtk;
import java.awt.Color;
import java.awt.Graphics;
-import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
-import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.GlyphVector;
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/CairoGraphics2D.java b/libjava/classpath/gnu/java/awt/peer/gtk/CairoGraphics2D.java
index 9f8f494..b665f56 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/CairoGraphics2D.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/CairoGraphics2D.java
@@ -40,6 +40,7 @@ package gnu.java.awt.peer.gtk;
import gnu.java.awt.ClasspathToolkit;
+import java.awt.AWTPermission;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
@@ -52,11 +53,11 @@ import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Paint;
+import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
-import java.awt.Polygon;
import java.awt.TexturePaint;
import java.awt.Toolkit;
import java.awt.font.FontRenderContext;
@@ -65,8 +66,8 @@ import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
+import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
-import java.awt.geom.Line2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
@@ -322,6 +323,11 @@ public abstract class CairoGraphics2D extends Graphics2D
* Set the current transform matrix
*/
private native void cairoSetMatrix(long pointer, double[] m);
+
+ /**
+ * Scaling method
+ */
+ private native void cairoScale(long pointer, double x, double y);
/**
* Set the compositing operator
@@ -369,6 +375,18 @@ public abstract class CairoGraphics2D extends Graphics2D
*/
private native void cairoRectangle(long pointer, double x, double y,
double width, double height);
+
+ /**
+ * Appends an arc to the current path
+ */
+ private native void cairoArc(long pointer, double x, double y,
+ double radius, double angle1, double angle2);
+
+ /**
+ * Save / restore a cairo path
+ */
+ private native void cairoSave(long pointer);
+ private native void cairoRestore(long pointer);
/**
* New current path
@@ -427,6 +445,46 @@ public abstract class CairoGraphics2D extends Graphics2D
*/
private native void cairoSurfaceSetFilter(long pointer, int filter);
+ /**
+ * Draws a line from (x1,y1) to (x2,y2).
+ *
+ * @param pointer the native pointer
+ *
+ * @param x1 the x coordinate of the starting point
+ * @param y1 the y coordinate of the starting point
+ * @param x2 the x coordinate of the end point
+ * @param y2 the y coordinate of the end point
+ */
+ private native void cairoDrawLine(long pointer, double x1, double y1,
+ double x2, double y2);
+
+ /**
+ * Draws a rectangle at starting point (x,y) and with the specified width
+ * and height.
+ *
+ * @param pointer the native pointer
+ * @param x the x coordinate of the upper left corner
+ * @param y the y coordinate of the upper left corner
+ * @param w the width of the rectangle
+ * @param h the height of the rectangle
+ */
+ private native void cairoDrawRect(long pointer, double x, double y, double w,
+ double h);
+
+ /**
+ * Fills a rectangle at starting point (x,y) and with the specified width
+ * and height.
+ *
+ * @param pointer the native pointer
+ * @param x the x coordinate of the upper left corner
+ * @param y the y coordinate of the upper left corner
+ * @param w the width of the rectangle
+ * @param h the height of the rectangle
+ */
+ private native void cairoFillRect(long pointer, double x, double y, double w,
+ double h);
+
+
///////////////////////// TRANSFORMS ///////////////////////////////////
/**
* Set the current transform
@@ -625,8 +683,8 @@ public abstract class CairoGraphics2D extends Graphics2D
int width = (int) tp.getAnchorRect().getWidth();
int height = (int) tp.getAnchorRect().getHeight();
- double scaleX = (width+1) / (double) img.getWidth();
- double scaleY = (height+1) / (double) img.getHeight();
+ double scaleX = width / (double) img.getWidth();
+ double scaleY = height / (double) img.getHeight();
AffineTransform at = new AffineTransform(scaleX, 0, 0, scaleY, 0, 0);
AffineTransformOp op = new AffineTransformOp(at, getRenderingHints());
@@ -737,7 +795,7 @@ public abstract class CairoGraphics2D extends Graphics2D
else
{
GeneralPath p = new GeneralPath();
- PathIterator pi = clip.getPathIterator(new AffineTransform());
+ PathIterator pi = clip.getPathIterator(null);
p.append(pi, false);
return p;
}
@@ -847,6 +905,12 @@ public abstract class CairoGraphics2D extends Graphics2D
}
else
{
+ // FIXME: this check is only required "if this Graphics2D
+ // context is drawing to a Component on the display screen".
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPermission(new AWTPermission("readDisplayPixels"));
+
// FIXME: implement general Composite support
throw new java.lang.UnsupportedOperationException();
}
@@ -857,54 +921,79 @@ public abstract class CairoGraphics2D extends Graphics2D
public void draw(Shape s)
{
if ((stroke != null && ! (stroke instanceof BasicStroke))
- || (comp instanceof AlphaComposite
- && ((AlphaComposite) comp).getAlpha() != 1.0))
+ || (comp instanceof AlphaComposite && ((AlphaComposite) comp).getAlpha() != 1.0))
{
- // FIXME: This is a hack to work around BasicStrokes's current
- // limitations wrt cubic curves.
- // See CubicSegment.getDisplacedSegments().
- if (stroke instanceof BasicStroke)
- {
- PathIterator flatten = s.getPathIterator(new AffineTransform(),
- 1.0);
- GeneralPath p = new GeneralPath();
- p.append(flatten, false);
- s = p;
- }
- fill(stroke.createStrokedShape(s));
- return;
+ // Cairo doesn't support stroking with alpha, so we create the stroked
+ // shape and fill with alpha instead
+ fill(stroke.createStrokedShape(s));
+ return;
}
- cairoNewPath(nativePointer);
-
- if (s instanceof Rectangle2D)
- {
- Rectangle2D r = (Rectangle2D) s;
- cairoRectangle(nativePointer, shifted(r.getX(), shiftDrawCalls),
- shifted(r.getY(), shiftDrawCalls), r.getWidth(),
- r.getHeight());
- }
- else
- walkPath(s.getPathIterator(null), shiftDrawCalls);
+ createPath(s);
cairoStroke(nativePointer);
}
public void fill(Shape s)
{
+ createPath(s);
+
+ double alpha = 1.0;
+ if (comp instanceof AlphaComposite)
+ alpha = ((AlphaComposite) comp).getAlpha();
+ cairoFill(nativePointer, alpha);
+ }
+
+ private void createPath(Shape s)
+ {
cairoNewPath(nativePointer);
+
+ // Optimize rectangles, since there is a direct Cairo function
if (s instanceof Rectangle2D)
{
- Rectangle2D r = (Rectangle2D) s;
- cairoRectangle(nativePointer, r.getX(), r.getY(), r.getWidth(),
+ Rectangle2D r = (Rectangle2D) s;
+ cairoRectangle(nativePointer, shifted(r.getX(), shiftDrawCalls),
+ shifted(r.getY(), shiftDrawCalls), r.getWidth(),
r.getHeight());
}
- else
- walkPath(s.getPathIterator(null), false);
- double alpha = 1.0;
- if (comp instanceof AlphaComposite)
- alpha = ((AlphaComposite) comp).getAlpha();
- cairoFill(nativePointer, alpha);
+ // We can optimize ellipses too; however we don't bother optimizing arcs:
+ // the iterator is fast enough (an ellipse requires 5 steps using the
+ // iterator, while most arcs are only 2-3)
+ else if (s instanceof Ellipse2D)
+ {
+ Ellipse2D e = (Ellipse2D) s;
+
+ double radius = Math.min(e.getHeight(), e.getWidth()) / 2;
+
+ // Cairo only draws circular shapes, but we can use a stretch to make
+ // them into ellipses
+ double xscale = 1, yscale = 1;
+ if (e.getHeight() != e.getWidth())
+ {
+ cairoSave(nativePointer);
+
+ if (e.getHeight() < e.getWidth())
+ xscale = e.getWidth() / (radius * 2);
+ else
+ yscale = e.getHeight() / (radius * 2);
+
+ if (xscale != 1 || yscale != 1)
+ cairoScale(nativePointer, xscale, yscale);
+ }
+
+ cairoArc(nativePointer,
+ shifted(e.getCenterX() / xscale, shiftDrawCalls),
+ shifted(e.getCenterY() / yscale, shiftDrawCalls), radius, 0,
+ Math.PI * 2);
+
+ if (xscale != 1 || yscale != 1)
+ cairoRestore(nativePointer);
+ }
+
+ // All other shapes are broken down and drawn in steps using the
+ // PathIterator
+ else
+ walkPath(s.getPathIterator(null), shiftDrawCalls);
}
/**
@@ -940,12 +1029,19 @@ public abstract class CairoGraphics2D extends Graphics2D
public void drawLine(int x1, int y1, int x2, int y2)
{
- draw(new Line2D.Double(x1, y1, x2, y2));
+ // The coordinates being pairwise identical means one wants
+ // to draw a single pixel. This is emulated by drawing
+ // a one pixel sized rectangle.
+ if (x1 == x2 && y1 == y2)
+ cairoFillRect(nativePointer, x1, y1, 1, 1);
+ else
+ cairoDrawLine(nativePointer, x1 + 0.5, y1 + 0.5, x2 + 0.5, y2 + 0.5);
}
public void drawRect(int x, int y, int width, int height)
{
- draw(new Rectangle(x, y, width, height));
+ cairoDrawRect(nativePointer, shifted(x, shiftDrawCalls),
+ shifted(y, shiftDrawCalls), width, height);
}
public void fillArc(int x, int y, int width, int height, int startAngle,
@@ -958,7 +1054,7 @@ public abstract class CairoGraphics2D extends Graphics2D
public void fillRect(int x, int y, int width, int height)
{
- fill(new Rectangle(x, y, width, height));
+ cairoFillRect(nativePointer, x, y, width, height);
}
public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
@@ -1137,6 +1233,9 @@ public abstract class CairoGraphics2D extends Graphics2D
if (img == null)
return false;
+ if (xform == null)
+ xform = new AffineTransform();
+
// In this case, xform is an AffineTransform that transforms bounding
// box of the specified image from image space to user space. However
// when we pass this transform to cairo, cairo will use this transform
@@ -1160,6 +1259,7 @@ public abstract class CairoGraphics2D extends Graphics2D
// Note - this can get us in trouble when the gdk lock is re-acquired.
// for example by VolatileImage. See ComponentGraphics for how we work
// around this.
+
if( !(img instanceof BufferedImage) )
{
ImageProducer source = img.getSource();
@@ -1176,6 +1276,7 @@ public abstract class CairoGraphics2D extends Graphics2D
// If this BufferedImage has a BufferedImageGraphics object,
// use the cached CairoSurface that BIG is drawing onto
+
if( BufferedImageGraphics.bufferedImages.get( b ) != null )
db = (DataBuffer)BufferedImageGraphics.bufferedImages.get( b );
else
@@ -1190,6 +1291,7 @@ public abstract class CairoGraphics2D extends Graphics2D
if(db instanceof CairoSurface)
{
((CairoSurface)db).drawSurface(nativePointer, i2u, alpha);
+ updateColor();
return true;
}
@@ -1206,24 +1308,7 @@ public abstract class CairoGraphics2D extends Graphics2D
setPaint( oldPaint );
}
- int[] pixels;
-
- // Shortcut for easy color models.
- if( b.getColorModel().equals(rgb32) )
- {
- pixels = ((DataBufferInt)db).getData();
- for(int i = 0; i < pixels.length; i++)
- pixels[i] |= 0xFF000000;
- }
- else if( b.getColorModel().equals(argb32) )
- {
- pixels = ((DataBufferInt)db).getData();
- }
- else
- {
- pixels = b.getRGB(0, 0, width, height,
- null, 0, width);
- }
+ int[] pixels = b.getRGB(0, 0, width, height, null, 0, width);
drawPixels(nativePointer, pixels, width, height, width, i2u, alpha);
@@ -1249,7 +1334,9 @@ public abstract class CairoGraphics2D extends Graphics2D
public void drawImage(BufferedImage image, BufferedImageOp op, int x, int y)
{
- Image filtered = op.filter(image, null);
+ Image filtered = image;
+ if (op != null)
+ filtered = op.filter(image, null);
drawImage(filtered, new AffineTransform(1f, 0f, 0f, 1f, x, y), null, null);
}
@@ -1317,7 +1404,7 @@ public abstract class CairoGraphics2D extends Graphics2D
else
{ cy = dy2; ch = dy1 - dy2; }
- setClip( cx, cy, cw, ch );
+ clipRect( cx, cy, cw, ch );
AffineTransform tx = new AffineTransform();
tx.translate( dx1 - sx1*scaleX, dy1 - sy1*scaleY );
@@ -1358,6 +1445,10 @@ public abstract class CairoGraphics2D extends Graphics2D
public void drawGlyphVector(GlyphVector gv, float x, float y)
{
double alpha = 1.0;
+
+ if( gv.getNumGlyphs() <= 0 )
+ return;
+
if (comp instanceof AlphaComposite)
alpha = ((AlphaComposite) comp).getAlpha();
if (gv instanceof FreetypeGlyphVector && alpha == 1.0)
@@ -1367,8 +1458,11 @@ public abstract class CairoGraphics2D extends Graphics2D
float[] positions = gv.getGlyphPositions (0, n, null);
setFont (gv.getFont ());
- cairoDrawGlyphVector(nativePointer, (GdkFontPeer)getFont().getPeer(),
- x, y, n, codes, positions);
+ synchronized( this.font )
+ {
+ cairoDrawGlyphVector(nativePointer, (GdkFontPeer)getFont().getPeer(),
+ x, y, n, codes, positions);
+ }
}
else
{
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/CairoSurface.java b/libjava/classpath/gnu/java/awt/peer/gtk/CairoSurface.java
index 5ccd2e1..78bc1e0 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/CairoSurface.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/CairoSurface.java
@@ -38,26 +38,16 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.Graphics;
-import java.awt.Color;
-import java.awt.Image;
import java.awt.Point;
import java.awt.Graphics2D;
-import java.awt.GraphicsConfiguration;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
-import java.io.File;
-import java.io.IOException;
+import java.nio.ByteOrder;
import java.util.Hashtable;
-import java.util.Vector;
-import java.io.ByteArrayOutputStream;
-import java.io.BufferedInputStream;
-import java.net.URL;
-import gnu.classpath.Pointer;
/**
* CairoSurface - wraps a Cairo surface.
@@ -79,10 +69,10 @@ public class CairoSurface extends DataBuffer
long bufferPointer;
- static ColorModel nativeModel = new DirectColorModel(32,
- 0x000000FF,
- 0x0000FF00,
+ static ColorModel nativeModel = new DirectColorModel(32,
0x00FF0000,
+ 0x0000FF00,
+ 0x000000FF,
0xFF000000);
/**
@@ -177,28 +167,45 @@ public class CairoSurface extends DataBuffer
height = image.height;
create(width, height, width);
-
+
if(surfacePointer == 0 || bufferPointer == 0)
throw new Error("Could not allocate bitmap.");
-
+
// Copy the pixel data from the GtkImage.
int[] data = image.getPixels();
// Swap ordering from GdkPixbuf to Cairo
- for(int i = 0; i < data.length; i++ )
+ if (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN)
+ {
+ for (int i = 0; i < data.length; i++ )
+ {
+ // On a big endian system we get a RRGGBBAA data array.
+ int alpha = data[i] & 0xFF;
+ if( alpha == 0 ) // I do not know why we need this, but it works.
+ data[i] = 0;
+ else
+ {
+ // Cairo needs a ARGB32 native array.
+ data[i] = (data[i] >>> 8) | (alpha << 24);
+ }
+ }
+ }
+ else
{
- int alpha = (data[i] & 0xFF000000) >> 24;
- if( alpha == 0 ) // I do not know why we need this, but it works.
- data[i] = 0;
- else
+ for (int i = 0; i < data.length; i++ )
{
- int r = (((data[i] & 0x00FF0000) >> 16) );
- int g = (((data[i] & 0x0000FF00) >> 8) );
- int b = ((data[i] & 0x000000FF) );
- data[i] = (( alpha << 24 ) & 0xFF000000)
- | (( b << 16 ) & 0x00FF0000)
- | (( g << 8 ) & 0x0000FF00)
- | ( r & 0x000000FF);
+ // On a little endian system we get a AABBGGRR data array.
+ int alpha = data[i] & 0xFF000000;
+ if( alpha == 0 ) // I do not know why we need this, but it works.
+ data[i] = 0;
+ else
+ {
+ int b = (data[i] & 0xFF0000) >> 16;
+ int g = (data[i] & 0xFF00);
+ int r = (data[i] & 0xFF) << 16;
+ // Cairo needs a ARGB32 native array.
+ data[i] = alpha | r | g | b;
+ }
}
}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java b/libjava/classpath/gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
index 91f0b49..7bd136c 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/CairoSurfaceGraphics.java
@@ -39,14 +39,9 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
import java.awt.Graphics;
-import java.awt.Color;
import java.awt.GraphicsEnvironment;
-import java.awt.Image;
-import java.awt.Point;
-import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.geom.Rectangle2D;
-import java.awt.image.*;
/**
* Implementation of Graphics2D on a Cairo surface.
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/ComponentGraphics.java b/libjava/classpath/gnu/java/awt/peer/gtk/ComponentGraphics.java
index d1d3c28..ffa78e9 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/ComponentGraphics.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/ComponentGraphics.java
@@ -39,7 +39,6 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
import java.awt.Color;
-import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
@@ -47,16 +46,14 @@ import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Toolkit;
-import java.awt.Point;
-import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
-import java.awt.image.ImagingOpException;
import java.awt.image.RenderedImage;
+import gnu.classpath.Pointer;
/**
* ComponentGraphics - context for drawing directly to a component,
@@ -66,6 +63,8 @@ import java.awt.image.RenderedImage;
*/
public class ComponentGraphics extends CairoGraphics2D
{
+ private static final boolean hasXRenderExtension = hasXRender();
+
private GtkComponentPeer component;
protected long cairo_t;
@@ -164,13 +163,27 @@ public class ComponentGraphics extends CairoGraphics2D
*/
public static native boolean hasXRender();
+ /**
+ * This is a utility method (used by GtkComponentPeer) for grabbing the
+ * image of a component.
+ */
+ private static native Pointer nativeGrab(GtkComponentPeer component);
private native void copyAreaNative(GtkComponentPeer component, int x, int y,
int width, int height, int dx, int dy);
private native void drawVolatile(GtkComponentPeer component,
long vimg, int x, int y,
- int width, int height);
+ int width, int height, int cx, int cy,
+ int cw, int ch);
+
+ /**
+ * Not really related (moveme?). Utility method used by GtkComponent.
+ */
+ public static GtkImage grab( GtkComponentPeer component )
+ {
+ return new GtkImage( nativeGrab( component ) );
+ }
/**
* Returns a Graphics2D object for a component, either an instance of this
@@ -178,7 +191,7 @@ public class ComponentGraphics extends CairoGraphics2D
*/
public static Graphics2D getComponentGraphics(GtkComponentPeer component)
{
- if( hasXRender() )
+ if( hasXRenderExtension )
return new ComponentGraphics(component);
Rectangle r = component.awtComponent.getBounds();
@@ -285,21 +298,24 @@ public class ComponentGraphics extends CairoGraphics2D
if (img instanceof GtkVolatileImage)
{
GtkVolatileImage vimg = (GtkVolatileImage) img;
- int type = transform.getType();
- if (type == AffineTransform.TYPE_IDENTITY)
- {
- drawVolatile(component, vimg.nativePointer,
- x, y, vimg.width, vimg.height);
- return true;
- }
- else if (type == AffineTransform.TYPE_TRANSLATION)
- {
- x += transform.getTranslateX();
- y += transform.getTranslateY();
- drawVolatile(component, vimg.nativePointer,
- x, y, vimg.width, vimg.height);
- return true;
- }
+ int type = transform.getType();
+ if ((type == AffineTransform.TYPE_IDENTITY
+ || type == AffineTransform.TYPE_TRANSLATION)
+ && (clip == null || clip instanceof Rectangle2D))
+ {
+ Rectangle2D r = (Rectangle2D) clip;
+ if (r == null)
+ r = getRealBounds();
+ x += transform.getTranslateX();
+ y += transform.getTranslateY();
+ drawVolatile(component, vimg.nativePointer,
+ x, y, vimg.width, vimg.height,
+ (int) (r.getX() + transform.getTranslateX()),
+ (int) (r.getY() + transform.getTranslateY()),
+ (int) r.getWidth(),
+ (int) r.getHeight());
+ return true;
+ }
else
return super.drawImage(vimg.getSnapshot(), x, y, observer);
}
@@ -323,24 +339,28 @@ public class ComponentGraphics extends CairoGraphics2D
// If it is a GtkVolatileImage with an "easy" transform then
// draw directly. Always pass a BufferedImage to super to avoid
// deadlock (see Note in CairoGraphics.drawImage()).
- if (img instanceof GtkVolatileImage)
+ if (img instanceof GtkVolatileImage
+ && (clip == null || clip instanceof Rectangle2D))
{
GtkVolatileImage vimg = (GtkVolatileImage) img;
- int type = transform.getType();
- if (type == AffineTransform.TYPE_IDENTITY)
- {
- drawVolatile(component, vimg.nativePointer,
- x, y, width, height);
- return true;
- }
- else if (type == AffineTransform.TYPE_TRANSLATION)
- {
- x += transform.getTranslateX();
- y += transform.getTranslateY();
- drawVolatile(component, vimg.nativePointer,
- x, y, width, height);
- return true;
- }
+ int type = transform.getType();
+ if ((type == AffineTransform.TYPE_IDENTITY
+ || type == AffineTransform.TYPE_TRANSLATION)
+ && (clip == null || clip instanceof Rectangle2D))
+ {
+ Rectangle2D r = (Rectangle2D) clip;
+ if (r == null)
+ r = getRealBounds();
+ x += transform.getTranslateX();
+ y += transform.getTranslateY();
+ drawVolatile(component, vimg.nativePointer,
+ x, y, width, height,
+ (int) (r.getX() + transform.getTranslateX()),
+ (int) (r.getY() + transform.getTranslateY()),
+ (int) r.getWidth(),
+ (int) r.getHeight());
+ return true;
+ }
else
return super.drawImage(vimg.getSnapshot(), x, y,
width, height, observer);
@@ -359,5 +379,57 @@ public class ComponentGraphics extends CairoGraphics2D
return super.drawImage(bimg, x, y, width, height, observer);
}
+ public void drawLine(int x1, int y1, int x2, int y2)
+ {
+ lock();
+ try
+ {
+ super.drawLine(x1, y1, x2, y2);
+ }
+ finally
+ {
+ unlock();
+ }
+ }
+
+ public void drawRect(int x, int y, int width, int height)
+ {
+ lock();
+ try
+ {
+ super.drawRect(x, y, width, height);
+ }
+ finally
+ {
+ unlock();
+ }
+ }
+
+ public void fillRect(int x, int y, int width, int height)
+ {
+ lock();
+ try
+ {
+ super.fillRect(x, y, width, height);
+ }
+ finally
+ {
+ unlock();
+ }
+ }
+
+ public void setClip(Shape s)
+ {
+ lock();
+ try
+ {
+ super.setClip(s);
+ }
+ finally
+ {
+ unlock();
+ }
+ }
+
}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java b/libjava/classpath/gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java
index 286fbea..2216d45 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/ComponentGraphicsCopy.java
@@ -39,17 +39,11 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
import java.awt.Color;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.GraphicsConfiguration;
import java.awt.Image;
-import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
-import java.awt.image.BufferedImage;
-import java.awt.image.DataBuffer;
import java.awt.image.RenderedImage;
import java.awt.image.ImageObserver;
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/FreetypeGlyphVector.java b/libjava/classpath/gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
index 4978c6a..2c9d917 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/FreetypeGlyphVector.java
@@ -137,6 +137,35 @@ public class FreetypeGlyphVector extends GlyphVector
}
/**
+ * Cloning constructor
+ */
+ private FreetypeGlyphVector( FreetypeGlyphVector gv )
+ {
+ font = gv.font;
+ peer = gv.peer;
+ frc = gv.frc;
+ s = gv.s;
+ nGlyphs = gv.nGlyphs;
+ logicalBounds = gv.logicalBounds.getBounds2D();
+
+ if( gv.metricsCache != null )
+ {
+ metricsCache = new GlyphMetrics[ nGlyphs ];
+ System.arraycopy(gv.metricsCache, 0, metricsCache, 0, nGlyphs);
+ }
+
+ glyphCodes = new int[ nGlyphs ];
+ glyphPositions = new float[ nGlyphs ];
+ glyphTransforms = new AffineTransform[ nGlyphs ];
+ for(int i = 0; i < nGlyphs; i++ )
+ {
+ glyphTransforms[ i ] = new AffineTransform( gv.glyphTransforms[ i ] );
+ glyphCodes[i] = gv.glyphCodes[ i ];
+ glyphPositions[i] = gv.glyphPositions[ i ];
+ }
+ }
+
+ /**
* Create the array of glyph codes.
*/
private void getGlyphs()
@@ -172,6 +201,12 @@ public class FreetypeGlyphVector extends GlyphVector
private native GeneralPath getGlyphOutlineNative(int glyphIndex);
+
+ public Object clone()
+ {
+ return new FreetypeGlyphVector( this );
+ }
+
/**
* Duh, compares two instances.
*/
@@ -260,8 +295,11 @@ public class FreetypeGlyphVector extends GlyphVector
if( gm == null )
return null;
Rectangle2D r = gm.getBounds2D();
- return new Rectangle2D.Double( r.getX() - gm.getLSB(), r.getY(),
- gm.getAdvanceX(), r.getHeight() );
+ Point2D p = getGlyphPosition( glyphIndex );
+ return new Rectangle2D.Double( p.getX() + r.getX() - gm.getLSB(),
+ p.getY() + r.getY(),
+ gm.getAdvanceX(),
+ r.getHeight() );
}
/*
@@ -385,8 +423,6 @@ public class FreetypeGlyphVector extends GlyphVector
for( int i = 1; i < nGlyphs; i++ )
{
Rectangle2D r2 = (Rectangle2D)getGlyphLogicalBounds( i );
- Point2D p = getGlyphPosition( i );
- r2.setRect( p.getX(), p.getY(), r2.getWidth(), r2.getHeight() );
rect = rect.createUnion( r2 );
}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GdkFontPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GdkFontPeer.java
index f5ed8a7..11635c3 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GdkFontPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GdkFontPeer.java
@@ -38,7 +38,6 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import gnu.classpath.Configuration;
import gnu.java.awt.peer.ClasspathFontPeer;
import gnu.java.awt.font.opentype.NameDecoder;
@@ -50,9 +49,7 @@ import java.awt.font.GlyphVector;
import java.awt.font.GlyphMetrics;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
-import java.awt.geom.Point2D;
import java.text.CharacterIterator;
-import java.text.StringCharacterIterator;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java b/libjava/classpath/gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java
index 035819d..e095c7d 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GdkGraphicsEnvironment.java
@@ -134,5 +134,9 @@ public class GdkGraphicsEnvironment extends GraphicsEnvironment
{
throw new java.lang.UnsupportedOperationException ();
}
-
+
+ /**
+ * Used by GtkMouseInfoPeer.
+ */
+ native int[] getMouseCoordinates();
}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GdkPixbufDecoder.java b/libjava/classpath/gnu/java/awt/peer/gtk/GdkPixbufDecoder.java
index cd047f2..6d0a52b 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GdkPixbufDecoder.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GdkPixbufDecoder.java
@@ -38,13 +38,10 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import gnu.classpath.Configuration;
-
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.ImageConsumer;
-import java.awt.image.ImageProducer;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.io.DataInput;
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GdkTextLayout.java b/libjava/classpath/gnu/java/awt/peer/gtk/GdkTextLayout.java
deleted file mode 100644
index a876522..0000000
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GdkTextLayout.java
+++ /dev/null
@@ -1,393 +0,0 @@
-/* GdkTextLayout.java
- Copyright (C) 2003, 2005, 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package gnu.java.awt.peer.gtk;
-
-import gnu.classpath.Configuration;
-import gnu.java.awt.peer.ClasspathTextLayoutPeer;
-
-import java.awt.Font;
-import java.awt.Graphics2D;
-import java.awt.Shape;
-import java.awt.font.FontRenderContext;
-import java.awt.font.GlyphMetrics;
-import java.awt.font.GlyphVector;
-import java.awt.font.TextAttribute;
-import java.awt.font.TextHitInfo;
-import java.awt.font.TextLayout;
-import java.awt.geom.AffineTransform;
-import java.awt.geom.GeneralPath;
-import java.awt.geom.Rectangle2D;
-import java.text.AttributedCharacterIterator;
-import java.text.AttributedString;
-import java.text.CharacterIterator;
-
-/**
- * This is an implementation of the text layout peer interface which
- * delegates all the hard work to pango.
- *
- * @author Graydon Hoare
- */
-
-public class GdkTextLayout
- implements ClasspathTextLayoutPeer
-{
- // native side, plumbing, etc.
- static
- {
- System.loadLibrary("gtkpeer");
-
- initStaticState ();
- }
- private native void setText(String str);
- private native void setFont(GdkFontPeer font);
- private native void getExtents(double[] inkExtents,
- double[] logExtents);
- private native void indexToPos(int idx, double[] pos);
-
- private native void initState ();
-
- private native void dispose ();
-
- private native void cairoDrawGdkTextLayout(long cg2d, float x, float y);
-
- static native void initStaticState();
-
- private final int native_state = GtkGenericPeer.getUniqueInteger ();
-
- protected void finalize ()
- {
- dispose ();
- }
-
- // we hold on to these to make sure we can render when presented
- // with non-GdkGraphics2D paint targets
- private AttributedString attributedString;
- private FontRenderContext fontRenderContext;
-
- public GdkTextLayout(AttributedString str, FontRenderContext frc)
- {
- initState();
- attributedString = str;
- fontRenderContext = frc;
- AttributedCharacterIterator aci = str.getIterator();
- char[] chars = new char[aci.getEndIndex() - aci.getBeginIndex()];
- for(int i = aci.getBeginIndex(); i < aci.getEndIndex(); i++)
- chars[i] = aci.setIndex(i);
- setText(new String(chars));
-
- Object fnt = aci.getAttribute(TextAttribute.FONT);
- if (fnt != null && fnt instanceof Font)
- setFont( (GdkFontPeer) ((Font)fnt).getPeer() );
- }
-
- protected class CharacterIteratorProxy
- implements CharacterIterator
- {
- public CharacterIterator target;
- public int begin;
- public int limit;
- public int index;
-
- public CharacterIteratorProxy (CharacterIterator ci)
- {
- target = ci;
- }
-
- public int getBeginIndex ()
- {
- return begin;
- }
-
- public int getEndIndex ()
- {
- return limit;
- }
-
- public int getIndex ()
- {
- return index;
- }
-
- public char setIndex (int idx)
- throws IllegalArgumentException
- {
- if (idx < begin || idx >= limit)
- throw new IllegalArgumentException ();
- char ch = target.setIndex (idx);
- index = idx;
- return ch;
- }
-
- public char first ()
- {
- int save = target.getIndex ();
- char ch = target.setIndex (begin);
- target.setIndex (save);
- return ch;
- }
-
- public char last ()
- {
- if (begin == limit)
- return this.first ();
-
- int save = target.getIndex ();
- char ch = target.setIndex (limit - 1);
- target.setIndex (save);
- return ch;
- }
-
- public char current ()
- {
- return target.current();
- }
-
- public char next ()
- {
- if (index >= limit - 1)
- return CharacterIterator.DONE;
- else
- {
- index++;
- return target.next();
- }
- }
-
- public char previous ()
- {
- if (index <= begin)
- return CharacterIterator.DONE;
- else
- {
- index--;
- return target.previous ();
- }
- }
-
- public Object clone ()
- {
- CharacterIteratorProxy cip = new CharacterIteratorProxy (this.target);
- cip.begin = this.begin;
- cip.limit = this.limit;
- cip.index = this.index;
- return cip;
- }
-
- }
-
-
- // public side
-
- public void draw (Graphics2D g2, float x, float y)
- {
- cairoDrawGdkTextLayout(((CairoGraphics2D) g2).nativePointer, x, y);
- }
-
- public TextHitInfo getStrongCaret (TextHitInfo hit1,
- TextHitInfo hit2)
- {
- throw new Error("not implemented");
- }
-
- public byte getBaseline ()
- {
- throw new Error("not implemented");
- }
-
- public boolean isLeftToRight ()
- {
- throw new Error("not implemented");
- }
-
- public boolean isVertical ()
- {
- throw new Error("not implemented");
- }
-
- public float getAdvance ()
- {
- throw new Error("not implemented");
- }
-
- public float getAscent ()
- {
- throw new Error("not implemented");
- }
-
- public float getDescent ()
- {
- throw new Error("not implemented");
- }
-
- public float getLeading ()
- {
- throw new Error("not implemented");
- }
-
- public int getCharacterCount ()
- {
- throw new Error("not implemented");
- }
-
- public byte getCharacterLevel (int index)
- {
- throw new Error("not implemented");
- }
-
- public float[] getBaselineOffsets ()
- {
- throw new Error("not implemented");
- }
-
- public Shape getBlackBoxBounds (int firstEndpoint, int secondEndpoint)
- {
- throw new Error("not implemented");
- }
-
- public Rectangle2D getBounds ()
- {
- double[] inkExtents = new double[4];
- double[] logExtents = new double[4];
- getExtents(inkExtents, logExtents);
- return new Rectangle2D.Double(logExtents[0], logExtents[1],
- logExtents[2], logExtents[3]);
- }
-
- public float[] getCaretInfo (TextHitInfo hit, Rectangle2D bounds)
- {
- throw new Error("not implemented");
- }
-
- public Shape getCaretShape (TextHitInfo hit, Rectangle2D bounds)
- {
- throw new Error("not implemented");
- }
-
- public Shape[] getCaretShapes (int offset, Rectangle2D bounds,
- TextLayout.CaretPolicy policy)
- {
- throw new Error("not implemented");
- }
-
- public Shape getLogicalHighlightShape (int firstEndpoint, int secondEndpoint,
- Rectangle2D bounds)
- {
- AffineTransform at = new AffineTransform();
- GeneralPath gp = new GeneralPath();
- double [] rect = new double[4];
- Rectangle2D tmp = new Rectangle2D.Double();
- for (int i = firstEndpoint; i <= secondEndpoint; ++i)
- {
- indexToPos(i, rect);
- tmp.setRect(rect[0], rect[1], rect[2], rect[3]);
- Rectangle2D.intersect(tmp, bounds, tmp);
- gp.append(tmp.getPathIterator(at), false);
- }
- return gp;
- }
-
- public int[] getLogicalRangesForVisualSelection (TextHitInfo firstEndpoint,
- TextHitInfo secondEndpoint)
- {
- throw new Error("not implemented");
- }
-
- public TextHitInfo getNextLeftHit (int offset, TextLayout.CaretPolicy policy)
- {
- throw new Error("not implemented");
- }
- public TextHitInfo getNextRightHit (int offset, TextLayout.CaretPolicy policy)
- {
- throw new Error("not implemented");
- }
- public TextHitInfo hitTestChar (float x, float y, Rectangle2D bounds)
- {
- throw new Error("not implemented");
- }
- public TextHitInfo getVisualOtherHit (TextHitInfo hit)
- {
- throw new Error("not implemented");
- }
-
- public float getVisibleAdvance ()
- {
- throw new Error("not implemented");
- }
-
- public native Shape getOutline (AffineTransform tx);
-
- public Shape getVisualHighlightShape (TextHitInfo firstEndpoint,
- TextHitInfo secondEndpoint,
- Rectangle2D bounds)
- {
- throw new Error("not implemented");
- }
-
-
- public TextLayout getJustifiedLayout (float justificationWidth)
- {
- throw new Error("not implemented");
- }
-
- public void handleJustify (float justificationWidth)
- {
- throw new Error("not implemented");
- }
-
- public Object clone ()
- {
- throw new Error("not implemented");
- }
-
- public int hashCode ()
- {
- throw new Error("not implemented");
- }
-
- public boolean equals (ClasspathTextLayoutPeer tl)
- {
- throw new Error("not implemented");
- }
-
- public String toString ()
- {
- throw new Error("not implemented");
- }
-
-}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkButtonPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkButtonPeer.java
index 63d9cd4..f18db7a 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkButtonPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkButtonPeer.java
@@ -38,13 +38,8 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.AWTEvent;
import java.awt.Button;
-import java.awt.Component;
-import java.awt.Point;
import java.awt.event.ActionEvent;
-import java.awt.event.KeyEvent;
-import java.awt.event.MouseEvent;
import java.awt.peer.ButtonPeer;
// A composite widget. GtkButtons have transparent backgrounds. An
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkCanvasPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkCanvasPeer.java
index edfc9cee..30c39de 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkCanvasPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkCanvasPeer.java
@@ -53,8 +53,8 @@ public class GtkCanvasPeer extends GtkComponentPeer implements CanvasPeer
// Preferred size for a drawing widget is always what the user
// requested.
- public Dimension getPreferredSize ()
+ public Dimension preferredSize()
{
- return awtComponent.getSize ();
+ return awtComponent.getSize();
}
}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkCheckboxGroupPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkCheckboxGroupPeer.java
deleted file mode 100644
index 46b0733..0000000
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkCheckboxGroupPeer.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/* GtkCheckboxGroupPeer.java - Wrap a CheckboxGroup
- Copyright (C) 2002 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package gnu.java.awt.peer.gtk;
-
-import java.awt.CheckboxGroup;
-import java.util.WeakHashMap;
-
-// Note that there is no peer interface for a CheckboxGroup. We
-// introduce our own in order to make it easier to keep a piece of
-// native state for each one.
-public class GtkCheckboxGroupPeer extends GtkGenericPeer
-{
- // This maps from a CheckboxGroup to the native peer.
- private static WeakHashMap map = new WeakHashMap ();
-
- // Find the native peer corresponding to a CheckboxGroup.
- public static synchronized GtkCheckboxGroupPeer
- getCheckboxGroupPeer (CheckboxGroup group)
- {
- if (group == null)
- return null;
- GtkCheckboxGroupPeer nat = (GtkCheckboxGroupPeer) map.get (group);
- if (nat == null)
- {
- nat = new GtkCheckboxGroupPeer ();
- map.put (group, nat);
- }
- return nat;
- }
-
- private GtkCheckboxGroupPeer ()
- {
- // We don't need any special state here. Note that we can't store
- // a reference to the java-side CheckboxGroup. That would mean
- // they could never be collected.
- super (null);
- }
-
- // Dispose of our native resources.
- public native void dispose ();
-
- // Remove a given checkbox from this group.
- public native void remove (GtkCheckboxPeer box);
-
- // When collected, clean up the native state.
- protected void finalize ()
- {
- dispose ();
- }
-}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkCheckboxPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkCheckboxPeer.java
index 094aa3c..90d16c5 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkCheckboxPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkCheckboxPeer.java
@@ -40,20 +40,32 @@ package gnu.java.awt.peer.gtk;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
-import java.awt.peer.CheckboxPeer;
-
import java.awt.event.ItemEvent;
+import java.awt.peer.CheckboxPeer;
+import java.util.WeakHashMap;
+/**
+ * This class wraps either a GtkCheckButton or a GtkOptionButton
+ * depending on if this peer's owner belongs to a CheckboxGroup.
+ */
public class GtkCheckboxPeer extends GtkComponentPeer
implements CheckboxPeer
{
- // Group from last time it was set.
- public GtkCheckboxGroupPeer old_group;
+ // The CheckboxGroup to which this GtkCheckboxPeer's owner belongs.
+ public CheckboxGroup current_group;
// The current state of the GTK checkbox.
- private boolean currentState;
+ private boolean currentState;
+
+ // A map from CheckboxGroup to GSList* GTK option group pointer.
+ private static WeakHashMap groupMap = new WeakHashMap();
+
+ public native void createCheckButton ();
+ public native void createRadioButton (long groupPointer);
- public native void create (GtkCheckboxGroupPeer group);
- public native void nativeSetCheckboxGroup (GtkCheckboxGroupPeer group);
+ public native void addToGroup (long groupPointer);
+ public native void removeFromGroup ();
+ public native void switchToGroup (long groupPointer);
+
public native void connectSignals ();
/**
@@ -68,17 +80,47 @@ public class GtkCheckboxPeer extends GtkComponentPeer
super (c);
}
- // FIXME: we must be able to switch between a checkbutton and a
- // radiobutton dynamically.
public void create ()
{
Checkbox checkbox = (Checkbox) awtComponent;
- CheckboxGroup g = checkbox.getCheckboxGroup ();
- old_group = GtkCheckboxGroupPeer.getCheckboxGroupPeer (g);
- create (old_group);
+ current_group = checkbox.getCheckboxGroup ();
+ if (current_group == null)
+ {
+ // Initially we're not part of a group so we're backed by a
+ // GtkCheckButton.
+ createCheckButton();
+ }
+ else
+ {
+ // Initially we're part of a group.
+
+ // See if this group is already stored in our map.
+ Long groupPointer = null;
+ synchronized (groupMap)
+ {
+ groupPointer = (Long) groupMap.get(current_group);
+ }
+
+ if (groupPointer == null)
+ {
+ // We don't know about this group. Create a new native
+ // group pointer for this group and store it in our map.
+ createRadioButton(0);
+ }
+ else
+ {
+ // We already know about this group. Pass the
+ // corresponding native group pointer value to the native
+ // create method.
+ createRadioButton(groupPointer.longValue());
+ }
+ }
currentState = checkbox.getState();
gtkToggleButtonSetActive(currentState);
- gtkButtonSetLabel (checkbox.getLabel ());
+
+ String label = checkbox.getLabel();
+ if (label != null)
+ gtkButtonSetLabel(label);
}
/**
@@ -87,7 +129,7 @@ public class GtkCheckboxPeer extends GtkComponentPeer
* event since events should only be posted for user initiated
* clicks on the GtkCheckButton.
*/
- synchronized public void setState (boolean state)
+ public synchronized void setState (boolean state)
{
if (currentState != state)
{
@@ -103,21 +145,87 @@ public class GtkCheckboxPeer extends GtkComponentPeer
public void setCheckboxGroup (CheckboxGroup group)
{
- GtkCheckboxGroupPeer gp
- = GtkCheckboxGroupPeer.getCheckboxGroupPeer (group);
- if (gp != old_group)
+ if (current_group == null && group != null)
{
- if (old_group != null)
- old_group.remove (this);
- nativeSetCheckboxGroup (gp);
- old_group = gp;
+ // This peer's owner is currently not in a group, and now
+ // we're adding it to a group. This means that the backing
+ // GtkWidget will change from a GtkCheckButton to a
+ // GtkRadioButton.
+
+ current_group = group;
+
+ // See if the new group is already stored in our map.
+ Long groupPointer = null;
+ synchronized (groupMap)
+ {
+ groupPointer = (Long) groupMap.get(current_group);
+ }
+
+ if (groupPointer == null)
+ {
+ // We don't know about this group. Create a new native
+ // group pointer for this group and store it in our map.
+ addToGroup(0);
+ }
+ else
+ {
+ // We already know about this group. Pass the
+ // corresponding native group pointer value to the native
+ // create method.
+ addToGroup(groupPointer.longValue());
+ }
+ }
+ else if (current_group != null && group == null)
+ {
+ // This peer's owner is currently in a group, and now we're
+ // removing it from a group. This means that the backing
+ // GtkWidget will change from a GtkRadioButton to a
+ // GtkCheckButton.
+ removeFromGroup();
+ current_group = null;
+ }
+ else if (current_group == null && group == null)
+ {
+ // This peer's owner is currently not in a group, and we're
+ // not adding it to a group, so simply return.
+ return;
+ }
+ else if (current_group != group)
+ {
+ // This peer's owner is currently in a group, and now we're
+ // putting it in another group. This means that we must
+ // remove the backing GtkRadioButton from one group and add it
+ // to the other group.
+
+ current_group = group;
+
+ // See if the new group is already stored in our map.
+ Long groupPointer = null;
+ synchronized (groupMap)
+ {
+ groupPointer = (Long) groupMap.get(current_group);
+ }
+
+ if (groupPointer == null)
+ {
+ // We don't know about this group. Create a new native
+ // group pointer for this group and store it in our map.
+ switchToGroup(0);
+ }
+ else
+ {
+ // We already know about this group. Pass the
+ // corresponding native group pointer value to the native
+ // create method.
+ switchToGroup(groupPointer.longValue());
+ }
}
}
// Override the superclass postItemEvent so that the peer doesn't
// need information that we have.
// called back by native side: item_toggled_cb
- synchronized public void postItemEvent(Object item, boolean state)
+ public synchronized void postItemEvent(Object item, boolean state)
{
// Only fire event is state actually changed.
if (currentState != state)
@@ -127,13 +235,20 @@ public class GtkCheckboxPeer extends GtkComponentPeer
state ? ItemEvent.SELECTED : ItemEvent.DESELECTED);
}
}
+
+ public void addToGroupMap(long groupPointer)
+ {
+ synchronized (groupMap)
+ {
+ groupMap.put(current_group, new Long (groupPointer));
+ }
+ }
public void dispose ()
{
- // Notify the group so that the native state can be cleaned up
- // appropriately.
- if (old_group != null)
- old_group.remove (this);
+ groupMap.clear();
+ current_group = null;
+ currentState = false;
super.dispose ();
}
}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkClipboardNotifier.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkClipboardNotifier.java
index fdc7d50..61df796 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkClipboardNotifier.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkClipboardNotifier.java
@@ -1,5 +1,5 @@
/* GtkClipboardNotifier.java -- Helper for announcing GtkSelection changes.
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,8 +38,6 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.datatransfer.*;
-import java.util.*;
class GtkClipboardNotifier extends Thread
{
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkComponentPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkComponentPeer.java
index 625855f..c11c45e 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkComponentPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkComponentPeer.java
@@ -52,9 +52,12 @@ import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Insets;
import java.awt.ItemSelectable;
+import java.awt.KeyboardFocusManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
@@ -66,13 +69,13 @@ import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.PaintEvent;
import java.awt.event.TextEvent;
-import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.image.VolatileImage;
import java.awt.peer.ComponentPeer;
import java.awt.peer.ContainerPeer;
+import java.awt.peer.LightweightPeer;
import java.awt.peer.WindowPeer;
import java.util.Timer;
import java.util.TimerTask;
@@ -109,6 +112,9 @@ public class GtkComponentPeer extends GtkGenericPeer
native void gtkWidgetRequestFocus ();
native void gtkWidgetDispatchKeyEvent (int id, long when, int mods,
int keyCode, int keyLocation);
+ native boolean gtkWidgetHasFocus();
+ native boolean gtkWidgetCanFocus();
+
native void realize();
native void setNativeEventMask ();
@@ -365,7 +371,7 @@ public class GtkComponentPeer extends GtkGenericPeer
public void print (Graphics g)
{
- throw new RuntimeException ();
+ g.drawImage( ComponentGraphics.grab( this ), 0, 0, null );
}
public void repaint (long tm, int x, int y, int width, int height)
@@ -414,8 +420,7 @@ public class GtkComponentPeer extends GtkGenericPeer
public void requestFocus ()
{
- gtkWidgetRequestFocus();
- postFocusEvent(FocusEvent.FOCUS_GAINED, false);
+ assert false: "Call new requestFocus() method instead";
}
public void reshape (int x, int y, int width, int height)
@@ -628,6 +633,12 @@ public class GtkComponentPeer extends GtkGenericPeer
q.postEvent(keyEvent);
}
+ /**
+ * Referenced from native code.
+ *
+ * @param id
+ * @param temporary
+ */
protected void postFocusEvent (int id, boolean temporary)
{
q().postEvent (new FocusEvent (awtComponent, id, temporary));
@@ -647,8 +658,10 @@ public class GtkComponentPeer extends GtkGenericPeer
public GraphicsConfiguration getGraphicsConfiguration ()
{
- // FIXME: just a stub for now.
- return null;
+ // FIXME: The component might be showing on a non-default screen.
+ GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ GraphicsDevice dev = env.getDefaultScreenDevice();
+ return dev.getDefaultConfiguration();
}
public void setEventMask (long mask)
@@ -661,10 +674,72 @@ public class GtkComponentPeer extends GtkGenericPeer
return false;
}
- public boolean requestFocus (Component source, boolean b1,
- boolean b2, long x)
+ public boolean requestFocus (Component request, boolean temporary,
+ boolean allowWindowFocus, long time)
{
- return false;
+ assert request == awtComponent || isLightweightDescendant(request);
+ boolean retval = false;
+ if (gtkWidgetHasFocus())
+ {
+ KeyboardFocusManager kfm =
+ KeyboardFocusManager.getCurrentKeyboardFocusManager();
+ Component currentFocus = kfm.getFocusOwner();
+ if (currentFocus == request)
+ // Nothing to do in this trivial case.
+ retval = true;
+ else
+ {
+ // Requested component is a lightweight descendant of this one
+ // or the actual heavyweight.
+ // Since this (native) component is already focused, we simply
+ // change the actual focus and be done.
+ postFocusEvent(FocusEvent.FOCUS_GAINED, temporary);
+ retval = true;
+ }
+ }
+ else
+ {
+ if (gtkWidgetCanFocus())
+ {
+ if (allowWindowFocus)
+ {
+ Window window = getWindowFor(request);
+ GtkWindowPeer wPeer = (GtkWindowPeer) window.getPeer();
+ if (! wPeer.gtkWindowHasFocus())
+ wPeer.requestWindowFocus();
+ }
+ // Store requested focus component so that the corresponding
+ // event is dispatched correctly.
+ gtkWidgetRequestFocus();
+ retval = true;
+ }
+ }
+ return retval;
+ }
+
+ private Window getWindowFor(Component c)
+ {
+ Component comp = c;
+ while (! (comp instanceof Window))
+ comp = comp.getParent();
+ return (Window) comp;
+ }
+
+ /**
+ * Returns true
if the component is a direct (== no intermediate
+ * heavyweights) lightweight descendant of this peer's component.
+ *
+ * @param c the component to check
+ *
+ * @return true
if the component is a direct (== no intermediate
+ * heavyweights) lightweight descendant of this peer's component
+ */
+ protected boolean isLightweightDescendant(Component c)
+ {
+ Component comp = c;
+ while (comp.getPeer() instanceof LightweightPeer)
+ comp = comp.getParent();
+ return comp == awtComponent;
}
public boolean isObscured ()
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkContainerPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkContainerPeer.java
index 06076e7..541de3d 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkContainerPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkContainerPeer.java
@@ -42,10 +42,7 @@ import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
-import java.awt.Graphics;
import java.awt.Insets;
-import java.awt.Window;
-import java.awt.peer.ComponentPeer;
import java.awt.peer.ContainerPeer;
public class GtkContainerPeer extends GtkComponentPeer
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkDialogPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkDialogPeer.java
index 3254f56..1390654 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkDialogPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkDialogPeer.java
@@ -1,5 +1,5 @@
/* GtkDialogPeer.java -- Implements DialogPeer with GTK
- Copyright (C) 1998, 1999, 2002 Free Software Foundation, Inc.
+ Copyright (C) 1998, 1999, 2002, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -39,9 +39,6 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
import java.awt.Dialog;
-import java.awt.Graphics;
-import java.awt.Rectangle;
-import java.awt.event.PaintEvent;
import java.awt.peer.DialogPeer;
public class GtkDialogPeer extends GtkWindowPeer
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkFramePeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkFramePeer.java
index 6ec0b72..bb6f8b3 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkFramePeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkFramePeer.java
@@ -39,11 +39,9 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
import java.awt.Frame;
-import java.awt.Graphics;
import java.awt.Image;
import java.awt.MenuBar;
import java.awt.Rectangle;
-import java.awt.event.PaintEvent;
import java.awt.peer.FramePeer;
import java.awt.peer.MenuBarPeer;
@@ -218,11 +216,7 @@ public class GtkFramePeer extends GtkWindowPeer
// TODO Auto-generated method stub
}
- public void updateAlwaysOnTop()
- {
- // TODO Auto-generated method stub
-
- }
+
public boolean requestWindowFocus()
{
// TODO Auto-generated method stub
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkImage.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkImage.java
index ef96518..0fd98bb 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkImage.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkImage.java
@@ -39,12 +39,10 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
import java.awt.Graphics;
-import java.awt.Color;
import java.awt.Image;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.MemoryImageSource;
-import java.awt.image.ImageConsumer;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkImageConsumer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkImageConsumer.java
index 299f01d..f1a74b8 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkImageConsumer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkImageConsumer.java
@@ -1,5 +1,5 @@
/* GtkImageConsumer.java
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,16 +38,11 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.Graphics;
-import java.awt.Image;
import java.awt.image.ColorModel;
-import java.awt.image.DirectColorModel;
import java.awt.image.ImageConsumer;
-import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.image.MemoryImageSource;
import java.util.Hashtable;
-import java.util.Vector;
/**
* Helper class to GtkImage. Sits and gathers pixels for a GtkImage and then
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkLabelPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkLabelPeer.java
index bbf4230..02db90d 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkLabelPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkLabelPeer.java
@@ -56,7 +56,7 @@ public class GtkLabelPeer extends GtkComponentPeer
native void nativeSetAlignment (float alignment);
- public native void setText(String text);
+ public native void setNativeText(String text);
native void setNativeBounds (int x, int y, int width, int height);
// Because this is a composite widget, we need to retrieve the
@@ -69,6 +69,12 @@ public class GtkLabelPeer extends GtkComponentPeer
create (label.getText (), getGtkAlignment (label.getAlignment ()));
}
+ public void setText(String text)
+ {
+ if (text != null)
+ setNativeText(text);
+ }
+
public GtkLabelPeer (Label l)
{
super (l);
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkMenuBarPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkMenuBarPeer.java
index d203b43..898f224 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkMenuBarPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkMenuBarPeer.java
@@ -38,12 +38,9 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.Font;
import java.awt.Menu;
import java.awt.MenuBar;
-import java.awt.MenuComponent;
import java.awt.peer.MenuBarPeer;
-import java.awt.peer.MenuPeer;
public class GtkMenuBarPeer extends GtkMenuComponentPeer
implements MenuBarPeer
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkMenuItemPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkMenuItemPeer.java
index 251bab2..ea523e9 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkMenuItemPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkMenuItemPeer.java
@@ -38,13 +38,8 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.Font;
-import java.awt.Menu;
-import java.awt.MenuBar;
-import java.awt.MenuComponent;
import java.awt.MenuItem;
import java.awt.peer.MenuItemPeer;
-import java.awt.peer.MenuPeer;
public class GtkMenuItemPeer extends GtkMenuComponentPeer
implements MenuItemPeer
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkMouseInfoPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkMouseInfoPeer.java
new file mode 100644
index 0000000..02bf84d
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkMouseInfoPeer.java
@@ -0,0 +1,76 @@
+/* GtkToolkit.java -- Implements an AWT Toolkit using GTK for peers
+ Copyright (C) 2006
+ Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.gtk;
+
+import java.awt.Point;
+import java.awt.GraphicsDevice;
+import java.awt.Window;
+import java.awt.peer.MouseInfoPeer;
+
+/**
+ * The MouseInfoPeer is so small, I'm including it here.
+ */
+public class GtkMouseInfoPeer implements MouseInfoPeer
+{
+ private static GdkGraphicsEnvironment gde = new GdkGraphicsEnvironment();
+
+ public int fillPointWithCoords(Point p)
+ {
+ int[] coords = gde.getMouseCoordinates();
+ p.x = coords[1];
+ p.y = coords[2];
+ return coords[0];
+ }
+
+ public boolean isWindowUnderMouse(Window w)
+ {
+ int[] coords = gde.getMouseCoordinates();
+ GraphicsDevice[] gds = gde.getScreenDevices();
+
+ // Check if the screen of the Window and the cursor match
+ if( gds[ coords[0] ] != w.getGraphicsConfiguration().getDevice() )
+ return false;
+
+ // Return the bounds-check.
+ Point p = w.getLocationOnScreen();
+ return (coords[1] >= p.x && coords[1] < p.x + w.getWidth() &&
+ coords[2] >= p.y && coords[2] < p.y + w.getHeight() );
+ }
+}
+
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkPanelPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkPanelPeer.java
index 51fe2bc..e0053f7 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkPanelPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkPanelPeer.java
@@ -1,5 +1,5 @@
/* GtkPanelPeer.java -- Implements PanelPeer with GTK
- Copyright (C) 1998, 1999 Free Software Foundation, Inc.
+ Copyright (C) 1998, 1999, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -41,7 +41,6 @@ package gnu.java.awt.peer.gtk;
import java.awt.AWTEvent;
import java.awt.Panel;
import java.awt.event.MouseEvent;
-import java.awt.event.PaintEvent;
import java.awt.peer.PanelPeer;
public class GtkPanelPeer extends GtkContainerPeer
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkPopupMenuPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkPopupMenuPeer.java
index 525a910..4d66a3f 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkPopupMenuPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkPopupMenuPeer.java
@@ -40,7 +40,6 @@ package gnu.java.awt.peer.gtk;
import java.awt.Component;
import java.awt.Event;
-import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.peer.PopupMenuPeer;
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkScrollbarPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkScrollbarPeer.java
index 9b31a73..e4147d3 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkScrollbarPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkScrollbarPeer.java
@@ -38,8 +38,6 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.Adjustable;
-import java.awt.EventQueue;
import java.awt.Scrollbar;
import java.awt.event.AdjustmentEvent;
import java.awt.peer.ScrollbarPeer;
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkToolkit.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkToolkit.java
index 163fc52..6aa87fc 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkToolkit.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkToolkit.java
@@ -39,32 +39,83 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import gnu.classpath.Configuration;
import gnu.java.awt.EmbeddedWindow;
+import gnu.java.awt.dnd.GtkMouseDragGestureRecognizer;
+import gnu.java.awt.dnd.peer.gtk.GtkDragSourceContextPeer;
import gnu.java.awt.peer.ClasspathFontPeer;
-import gnu.java.awt.peer.ClasspathTextLayoutPeer;
import gnu.java.awt.peer.EmbeddedWindowPeer;
-import java.awt.*;
+import java.awt.AWTException;
+import java.awt.Button;
+import java.awt.Canvas;
+import java.awt.Checkbox;
+import java.awt.CheckboxMenuItem;
+import java.awt.Choice;
+import java.awt.Component;
+import java.awt.Cursor;
+import java.awt.Dialog;
+import java.awt.Dimension;
+import java.awt.EventQueue;
+import java.awt.FileDialog;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Frame;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.Image;
+import java.awt.Label;
+import java.awt.List;
+import java.awt.Menu;
+import java.awt.MenuBar;
+import java.awt.MenuItem;
+import java.awt.Panel;
+import java.awt.Point;
+import java.awt.PopupMenu;
+import java.awt.PrintJob;
+import java.awt.Rectangle;
+import java.awt.ScrollPane;
+import java.awt.Scrollbar;
+import java.awt.TextArea;
+import java.awt.TextField;
+import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.dnd.DragGestureEvent;
+import java.awt.dnd.DragGestureListener;
+import java.awt.dnd.DragGestureRecognizer;
+import java.awt.dnd.DragSource;
import java.awt.dnd.peer.DragSourceContextPeer;
-import java.awt.font.FontRenderContext;
import java.awt.im.InputMethodHighlight;
-import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
-import java.awt.image.ImageConsumer;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
-import java.awt.peer.*;
+import java.awt.peer.ButtonPeer;
+import java.awt.peer.CanvasPeer;
+import java.awt.peer.CheckboxMenuItemPeer;
+import java.awt.peer.CheckboxPeer;
+import java.awt.peer.ChoicePeer;
+import java.awt.peer.DialogPeer;
+import java.awt.peer.FileDialogPeer;
+import java.awt.peer.FontPeer;
+import java.awt.peer.FramePeer;
+import java.awt.peer.LabelPeer;
+import java.awt.peer.ListPeer;
+import java.awt.peer.MenuBarPeer;
+import java.awt.peer.MenuItemPeer;
+import java.awt.peer.MouseInfoPeer;
+import java.awt.peer.MenuPeer;
+import java.awt.peer.PanelPeer;
+import java.awt.peer.PopupMenuPeer;
+import java.awt.peer.RobotPeer;
+import java.awt.peer.ScrollPanePeer;
+import java.awt.peer.ScrollbarPeer;
+import java.awt.peer.TextAreaPeer;
+import java.awt.peer.TextFieldPeer;
+import java.awt.peer.WindowPeer;
import java.io.InputStream;
import java.net.URL;
-import java.text.AttributedString;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Hashtable;
-import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
@@ -310,6 +361,11 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
public PrintJob getPrintJob (Frame frame, String jobtitle, Properties props)
{
+ SecurityManager sm;
+ sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPrintJobAccess();
+
return null;
}
@@ -528,12 +584,6 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
}
}
- public ClasspathTextLayoutPeer getClasspathTextLayoutPeer (AttributedString str,
- FontRenderContext frc)
- {
- return new GdkTextLayout(str, frc);
- }
-
protected EventQueue getSystemEventQueueImpl()
{
synchronized (GtkToolkit.class)
@@ -555,7 +605,26 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent e)
{
- throw new Error("not implemented");
+ return new GtkDragSourceContextPeer(e);
+ }
+
+ public DragGestureRecognizer createDragGestureRecognizer(Class recognizer,
+ DragSource ds,
+ Component comp,
+ int actions,
+ DragGestureListener l)
+ {
+ if (recognizer.getName().equals("java.awt.dnd.MouseDragGestureRecognizer"))
+ {
+ GtkMouseDragGestureRecognizer gestureRecognizer
+ = new GtkMouseDragGestureRecognizer(ds, comp, actions, l);
+ gestureRecognizer.registerListeners();
+ return gestureRecognizer;
+ }
+ else
+ {
+ return null;
+ }
}
public Map mapInputMethodHighlight(InputMethodHighlight highlight)
@@ -593,4 +662,12 @@ public class GtkToolkit extends gnu.java.awt.ClasspathToolkit
}
public static native void gtkMain();
+
+ protected MouseInfoPeer getMouseInfoPeer()
+ {
+ return new GtkMouseInfoPeer();
+ }
+
+ public native int getMouseNumberOfButtons();
+
} // class GtkToolkit
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkVolatileImage.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkVolatileImage.java
index f38007f..44e7b02 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkVolatileImage.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkVolatileImage.java
@@ -50,6 +50,8 @@ public class GtkVolatileImage extends VolatileImage
int width, height;
private ImageCapabilities caps;
+ final GtkComponentPeer component;
+
/**
* Don't touch, accessed from native code.
*/
@@ -85,6 +87,7 @@ public class GtkVolatileImage extends VolatileImage
this.width = width;
this.height = height;
this.caps = caps;
+ this.component = component;
nativePointer = init( component, width, height );
}
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/GtkWindowPeer.java b/libjava/classpath/gnu/java/awt/peer/gtk/GtkWindowPeer.java
index d15beac..866d9c8 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/GtkWindowPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/GtkWindowPeer.java
@@ -38,13 +38,14 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.AWTEvent;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Graphics;
+import java.awt.KeyboardFocusManager;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ComponentEvent;
+import java.awt.event.FocusEvent;
import java.awt.event.PaintEvent;
import java.awt.event.WindowEvent;
import java.awt.peer.WindowPeer;
@@ -70,7 +71,8 @@ public class GtkWindowPeer extends GtkContainerPeer
native void gtkWindowSetTitle (String title);
native void gtkWindowSetResizable (boolean resizable);
native void gtkWindowSetModal (boolean modal);
-
+ native void gtkWindowSetAlwaysOnTop ( boolean alwaysOnTop );
+ native boolean gtkWindowHasFocus();
native void realize ();
/** Returns the cached width of the AWT window component. */
@@ -275,10 +277,13 @@ public class GtkWindowPeer extends GtkContainerPeer
else
q().postEvent (new WindowEvent ((Window) awtComponent, id, opposite));
}
+
+ /**
+ * Update the always-on-top status of the native window.
+ */
public void updateAlwaysOnTop()
{
- // TODO Auto-generated method stub
-
+ gtkWindowSetAlwaysOnTop( ((Window)awtComponent).isAlwaysOnTop() );
}
protected void postExposeEvent (int x, int y, int width, int height)
@@ -299,7 +304,40 @@ public class GtkWindowPeer extends GtkContainerPeer
// TODO Auto-generated method stub
return false;
}
-
+
+ public boolean requestFocus (Component request, boolean temporary,
+ boolean allowWindowFocus, long time)
+ {
+ assert request == awtComponent || isLightweightDescendant(request);
+ boolean retval = false;
+ if (gtkWindowHasFocus())
+ {
+ KeyboardFocusManager kfm =
+ KeyboardFocusManager.getCurrentKeyboardFocusManager();
+ Component currentFocus = kfm.getFocusOwner();
+ if (currentFocus == request)
+ // Nothing to do in this trivial case.
+ retval = true;
+ else
+ {
+ // Requested component is a lightweight descendant of this one
+ // or the actual heavyweight.
+ // Since this (native) component is already focused, we simply
+ // change the actual focus and be done.
+ postFocusEvent(FocusEvent.FOCUS_GAINED, temporary);
+ retval = true;
+ }
+ }
+ else
+ {
+ if (allowWindowFocus)
+ {
+ retval = requestWindowFocus();
+ }
+ }
+ return retval;
+ }
+
public Graphics getGraphics ()
{
Graphics g = super.getGraphics ();
diff --git a/libjava/classpath/gnu/java/awt/peer/gtk/VolatileImageGraphics.java b/libjava/classpath/gnu/java/awt/peer/gtk/VolatileImageGraphics.java
index fa84ea0..5849655 100644
--- a/libjava/classpath/gnu/java/awt/peer/gtk/VolatileImageGraphics.java
+++ b/libjava/classpath/gnu/java/awt/peer/gtk/VolatileImageGraphics.java
@@ -38,25 +38,11 @@ exception statement from your version. */
package gnu.java.awt.peer.gtk;
-import java.awt.Color;
import java.awt.Graphics;
-import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
-import java.awt.Point;
-import java.awt.Rectangle;
-import java.awt.Shape;
-import java.awt.font.GlyphVector;
-import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
-import java.awt.image.BufferedImage;
-import java.awt.image.DataBuffer;
-import java.awt.image.DataBufferInt;
-import java.awt.image.ColorModel;
-import java.awt.image.DirectColorModel;
-import java.awt.image.RenderedImage;
import java.awt.image.ImageObserver;
-import java.util.WeakHashMap;
public class VolatileImageGraphics extends ComponentGraphics
{
@@ -83,7 +69,7 @@ public class VolatileImageGraphics extends ComponentGraphics
public GraphicsConfiguration getDeviceConfiguration()
{
- return null;
+ return owner.component.getGraphicsConfiguration();
}
public Graphics create()
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtCheckboxPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtCheckboxPeer.java
index 788e08e..acac5e4 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtCheckboxPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtCheckboxPeer.java
@@ -1,5 +1,5 @@
/* QtCheckboxPeer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -37,7 +37,6 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
-import java.awt.Rectangle;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.event.ItemEvent;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtComponentGraphics.java b/libjava/classpath/gnu/java/awt/peer/qt/QtComponentGraphics.java
index 7395a8e..c5c839e 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtComponentGraphics.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtComponentGraphics.java
@@ -1,5 +1,5 @@
/* QtComponentGraphics.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -40,9 +40,7 @@ package gnu.java.awt.peer.qt;
import java.awt.Color;
import java.awt.GraphicsConfiguration;
import java.awt.Graphics;
-import java.awt.Graphics2D;
import java.awt.Rectangle;
-import java.awt.Paint;
/**
* QtComponentPainter is a Graphics2D context for painting directly to AWT
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtComponentPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtComponentPeer.java
index d5662a8..4d7b58c 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtComponentPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtComponentPeer.java
@@ -1,5 +1,5 @@
/* QtComponentPeer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -41,7 +41,6 @@ import java.awt.AWTEvent;
import java.awt.AWTException;
import java.awt.BufferCapabilities;
import java.awt.Component;
-import java.awt.Container;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtContainerPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtContainerPeer.java
index 3782d78..ec04b05 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtContainerPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtContainerPeer.java
@@ -1,5 +1,5 @@
/* QtContainerPeer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -37,7 +37,6 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
-import java.awt.Container;
import java.awt.Component;
import java.awt.Insets;
import java.awt.peer.ContainerPeer;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtDialogPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtDialogPeer.java
index 0da2e4e..23e5c06 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtDialogPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtDialogPeer.java
@@ -1,5 +1,5 @@
/* QtDialogPeer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,8 +38,6 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
import java.awt.Dialog;
-import java.awt.MenuBar;
-import java.awt.Rectangle;
import java.awt.peer.DialogPeer;
public class QtDialogPeer extends QtWindowPeer implements DialogPeer
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtEmbeddedWindowPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtEmbeddedWindowPeer.java
index cac12b9..0f859b7 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtEmbeddedWindowPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtEmbeddedWindowPeer.java
@@ -1,5 +1,5 @@
/* QtEmbeddedWindowPeer.java -- embedded window peer
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,7 +38,6 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
import java.awt.Component;
-import java.awt.peer.WindowPeer;
import gnu.java.awt.peer.EmbeddedWindowPeer;
/**
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtFontMetrics.java b/libjava/classpath/gnu/java/awt/peer/qt/QtFontMetrics.java
index e403239..2438fcc 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtFontMetrics.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtFontMetrics.java
@@ -1,5 +1,5 @@
/* QtFontMetrics.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -41,9 +41,6 @@ import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.geom.Rectangle2D;
-import java.awt.font.FontRenderContext;
-import java.awt.font.GlyphVector;
-import java.awt.font.LineMetrics;
public class QtFontMetrics extends FontMetrics
{
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtFontPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtFontPeer.java
index ee88c7d..d847a80 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtFontPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtFontPeer.java
@@ -1,5 +1,5 @@
/* QtFontPeer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -46,7 +46,6 @@ import java.awt.font.LineMetrics;
import java.text.CharacterIterator;
import java.util.Locale;
import java.util.Map;
-import java.awt.peer.FontPeer;
import gnu.java.awt.peer.ClasspathFontPeer;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtGraphics.java b/libjava/classpath/gnu/java/awt/peer/qt/QtGraphics.java
index f9b4f26..842cbbbf 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtGraphics.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtGraphics.java
@@ -1,5 +1,5 @@
/* QtGraphics.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
import java.awt.AlphaComposite;
+import java.awt.AWTPermission;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
@@ -57,7 +58,6 @@ import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
-import java.awt.geom.PathIterator;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
@@ -605,8 +605,16 @@ public abstract class QtGraphics extends Graphics2D
composite = comp;
}
else
- throw new UnsupportedOperationException("We don't support custom"+
- " composites yet.");
+ {
+ // FIXME: this check is only required "if this Graphics2D
+ // context is drawing to a Component on the display screen".
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPermission(new AWTPermission("readDisplayPixels"));
+
+ throw new UnsupportedOperationException("We don't support custom"+
+ " composites yet.");
+ }
}
public Composite getComposite()
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtGraphicsEnvironment.java b/libjava/classpath/gnu/java/awt/peer/qt/QtGraphicsEnvironment.java
index 142b140..15a0159 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtGraphicsEnvironment.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtGraphicsEnvironment.java
@@ -1,5 +1,5 @@
/* QtGraphicsEnvironment.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -41,7 +41,6 @@ import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
-import java.awt.HeadlessException;
import java.awt.image.BufferedImage;
import java.util.Locale;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtImage.java b/libjava/classpath/gnu/java/awt/peer/qt/QtImage.java
index 9095464..b6fbb1d 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtImage.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtImage.java
@@ -1,5 +1,5 @@
/* QtImage.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -43,7 +43,6 @@ import java.awt.Image;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.MemoryImageSource;
-import java.awt.image.ImageConsumer;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtImageConsumer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtImageConsumer.java
index aec0671..7096c21 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtImageConsumer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtImageConsumer.java
@@ -1,5 +1,5 @@
/* QtImageConsumer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -37,15 +37,10 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
-import java.awt.Graphics;
-import java.awt.Image;
import java.awt.image.ColorModel;
-import java.awt.image.DirectColorModel;
import java.awt.image.ImageConsumer;
-import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.util.Hashtable;
-import java.util.Vector;
/**
* Helper class to QtImage. Sits and gathers pixels for a QtImage and then
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtImageDirectGraphics.java b/libjava/classpath/gnu/java/awt/peer/qt/QtImageDirectGraphics.java
index 5a6f318..d49084a 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtImageDirectGraphics.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtImageDirectGraphics.java
@@ -1,5 +1,5 @@
/* QtImageDirectGraphics.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,29 +38,10 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
import java.awt.Color;
-import java.awt.GraphicsConfiguration;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
import java.awt.Image;
-import java.awt.Paint;
-import java.awt.Rectangle;
-import java.util.Stack;
import java.awt.Shape;
-import java.awt.Stroke;
-import java.awt.font.FontRenderContext;
-import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
-import java.awt.geom.PathIterator;
-import java.awt.geom.Arc2D;
-import java.awt.geom.Ellipse2D;
-import java.awt.geom.Line2D;
-import java.awt.geom.Rectangle2D;
-import java.awt.geom.RoundRectangle2D;
-import java.awt.image.BufferedImage;
-import java.awt.image.BufferedImageOp;
import java.awt.image.ImageObserver;
-import java.awt.image.RenderedImage;
-import java.awt.image.renderable.RenderableImage;
/**
* A QtImagePainter that does an update after every drawing op.
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtImageGraphics.java b/libjava/classpath/gnu/java/awt/peer/qt/QtImageGraphics.java
index f8a7e51..1224d69 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtImageGraphics.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtImageGraphics.java
@@ -1,5 +1,5 @@
/* QtImageGraphics.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -40,9 +40,7 @@ package gnu.java.awt.peer.qt;
import java.awt.Color;
import java.awt.GraphicsConfiguration;
import java.awt.Graphics;
-import java.awt.Graphics2D;
import java.awt.Image;
-import java.awt.Paint;
import java.awt.Rectangle;
import java.util.Stack;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtMenuBarPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtMenuBarPeer.java
index d8f0d1f..c91b37f 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtMenuBarPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtMenuBarPeer.java
@@ -1,5 +1,5 @@
/* QtMenuBarPeer.java -- Qt peer for a menu bar.
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -40,7 +40,6 @@ package gnu.java.awt.peer.qt;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.peer.MenuBarPeer;
-import java.util.Vector;
public class QtMenuBarPeer extends QtMenuComponentPeer implements MenuBarPeer
{
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtMenuItemPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtMenuItemPeer.java
index 34753cb..7658ff0 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtMenuItemPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtMenuItemPeer.java
@@ -1,5 +1,5 @@
/* QtMenuItemPeer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -37,7 +37,6 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
-import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.CheckboxMenuItem;
import java.awt.event.ActionEvent;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtPopupMenuPeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtPopupMenuPeer.java
index 81577cc..b96c5c5 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtPopupMenuPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtPopupMenuPeer.java
@@ -1,5 +1,5 @@
/* QtPopupMenuPeer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,12 +38,9 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
import java.awt.Component;
-import java.awt.Menu;
-import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.Event;
-import java.awt.event.ActionEvent;
import java.awt.peer.PopupMenuPeer;
public class QtPopupMenuPeer extends QtMenuPeer implements PopupMenuPeer
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtScreenDeviceConfiguration.java b/libjava/classpath/gnu/java/awt/peer/qt/QtScreenDeviceConfiguration.java
index 045cfdf..c67b55b 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtScreenDeviceConfiguration.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtScreenDeviceConfiguration.java
@@ -1,5 +1,5 @@
/* QtScreenDeviceConfiguration.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -37,11 +37,9 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
-import java.awt.DisplayMode;
import java.awt.ImageCapabilities;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
-import java.awt.GraphicsConfigTemplate;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtScrollPanePeer.java b/libjava/classpath/gnu/java/awt/peer/qt/QtScrollPanePeer.java
index 02fa8fb..c3731cb 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtScrollPanePeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtScrollPanePeer.java
@@ -1,5 +1,5 @@
/* QtScrollPanePeer.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -38,7 +38,6 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
import java.awt.Adjustable;
-import java.awt.Dimension;
import java.awt.Insets;
import java.awt.ScrollPane;
import java.awt.peer.ScrollPanePeer;
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtToolkit.java b/libjava/classpath/gnu/java/awt/peer/qt/QtToolkit.java
index 73652f8..5116769 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtToolkit.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtToolkit.java
@@ -1,5 +1,5 @@
/* QtToolkit.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -37,19 +37,16 @@ exception statement from your version. */
package gnu.java.awt.peer.qt;
-import gnu.classpath.Configuration;
import gnu.java.awt.EmbeddedWindow;
import gnu.java.awt.peer.ClasspathFontPeer;
import gnu.java.awt.peer.EmbeddedWindowPeer;
-import gnu.java.awt.peer.ClasspathTextLayoutPeer;
-import java.awt.AWTEvent;
+
import java.awt.AWTException;
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Checkbox;
import java.awt.CheckboxMenuItem;
import java.awt.Choice;
-import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
@@ -68,18 +65,13 @@ import java.awt.TextField;
import java.awt.FileDialog;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
-import java.awt.HeadlessException;
import java.awt.PopupMenu;
import java.awt.PrintJob;
import java.awt.Scrollbar;
import java.awt.ScrollPane;
-import java.awt.Toolkit;
import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.dnd.DragGestureEvent;
-import java.awt.dnd.DragGestureListener;
-import java.awt.dnd.DragGestureRecognizer;
-import java.awt.dnd.DragSource;
import java.awt.dnd.peer.DragSourceContextPeer;
import java.awt.event.AWTEventListener;
import java.awt.image.ColorModel;
@@ -91,37 +83,29 @@ import java.awt.peer.ButtonPeer;
import java.awt.peer.FontPeer;
import java.awt.peer.PanelPeer;
import java.awt.peer.CanvasPeer;
-import java.awt.peer.FramePeer;
+import java.awt.peer.FramePeer;
import java.awt.peer.PopupMenuPeer;
import java.awt.peer.CheckboxMenuItemPeer;
import java.awt.peer.LabelPeer;
import java.awt.peer.RobotPeer;
import java.awt.peer.CheckboxPeer;
-import java.awt.peer.LightweightPeer;
import java.awt.peer.ScrollPanePeer;
-import java.awt.peer.ChoicePeer;
+import java.awt.peer.ChoicePeer;
import java.awt.peer.ListPeer;
import java.awt.peer.ScrollbarPeer;
-import java.awt.peer.ComponentPeer;
import java.awt.peer.MenuBarPeer;
import java.awt.peer.TextAreaPeer;
-import java.awt.peer.ContainerPeer;
-import java.awt.peer.MenuComponentPeer;
-import java.awt.peer.TextComponentPeer;
import java.awt.peer.DialogPeer;
import java.awt.peer.MenuItemPeer;
import java.awt.peer.TextFieldPeer;
import java.awt.peer.FileDialogPeer;
import java.awt.peer.MenuPeer;
import java.awt.peer.WindowPeer;
-import java.awt.font.FontRenderContext;
import java.io.InputStream;
import java.net.URL;
-import java.text.AttributedString;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-import javax.imageio.spi.IIORegistry;
import gnu.java.awt.ClasspathToolkit;
@@ -402,6 +386,11 @@ public class QtToolkit extends ClasspathToolkit
String jobtitle,
Properties props)
{
+ SecurityManager sm;
+ sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPrintJobAccess();
+
throw new RuntimeException("Not implemented");
}
@@ -445,12 +434,6 @@ public class QtToolkit extends ClasspathToolkit
return new QtFontPeer (name, attrs);
}
- public ClasspathTextLayoutPeer getClasspathTextLayoutPeer(AttributedString str,
- FontRenderContext frc)
- {
- return null;
- }
-
// FIXME
public Font createFont(int format, InputStream stream)
{
diff --git a/libjava/classpath/gnu/java/awt/peer/qt/QtVolatileImage.java b/libjava/classpath/gnu/java/awt/peer/qt/QtVolatileImage.java
index 0ec61de..c81bb2a 100644
--- a/libjava/classpath/gnu/java/awt/peer/qt/QtVolatileImage.java
+++ b/libjava/classpath/gnu/java/awt/peer/qt/QtVolatileImage.java
@@ -1,5 +1,5 @@
/* QtVolatileImage.java --
- Copyright (C) 2005 Free Software Foundation, Inc.
+ Copyright (C) 2005, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -47,15 +47,11 @@ import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.MemoryImageSource;
-import java.awt.image.ImageConsumer;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.awt.image.VolatileImage;
-import java.io.File;
-import java.io.IOException;
import java.util.Hashtable;
import java.util.WeakHashMap;
-import java.util.Vector;
/**
* QtVolatileImage - wraps a QImage
diff --git a/libjava/classpath/gnu/java/awt/peer/swing/SwingComponentPeer.java b/libjava/classpath/gnu/java/awt/peer/swing/SwingComponentPeer.java
index f60c8e9..96ccc00 100644
--- a/libjava/classpath/gnu/java/awt/peer/swing/SwingComponentPeer.java
+++ b/libjava/classpath/gnu/java/awt/peer/swing/SwingComponentPeer.java
@@ -48,8 +48,6 @@ import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GraphicsConfiguration;
-import java.awt.GraphicsDevice;
-import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
@@ -101,8 +99,8 @@ public class SwingComponentPeer
/**
* Creates a SwingComponentPeer instance. Subclasses are expected to call
* this constructor and thereafter call
- * {@link #init(Component, SwingComponent)} in order to setup the AWT and
- * Swing components properly.
+ * {@link #init(Component,SwingComponent)}
+ * in order to setup the AWT and Swing components properly.
*/
protected SwingComponentPeer()
{
@@ -167,12 +165,9 @@ public class SwingComponentPeer
*/
public Image createImage(int width, int height)
{
- GraphicsEnvironment graphicsEnv =
- GraphicsEnvironment.getLocalGraphicsEnvironment();
- GraphicsDevice dev = graphicsEnv.getDefaultScreenDevice();
- GraphicsConfiguration conf = dev.getDefaultConfiguration();
- Image image = conf.createCompatibleImage(width, height);
- return image;
+ Component parent = awtComponent.getParent();
+ ComponentPeer parentPeer = parent.getPeer();
+ return parentPeer.createImage(width, height);
}
/**
@@ -336,21 +331,24 @@ public class SwingComponentPeer
{
case PaintEvent.UPDATE:
case PaintEvent.PAINT:
- Graphics g = getGraphics();
- Rectangle clip = ((PaintEvent)e).getUpdateRect();
- g.clipRect(clip.x, clip.y, clip.width, clip.height);
- //if (this instanceof LightweightPeer)
- // {
+ // This only will work when the component is showing.
+ if (awtComponent.isShowing())
+ {
+ Graphics g = getGraphics();
+ Rectangle clip = ((PaintEvent)e).getUpdateRect();
+ g.clipRect(clip.x, clip.y, clip.width, clip.height);
+ //if (this instanceof LightweightPeer)
+ // {
if (e.getID() == PaintEvent.UPDATE)
awtComponent.update(g);
else
awtComponent.paint(g);
- // }
- // We paint the 'heavyweights' at last, so that they appear on top of
- // everything else.
- peerPaint(g);
-
- g.dispose();
+ // }
+ // We paint the 'heavyweights' at last, so that they appear on top of
+ // everything else.
+ peerPaint(g);
+ g.dispose();
+ }
break;
case MouseEvent.MOUSE_PRESSED:
case MouseEvent.MOUSE_RELEASED:
@@ -384,6 +382,11 @@ public class SwingComponentPeer
{
if (swingComponent != null)
swingComponent.getJComponent().setVisible(false);
+
+ Component parent = awtComponent.getParent();
+ if (parent != null)
+ parent.repaint(awtComponent.getX(), awtComponent.getY(),
+ awtComponent.getWidth(), awtComponent.getHeight());
}
/**
@@ -470,17 +473,15 @@ public class SwingComponentPeer
public boolean prepareImage(Image img, int width, int height, ImageObserver ob)
{
Component parent = awtComponent.getParent();
- boolean res;
if(parent != null)
- {
- ComponentPeer parentPeer = parent.getPeer();
- res = parentPeer.prepareImage(img, width, height, ob);
- }
+ {
+ ComponentPeer parentPeer = parent.getPeer();
+ return parentPeer.prepareImage(img, width, height, ob);
+ }
else
- {
- res = Toolkit.getDefaultToolkit().prepareImage(img, width, height, ob);
- }
- return res;
+ {
+ return Toolkit.getDefaultToolkit().prepareImage(img, width, height, ob);
+ }
}
public void print(Graphics graphics)
@@ -662,8 +663,10 @@ public class SwingComponentPeer
*/
public void setVisible(boolean visible)
{
- if (swingComponent != null)
- swingComponent.getJComponent().setVisible(visible);
+ if (visible)
+ show();
+ else
+ hide();
}
/**
@@ -782,8 +785,13 @@ public class SwingComponentPeer
public VolatileImage createVolatileImage(int width, int height)
{
Component parent = awtComponent.getParent();
- ComponentPeer parentPeer = parent.getPeer();
- return parentPeer.createVolatileImage(width, height);
+ VolatileImage im = null;
+ if (parent != null)
+ {
+ ComponentPeer parentPeer = parent.getPeer();
+ im = parentPeer.createVolatileImage(width, height);
+ }
+ return im;
}
/**
diff --git a/libjava/classpath/gnu/java/awt/peer/x/GLGraphics.java b/libjava/classpath/gnu/java/awt/peer/x/GLGraphics.java
new file mode 100644
index 0000000..c80c85c
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/GLGraphics.java
@@ -0,0 +1,123 @@
+/* GLGraphics.java -- Graphics2D impl on top of GLX
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Color;
+import java.awt.GraphicsConfiguration;
+import java.awt.image.ColorModel;
+
+import gnu.java.awt.java2d.AbstractGraphics2D;
+import gnu.x11.extension.glx.GL;
+
+/**
+ * An implementation of Graphics2D on top of the GLX extension of X.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class GLGraphics extends AbstractGraphics2D
+{
+
+ /**
+ * The rendering context.
+ */
+ private GL gl;
+
+ /**
+ * Creates a new GLGraphics that paints on the specified GL context.
+ *
+ * @param g the GL context to paint to
+ */
+ GLGraphics(GL g)
+ {
+ gl = g;
+ }
+
+ public void setBackground(Color b)
+ {
+ super.setBackground(b);
+ gl.clear_color(b.getRed() / 255.F, b.getGreen() / 255.F,
+ b.getBlue() / 255.F, b.getAlpha() / 255.F);
+ }
+
+ public void clearRect(int x, int y, int w, int h)
+ {
+ // TODO: Maybe use fillRect().
+ gl.clear(GL.COLOR_BUFFER_BIT);
+ }
+
+ public void drawLine(int x1, int y1, int x2, int y2)
+ {
+ gl.begin(GL.LINES);
+ gl.vertex2i(x1, y1);
+ gl.vertex2i(x2, y2);
+ gl.end();
+ // TODO: Maybe do:
+ // gl.flush();
+ }
+
+ public void drawRect(int x, int y, int w, int h)
+ {
+ gl.polygon_mode(GL.FRONT_AND_BACK, GL.LINE);
+ gl.begin(GL.POLYGON);
+ gl.recti(x, y, x + w, y + h);
+ gl.end();
+ // TODO: Maybe do:
+ // gl.flush();
+ }
+
+ public void fillRect(int x, int y, int w, int h)
+ {
+ gl.polygon_mode(GL.FRONT_AND_BACK, GL.FILL);
+ gl.recti(x, y, x + w, y + h);
+ // TODO: Maybe do:
+ // gl.flush();
+ }
+
+ protected ColorModel getColorModel()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public GraphicsConfiguration getDeviceConfiguration()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/ImageConverter.java b/libjava/classpath/gnu/java/awt/peer/x/ImageConverter.java
new file mode 100644
index 0000000..6d32448
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/ImageConverter.java
@@ -0,0 +1,113 @@
+/* ImageConverter.java -- Convert arbitrary Image impl to XImage
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Color;
+import java.awt.Graphics;
+import java.awt.image.ColorModel;
+import java.awt.image.ImageConsumer;
+import java.util.Hashtable;
+
+/**
+ * Convert a non-XImage to an XImage.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class ImageConverter implements ImageConsumer
+{
+
+ private XImage image;
+ private Graphics imageGraphics;
+
+ public void setDimensions(int width, int height)
+ {
+ image = new XImage(width, height);
+ }
+
+ public void setProperties(Hashtable props)
+ {
+ // Ignore for now.
+ }
+
+ public void setColorModel(ColorModel model)
+ {
+ // Ignore for now.
+ }
+
+ public void setHints(int flags)
+ {
+ // Ignore for now.
+ }
+
+ public void setPixels(int x, int y, int w, int h, ColorModel model,
+ byte[] pixels, int offset, int scansize)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public void setPixels(int x, int y, int w, int h, ColorModel model,
+ int[] pixels, int offset, int scansize)
+ {
+ System.err.println("transferType: " + model.getTransferType());
+ System.err.println("colorModel: " + model);
+ if (imageGraphics == null)
+ imageGraphics = image.getGraphics();
+ int xend = x + w;
+ int yend = y + h;
+ for (int yy = y; yy < yend; yy++)
+ {
+ for (int xx = x; xx < xend; xx++)
+ {
+ int pixel = pixels[yy * scansize + xx + offset];
+ imageGraphics.setColor(new Color(model.getRGB(pixel)));
+ imageGraphics.fillRect(xx, yy, 1, 1);
+ }
+ }
+ }
+
+ public void imageComplete(int status)
+ {
+ // Nothing to do here.
+ }
+
+ XImage getXImage()
+ {
+ return image;
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/KeyboardMapping.java b/libjava/classpath/gnu/java/awt/peer/x/KeyboardMapping.java
new file mode 100644
index 0000000..8e0a31f
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/KeyboardMapping.java
@@ -0,0 +1,415 @@
+/* KeyboardMapping.java -- Maps X keysyms to Java keyCode and keyChar
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.x;
+
+import gnu.x11.Input;
+import gnu.x11.keysym.Latin1;
+import gnu.x11.keysym.Misc;
+
+import java.awt.event.KeyEvent;
+
+/**
+ * Defines the keyboard mapping from X keysyms to Java
+ * keycodes and keychars.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+final class KeyboardMapping
+{
+
+ /**
+ * Maps X keycodes to AWT keycodes.
+ *
+ * @param xInput the X input event
+ * @param xKeyCode the X keycode to map
+ * @param xMods the X modifiers
+ *
+ * @return the AWT keycode and keychar
+ */
+ static int mapToKeyCode(gnu.x11.Input xInput, int xKeyCode, int xMods)
+ {
+ int mapped = KeyEvent.VK_UNDEFINED;
+ int keysym = xInput.keycode_to_keysym(xKeyCode, xMods, true);
+
+ // Special keys.
+ if (keysym >= 255 << 8)
+ {
+ // FIXME: Add missing mappings.
+ switch (keysym)
+ {
+ case Misc.BACKSPACE:
+ mapped = KeyEvent.VK_BACK_SPACE;
+ break;
+ case Misc.TAB:
+ mapped = KeyEvent.VK_TAB;
+ break;
+ case Misc.CLEAR:
+ mapped = KeyEvent.VK_CLEAR;
+ break;
+ case Misc.RETURN:
+ mapped = KeyEvent.VK_ENTER;
+ break;
+ case Misc.PAUSE:
+ mapped = KeyEvent.VK_PAUSE;
+ break;
+ case Misc.SCROLL_LOCK:
+ mapped = KeyEvent.VK_SCROLL_LOCK;
+ break;
+ case Misc.ESCAPE:
+ mapped = KeyEvent.VK_ESCAPE;
+ break;
+ case Misc.HOME:
+ mapped = KeyEvent.VK_HOME;
+ break;
+ case Misc.LEFT:
+ mapped = KeyEvent.VK_LEFT;
+ break;
+ case Misc.UP:
+ mapped = KeyEvent.VK_UP;
+ break;
+ case Misc.RIGHT:
+ mapped = KeyEvent.VK_RIGHT;
+ break;
+ case Misc.DOWN:
+ mapped = KeyEvent.VK_DOWN;
+ break;
+ case Misc.PAGE_UP:
+ mapped = KeyEvent.VK_PAGE_UP;
+ break;
+ case Misc.PAGE_DOWN:
+ mapped = KeyEvent.VK_PAGE_DOWN;
+ break;
+ case Misc.END:
+ mapped = KeyEvent.VK_END;
+ break;
+ case Misc.BEGIN:
+ mapped = KeyEvent.VK_BEGIN;
+ break;
+ case Misc.INSERT:
+ mapped = KeyEvent.VK_INSERT;
+ break;
+ case Misc.UNDO:
+ mapped = KeyEvent.VK_UNDO;
+ break;
+ case Misc.FIND:
+ mapped = KeyEvent.VK_FIND;
+ break;
+ case Misc.CANCEL:
+ mapped = KeyEvent.VK_CANCEL;
+ break;
+ case Misc.HELP:
+ mapped = KeyEvent.VK_HELP;
+ break;
+ case Misc.MODE_SWITCH:
+ mapped = KeyEvent.VK_MODECHANGE;
+ break;
+ case Misc.NUM_LOCK:
+ mapped = KeyEvent.VK_NUM_LOCK;
+ break;
+ case Misc.KP_LEFT:
+ mapped = KeyEvent.VK_KP_LEFT;
+ break;
+ case Misc.KP_UP:
+ mapped = KeyEvent.VK_KP_UP;
+ break;
+ case Misc.KP_RIGHT:
+ mapped = KeyEvent.VK_KP_RIGHT;
+ break;
+ case Misc.KP_DOWN:
+ mapped = KeyEvent.VK_KP_DOWN;
+ break;
+ case Misc.F1:
+ mapped = KeyEvent.VK_F1;
+ break;
+ case Misc.F2:
+ mapped = KeyEvent.VK_F2;
+ break;
+ case Misc.F3:
+ mapped = KeyEvent.VK_F3;
+ break;
+ case Misc.F4:
+ mapped = KeyEvent.VK_F4;
+ break;
+ case Misc.F5:
+ mapped = KeyEvent.VK_F5;
+ break;
+ case Misc.F6:
+ mapped = KeyEvent.VK_F6;
+ break;
+ case Misc.F7:
+ mapped = KeyEvent.VK_F7;
+ break;
+ case Misc.F8:
+ mapped = KeyEvent.VK_F8;
+ break;
+ case Misc.F9:
+ mapped = KeyEvent.VK_F9;
+ break;
+ case Misc.F10:
+ mapped = KeyEvent.VK_F10;
+ break;
+ case Misc.F11:
+ mapped = KeyEvent.VK_F11;
+ break;
+ case Misc.F12:
+ mapped = KeyEvent.VK_F12;
+ break;
+ case Misc.F13:
+ mapped = KeyEvent.VK_F13;
+ break;
+ case Misc.F14:
+ mapped = KeyEvent.VK_F14;
+ break;
+ case Misc.F15:
+ mapped = KeyEvent.VK_F15;
+ break;
+ case Misc.F16:
+ mapped = KeyEvent.VK_F16;
+ break;
+ case Misc.F17:
+ mapped = KeyEvent.VK_F17;
+ break;
+ case Misc.F18:
+ mapped = KeyEvent.VK_F18;
+ break;
+ case Misc.F19:
+ mapped = KeyEvent.VK_F19;
+ break;
+ case Misc.F20:
+ mapped = KeyEvent.VK_F20;
+ break;
+ case Misc.F21:
+ mapped = KeyEvent.VK_F21;
+ break;
+ case Misc.F22:
+ mapped = KeyEvent.VK_F22;
+ break;
+ case Misc.F23:
+ mapped = KeyEvent.VK_F23;
+ break;
+ case Misc.F24:
+ mapped = KeyEvent.VK_F24;
+ break;
+ case Misc.SHIFT_L:
+ case Misc.SHIFT_R:
+ mapped = KeyEvent.VK_SHIFT;
+ break;
+ case Misc.CONTROL_L:
+ case Misc.CONTROL_R:
+ mapped = KeyEvent.VK_CONTROL;
+ break;
+ case Misc.CAPS_LOCK:
+ case Misc.SHIFT_LOCK:
+ mapped = KeyEvent.VK_CAPS_LOCK;
+ break;
+ case Misc.META_L:
+ case Misc.META_R:
+ mapped = KeyEvent.VK_META;
+ break;
+ case Misc.ALT_L:
+ case Misc.ALT_R:
+ mapped = KeyEvent.VK_ALT;
+ break;
+ case Misc.DELETE:
+ mapped = KeyEvent.VK_DELETE;
+ break;
+ default:
+ mapped = KeyEvent.VK_UNDEFINED;
+ }
+ }
+ // Map Latin1 characters.
+ else if (keysym < 256)
+ {
+ // TODO: Add missing mappings, if any.
+ // Lowercase characters are mapped to
+ // their corresponding upper case pendants.
+ if (keysym >= Latin1.A_SMALL && keysym <= Latin1.Z_SMALL)
+ mapped = keysym - 0x20;
+ // Uppercase characters are mapped 1:1.
+ else if (keysym >= Latin1.A && keysym <= Latin1.Z)
+ mapped = keysym;
+ // Digits are mapped 1:1.
+ else if (keysym >= Latin1.NUM_0 && keysym <= Latin1.NUM_9)
+ mapped = keysym;
+ else
+ {
+ switch (keysym)
+ {
+ case Latin1.SPACE:
+ mapped = KeyEvent.VK_SPACE;
+ break;
+ case Latin1.EXCLAM:
+ mapped = KeyEvent.VK_EXCLAMATION_MARK;
+ break;
+ case Latin1.QUOTE_DBL:
+ mapped = KeyEvent.VK_QUOTEDBL;
+ break;
+ case Latin1.NUMBER_SIGN:
+ mapped = KeyEvent.VK_NUMBER_SIGN;
+ break;
+ case Latin1.DOLLAR:
+ mapped = KeyEvent.VK_DOLLAR;
+ break;
+ case Latin1.AMPERSAND:
+ mapped = KeyEvent.VK_AMPERSAND;
+ break;
+ case Latin1.APOSTROPHE:
+ mapped = KeyEvent.VK_QUOTE;
+ break;
+ case Latin1.PAREN_LEFT:
+ mapped = KeyEvent.VK_LEFT_PARENTHESIS;
+ break;
+ case Latin1.PAREN_RIGHT:
+ mapped = KeyEvent.VK_RIGHT_PARENTHESIS;
+ break;
+ case Latin1.ASTERISK:
+ mapped = KeyEvent.VK_ASTERISK;
+ break;
+ case Latin1.PLUS:
+ mapped = KeyEvent.VK_PLUS;
+ break;
+ case Latin1.COMMA:
+ mapped = KeyEvent.VK_COMMA;
+ break;
+ case Latin1.MINUS:
+ mapped = KeyEvent.VK_MINUS;
+ break;
+ case Latin1.PERIOD:
+ mapped = KeyEvent.VK_PERIOD;
+ break;
+ case Latin1.SLASH:
+ mapped = KeyEvent.VK_SLASH;
+ break;
+ case Latin1.COLON:
+ mapped = KeyEvent.VK_COLON;
+ break;
+ case Latin1.SEMICOLON:
+ mapped = KeyEvent.VK_SEMICOLON;
+ break;
+ case Latin1.LESS:
+ mapped = KeyEvent.VK_LESS;
+ break;
+ case Latin1.EQUAL:
+ mapped = KeyEvent.VK_EQUALS;
+ break;
+ case Latin1.GREATER:
+ mapped = KeyEvent.VK_GREATER;
+ break;
+ case Latin1.AT:
+ mapped = KeyEvent.VK_AT;
+ break;
+ case Latin1.BRACKET_LEFT:
+ mapped = KeyEvent.VK_OPEN_BRACKET;
+ break;
+ case Latin1.BACKSLASH:
+ mapped = KeyEvent.VK_BACK_SLASH;
+ break;
+ case Latin1.BRACKET_RIGHT:
+ mapped = KeyEvent.VK_CLOSE_BRACKET;
+ break;
+ case Latin1.ASCII_CIRCUM:
+ mapped = KeyEvent.VK_CIRCUMFLEX;
+ break;
+ case Latin1.UNDERSCORE:
+ mapped = KeyEvent.VK_UNDERSCORE;
+ break;
+ case Latin1.GRAVE:
+ mapped = KeyEvent.VK_DEAD_GRAVE;
+ break;
+ case Latin1.BRACE_LEFT:
+ mapped = KeyEvent.VK_BRACELEFT;
+ break;
+ case Latin1.BRACE_RIGHT:
+ mapped = KeyEvent.VK_BRACERIGHT;
+ break;
+ case Latin1.ASCII_TILDE:
+ mapped = KeyEvent.VK_DEAD_TILDE;
+ break;
+ case Latin1.EXCLAM_DOWN:
+ mapped = KeyEvent.VK_INVERTED_EXCLAMATION_MARK;
+ break;
+ default:
+ mapped = KeyEvent.VK_UNDEFINED;
+ }
+ }
+ }
+ return mapped;
+ }
+
+ /**
+ * Maps X keycodes+modifiers to Java keychars.
+ *
+ * @param xInput The X Input to use for mapping
+ * @param xKeyCode the X keycode
+ * @param xMods the X key modifiers
+ *
+ * @return the Java keychar
+ */
+ static char mapToKeyChar(gnu.x11.Input xInput, int xKeyCode, int xMods)
+ {
+ char mapped = KeyEvent.CHAR_UNDEFINED;
+ char keysym = (char) xInput.keycode_to_keysym(xKeyCode, xMods, false);
+ // FIXME: Map other encodings properly.
+ if (keysym < 256) // Latin1.
+ {
+ mapped = keysym;
+ }
+ return mapped;
+ }
+
+ /**
+ * Maps X modifier masks to AWT modifier masks.
+ *
+ * @param xMods the X modifiers
+ *
+ * @return the AWT modifiers
+ */
+ static int mapModifiers(int xMods)
+ {
+ int mods = 0;
+
+ if ((xMods & Input.SHIFT_MASK) != 0)
+ mods |= KeyEvent.SHIFT_MASK | KeyEvent.SHIFT_DOWN_MASK;
+ if ((xMods & Input.ALT_MASK) != 0)
+ mods |= KeyEvent.ALT_MASK | KeyEvent.ALT_DOWN_MASK;
+ if ((xMods & Input.CONTROL_MASK) != 0)
+ mods |= KeyEvent.CTRL_MASK | KeyEvent.CTRL_DOWN_MASK;
+
+ return mods;
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XDialogPeer.java b/libjava/classpath/gnu/java/awt/peer/x/XDialogPeer.java
new file mode 100644
index 0000000..45ad24d
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XDialogPeer.java
@@ -0,0 +1,61 @@
+/* XDialogPeer.java -- The peer for AWT dialogs
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Dialog;
+import java.awt.peer.DialogPeer;
+
+public class XDialogPeer
+ extends XWindowPeer
+ implements DialogPeer
+{
+
+ XDialogPeer(Dialog target)
+ {
+ super(target);
+ }
+
+ public void setResizable(boolean resizeable)
+ {
+ }
+
+ public void setTitle(String title)
+ {
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XEventPump.java b/libjava/classpath/gnu/java/awt/peer/x/XEventPump.java
new file mode 100644
index 0000000..870edf3
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XEventPump.java
@@ -0,0 +1,287 @@
+/* XEventPump.java -- Pumps events from X to AWT
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Graphics;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
+import java.awt.Window;
+import java.awt.event.ComponentEvent;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseEvent;
+import java.awt.event.PaintEvent;
+import java.util.HashMap;
+
+import gnu.x11.Display;
+import gnu.x11.event.ButtonPress;
+import gnu.x11.event.ButtonRelease;
+import gnu.x11.event.ConfigureNotify;
+import gnu.x11.event.Event;
+import gnu.x11.event.Expose;
+import gnu.x11.event.Input;
+import gnu.x11.event.KeyPress;
+import gnu.x11.event.KeyRelease;
+import gnu.x11.event.MotionNotify;
+
+/**
+ * Fetches events from X, translates them to AWT events and pumps them up
+ * into the AWT event queue.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class XEventPump
+ implements Runnable
+{
+
+ /**
+ * The X Display from which we fetch and pump up events.
+ */
+ private Display display;
+
+ /**
+ * Maps X Windows to AWT Windows to be able to correctly determine the
+ * event targets.
+ */
+ private HashMap windows;
+
+ /**
+ * Indicates if we are currently inside a drag operation. This is
+ * set to the button ID when a button is pressed and to -1 (indicating
+ * that no drag is active) when the mouse is released.
+ */
+ private int drag;
+
+ /**
+ * Creates a new XEventPump for the specified X Display.
+ *
+ * @param d the X Display
+ */
+ XEventPump(Display d)
+ {
+ display = d;
+ windows = new HashMap();
+ drag = -1;
+ Thread t = new Thread(this);
+ t.start();
+ }
+
+ /**
+ * The main event pump loop. This basically fetches events from the
+ * X Display and pumps them into the system event queue.
+ */
+ public void run()
+ {
+ while (display.connected)
+ {
+ try
+ {
+ Event xEvent = display.next_event();
+ handleEvent(xEvent);
+ }
+ catch (ThreadDeath death)
+ {
+ // If someone wants to kill us, let them.
+ return;
+ }
+ catch (Throwable x)
+ {
+ System.err.println("Exception during event dispatch:");
+ x.printStackTrace(System.err);
+ }
+ }
+ }
+
+ /**
+ * Adds an X Window to AWT Window mapping. This is required so that the
+ * event pump can correctly determine the event targets.
+ *
+ * @param xWindow the X Window
+ * @param awtWindow the AWT Window
+ */
+ void registerWindow(gnu.x11.Window xWindow, Window awtWindow)
+ {
+ if (XToolkit.DEBUG)
+ System.err.println("registering window id: " + xWindow.id);
+ windows.put(new Integer(xWindow.id), awtWindow);
+ }
+
+ void unregisterWindow(gnu.x11.Window xWindow)
+ {
+ windows.remove(new Integer(xWindow.id));
+ }
+
+ private void handleEvent(Event xEvent)
+ {
+ Integer key = new Integer(xEvent.window_id());;
+ Window awtWindow = (Window) windows.get(key);
+
+ if (XToolkit.DEBUG)
+ System.err.println("fetched event: " + xEvent);
+ switch (xEvent.code())
+ {
+ case ButtonPress.CODE:
+ ButtonPress bp = (ButtonPress) xEvent;
+ // Create and post the mouse event.
+ int button = bp.detail();
+ drag = button;
+ MouseEvent mp = new MouseEvent(awtWindow, MouseEvent.MOUSE_PRESSED,
+ System.currentTimeMillis(), 0,
+ bp.event_x(), bp.event_y(),
+ 1, false, button);
+ Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(mp);
+ break;
+ case ButtonRelease.CODE:
+ ButtonRelease br = (ButtonRelease) xEvent;
+ drag = -1;
+ MouseEvent mr = new MouseEvent(awtWindow, MouseEvent.MOUSE_RELEASED,
+ System.currentTimeMillis(), 0,
+ br.event_x(), br.event_y(),
+ 1, false, br.detail());
+ Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(mr);
+ break;
+ case MotionNotify.CODE:
+ MotionNotify mn = (MotionNotify) xEvent;
+ MouseEvent mm;
+ if (drag == -1)
+ {
+ mm = new MouseEvent(awtWindow, MouseEvent.MOUSE_MOVED,
+ System.currentTimeMillis(), 0,
+ mn.event_x(), mn.event_y(),
+ 1, false);
+ }
+ else
+ {
+ mm = new MouseEvent(awtWindow, MouseEvent.MOUSE_DRAGGED,
+ System.currentTimeMillis(), 0,
+ mn.event_x(), mn.event_y(),
+ 1, false);
+ }
+ Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(mm);
+ break;
+ case ConfigureNotify.CODE:
+ ConfigureNotify c = (ConfigureNotify) xEvent;
+ if (XToolkit.DEBUG)
+ System.err.println("resize request for window id: " + key);
+
+ // Detect and report size changes.
+ if (c.width() != awtWindow.getWidth()
+ || c.height() != awtWindow.getHeight())
+ {
+ if (XToolkit.DEBUG)
+ System.err.println("Setting size on AWT window: " + c.width()
+ + ", " + c.height() + ", " + awtWindow.getWidth()
+ + ", " + awtWindow.getHeight());
+ ((XWindowPeer) awtWindow.getPeer()).callback = true;
+ awtWindow.setSize(c.width(), c.height());
+ ((XWindowPeer) awtWindow.getPeer()).callback = false;
+ }
+ break;
+ case Expose.CODE:
+ Expose exp = (Expose) xEvent;
+ if (XToolkit.DEBUG)
+ System.err.println("expose request for window id: " + key);
+ Rectangle r = new Rectangle(exp.x(), exp.y(), exp.width(),
+ exp.height());
+ //System.err.println("expose paint: " + r);
+ // We need to clear the background of the exposed rectangle.
+ Graphics g = awtWindow.getGraphics();
+ g.clearRect(r.x, r.y, r.width, r.height);
+ g.dispose();
+ PaintEvent pev = new PaintEvent(awtWindow, PaintEvent.PAINT, r);
+ Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(pev);
+ break;
+ case KeyPress.CODE:
+ case KeyRelease.CODE:
+ handleKeyEvent(xEvent, awtWindow);
+ break;
+ default:
+ if (XToolkit.DEBUG)
+ System.err.println("Unhandled X event: " + xEvent);
+ }
+ }
+
+ /**
+ * Handles key events from X.
+ *
+ * @param xEvent the X event
+ * @param awtWindow the AWT window to which the event gets posted
+ */
+ private void handleKeyEvent(Event xEvent, Window awtWindow)
+ {
+ Input keyEvent = (Input) xEvent;
+ int xKeyCode = keyEvent.detail();
+ int xMods = keyEvent.state();
+ int keyCode = KeyboardMapping.mapToKeyCode(xEvent.display.input, xKeyCode,
+ xMods);
+ char keyChar = KeyboardMapping.mapToKeyChar(xEvent.display.input, xKeyCode,
+ xMods);
+ if (XToolkit.DEBUG)
+ System.err.println("XEventPump.handleKeyEvent: " + xKeyCode + ", "
+ + xMods + ": " + ((int) keyChar) + ", " + keyCode);
+ int awtMods = KeyboardMapping.mapModifiers(xMods);
+ long when = System.currentTimeMillis();
+ KeyEvent ke;
+ if (keyEvent.code() == KeyPress.CODE)
+ {
+ ke = new KeyEvent(awtWindow, KeyEvent.KEY_PRESSED, when,
+ awtMods, keyCode,
+ KeyEvent.CHAR_UNDEFINED);
+ Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(ke);
+ if (keyChar != KeyEvent.CHAR_UNDEFINED)
+ {
+ ke = new KeyEvent(awtWindow, KeyEvent.KEY_TYPED, when,
+ awtMods, KeyEvent.VK_UNDEFINED,
+ keyChar);
+ Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(ke);
+ }
+
+ }
+ else
+ {
+ ke = new KeyEvent(awtWindow, KeyEvent.KEY_RELEASED, when,
+ awtMods, keyCode,
+ KeyEvent.CHAR_UNDEFINED);
+ Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(ke);
+ }
+
+ }
+
+
+}
+
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XFontPeer.java b/libjava/classpath/gnu/java/awt/peer/x/XFontPeer.java
new file mode 100644
index 0000000..fd293d8
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XFontPeer.java
@@ -0,0 +1,766 @@
+/* XFontPeer.java -- The font peer for X
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import java.awt.AWTError;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.font.FontRenderContext;
+import java.awt.font.GlyphVector;
+import java.awt.font.LineMetrics;
+import java.awt.font.TextAttribute;
+import java.awt.geom.Rectangle2D;
+import java.io.IOException;
+import java.io.InputStream;
+import java.text.CharacterIterator;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Properties;
+
+import gnu.java.awt.peer.ClasspathFontPeer;
+import gnu.x11.Display;
+import gnu.x11.Fontable;
+
+/**
+ * The bridge from AWT to X fonts.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class XFontPeer
+ extends ClasspathFontPeer
+{
+
+ /**
+ * The font mapping as specified in the file fonts.properties.
+ */
+ private static Properties fontProperties;
+ static
+ {
+ fontProperties = new Properties();
+ InputStream in = XFontPeer.class.getResourceAsStream("fonts.properties");
+ try
+ {
+ fontProperties.load(in);
+ }
+ catch (IOException e)
+ {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * The FontMetrics implementation for XFontPeer.
+ */
+ private class XFontMetrics
+ extends FontMetrics
+ {
+ /**
+ * The ascent of the font.
+ */
+ int ascent;
+
+ /**
+ * The descent of the font.
+ */
+ int descent;
+
+ /**
+ * The maximum of the character advances.
+ */
+ private int maxAdvance;
+
+ /**
+ * The internal leading.
+ */
+ int leading;
+
+ /**
+ * Cached string metrics. This caches string metrics locally so that the
+ * server doesn't have to be asked each time.
+ */
+ private HashMap metricsCache;
+
+ /**
+ * The widths of the characters indexed by the characters themselves.
+ */
+ private int[] charWidths;
+
+ /**
+ * Creates a new XFontMetrics for the specified font.
+ *
+ * @param font the font
+ */
+ protected XFontMetrics(Font font)
+ {
+ super(font);
+ metricsCache = new HashMap();
+ Fontable.FontReply info = getXFont().info();
+ ascent = info.font_ascent();
+ descent = info.font_descent();
+ maxAdvance = info.max_bounds().character_width();
+ leading = 0; // TODO: Not provided by X. Possible not needed.
+
+ if (info.min_byte1() == 0 && info.max_byte1() == 0)
+ readCharWidthsLinear(info);
+ else
+ readCharWidthsNonLinear(info);
+ }
+
+ /**
+ * Reads the character widths when specified in a linear fashion. That is
+ * when the min-byte1 and max-byte2 fields are both zero in the X protocol.
+ *
+ * @param info the font info reply
+ */
+ private void readCharWidthsLinear(Fontable.FontReply info)
+ {
+ int startIndex = info.min_char_or_byte2();
+ int endIndex = info.max_char_or_byte2();
+ charWidths = new int[endIndex + 1];
+ // All the characters before startIndex are zero width.
+ for (int i = 0; i < startIndex; i++)
+ {
+ charWidths[i] = 0;
+ }
+ // All the other character info is fetched from the font info.
+ int index = startIndex;
+ Iterator charInfos = info.char_infos().iterator();
+ while (charInfos.hasNext())
+ {
+ Fontable.FontReply.CharInfo charInfo =
+ (Fontable.FontReply.CharInfo) charInfos.next();
+ charWidths[index] = charInfo.character_width();
+ index++;
+ }
+ }
+
+ private void readCharWidthsNonLinear(Fontable.FontReply info)
+ {
+ // TODO: Implement.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ /**
+ * Returns the ascent of the font.
+ *
+ * @return the ascent of the font
+ */
+ public int getAscent()
+ {
+ return ascent;
+ }
+
+ /**
+ * Returns the descent of the font.
+ *
+ * @return the descent of the font
+ */
+ public int getDescent()
+ {
+ return descent;
+ }
+
+ /**
+ * Returns the overall height of the font. This is the distance from
+ * baseline to baseline (usually ascent + descent + leading).
+ *
+ * @return the overall height of the font
+ */
+ public int getHeight()
+ {
+ return ascent + descent;
+ }
+
+ /**
+ * Returns the leading of the font.
+ *
+ * @return the leading of the font
+ */
+ public int getLeading()
+ {
+ return leading;
+ }
+
+ /**
+ * Returns the maximum advance for this font.
+ *
+ * @return the maximum advance for this font
+ */
+ public int getMaxAdvance()
+ {
+ return maxAdvance;
+ }
+
+ /**
+ * Determines the width of the specified character c
.
+ *
+ * @param c the character
+ *
+ * @return the width of the character
+ */
+ public int charWidth(char c)
+ {
+ int width;
+ if (c > charWidths.length)
+ width = charWidths['?'];
+ else
+ width = charWidths[c];
+ return width;
+ }
+
+ /**
+ * Determines the overall width of the specified string.
+ *
+ * @param c the char buffer holding the string
+ * @param offset the starting offset of the string in the buffer
+ * @param length the number of characters in the string buffer
+ *
+ * @return the overall width of the specified string
+ */
+ public int charsWidth(char[] c, int offset, int length)
+ {
+ int width = 0;
+ if (c.length > 0 && length > 0)
+ {
+ String s = new String(c, offset, length);
+ width = stringWidth(s);
+ }
+ return width;
+ }
+
+ /**
+ * Determines the overall width of the specified string.
+ *
+ * @param s the string
+ *
+ * @return the overall width of the specified string
+ */
+ public int stringWidth(String s)
+ {
+ int width = 0;
+ if (s.length() > 0)
+ {
+ if (metricsCache.containsKey(s))
+ {
+ width = ((Integer) metricsCache.get(s)).intValue();
+ }
+ else
+ {
+ Fontable.TextExtentReply extents = getXFont().text_extent(s);
+ /*
+ System.err.println("string: '" + s + "' : ");
+ System.err.println("ascent: " + extents.getAscent());
+ System.err.println("descent: " + extents.getDescent());
+ System.err.println("overall ascent: " + extents.getOverallAscent());
+ System.err.println("overall descent: " + extents.getOverallDescent());
+ System.err.println("overall width: " + extents.getOverallWidth());
+ System.err.println("overall left: " + extents.getOverallLeft());
+ System.err.println("overall right: " + extents.getOverallRight());
+ */
+ width = extents.overall_width(); // + extents.overall_left();
+ //System.err.println("String: " + s + ", width: " + width);
+ metricsCache.put(s, new Integer(width));
+ }
+ }
+ //System.err.print("stringWidth: '" + s + "': ");
+ //System.err.println(width);
+ return width;
+ }
+ }
+
+ /**
+ * The LineMetrics implementation for the XFontPeer.
+ */
+ private class XLineMetrics
+ extends LineMetrics
+ {
+
+ /**
+ * Returns the ascent of the font.
+ *
+ * @return the ascent of the font
+ */
+ public float getAscent()
+ {
+ return fontMetrics.ascent;
+ }
+
+ public int getBaselineIndex()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException();
+ }
+
+ public float[] getBaselineOffsets()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Returns the descent of the font.
+ *
+ * @return the descent of the font
+ */
+ public float getDescent()
+ {
+ return fontMetrics.descent;
+ }
+
+ /**
+ * Returns the overall height of the font. This is the distance from
+ * baseline to baseline (usually ascent + descent + leading).
+ *
+ * @return the overall height of the font
+ */
+ public float getHeight()
+ {
+ return fontMetrics.ascent + fontMetrics.descent;
+ }
+
+ /**
+ * Returns the leading of the font.
+ *
+ * @return the leading of the font
+ */
+ public float getLeading()
+ {
+ return fontMetrics.leading;
+ }
+
+ public int getNumChars()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException();
+ }
+
+ public float getStrikethroughOffset()
+ {
+ return 0.F; // TODO: Provided by X??
+ }
+
+ public float getStrikethroughThickness()
+ {
+ return 1.F; // TODO: Provided by X??
+ }
+
+ public float getUnderlineOffset()
+ {
+ return 0.F; // TODO: Provided by X??
+ }
+
+ public float getUnderlineThickness()
+ {
+ return 1.F; // TODO: Provided by X??
+ }
+
+ }
+
+ /**
+ * The X font.
+ */
+ private gnu.x11.Font xfont;
+
+ private String name;
+
+ private int style;
+
+ private int size;
+
+ /**
+ * The font metrics for this font.
+ */
+ XFontMetrics fontMetrics;
+
+ /**
+ * Creates a new XFontPeer for the specified font name, style and size.
+ *
+ * @param name the font name
+ * @param style the font style (bold / italic / normal)
+ * @param size the size of the font
+ */
+ public XFontPeer(String name, int style, int size)
+ {
+ super(name, style, size);
+ this.name = name;
+ this.style = style;
+ this.size = size;
+ }
+
+ /**
+ * Creates a new XFontPeer for the specified font name and style
+ * attributes.
+ *
+ * @param name the font name
+ * @param atts the font attributes
+ */
+ public XFontPeer(String name, Map atts)
+ {
+ super(name, atts);
+ String family = name;
+ if (family == null || family.equals(""))
+ family = (String) atts.get(TextAttribute.FAMILY);
+ if (family == null)
+ family = "SansSerif";
+
+ int size = 12;
+ Float sizeFl = (Float) atts.get(TextAttribute.SIZE);
+ if (sizeFl != null)
+ size = sizeFl.intValue();
+
+ int style = 0;
+ // Detect italic attribute.
+ Float posture = (Float) atts.get(TextAttribute.POSTURE);
+ if (posture != null && !posture.equals(TextAttribute.POSTURE_REGULAR))
+ style |= Font.ITALIC;
+
+ // Detect bold attribute.
+ Float weight = (Float) atts.get(TextAttribute.WEIGHT);
+ if (weight != null && weight.compareTo(TextAttribute.WEIGHT_REGULAR) > 0)
+ style |= Font.BOLD;
+
+ this.name = name;
+ this.style = style;
+ this.size = size;
+ }
+
+ /**
+ * Initializes the font peer with the specified attributes. This method is
+ * called from both constructors.
+ *
+ * @param name the font name
+ * @param style the font style
+ * @param size the font size
+ */
+ private void init(String name, int style, int size)
+ {
+ GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
+ GraphicsDevice dev = env.getDefaultScreenDevice();
+ if (dev instanceof XGraphicsDevice)
+ {
+ Display display = ((XGraphicsDevice) dev).getDisplay();
+ String fontDescr = encodeFont(name, style, size);
+ if (XToolkit.DEBUG)
+ System.err.println("XLFD font description: " + fontDescr);
+ xfont = new gnu.x11.Font(display, fontDescr);
+ }
+ else
+ {
+ throw new AWTError("Local GraphicsEnvironment is not XWindowGraphicsEnvironment");
+ }
+ }
+
+ public boolean canDisplay(Font font, char c)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public int canDisplayUpTo(Font font, CharacterIterator i, int start, int limit)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public String getSubFamilyName(Font font, Locale locale)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public String getPostScriptName(Font font)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public int getNumGlyphs(Font font)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public int getMissingGlyphCode(Font font)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public byte getBaselineFor(Font font, char c)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public String getGlyphName(Font font, int glyphIndex)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public GlyphVector createGlyphVector(Font font, FontRenderContext frc,
+ CharacterIterator ci)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public GlyphVector createGlyphVector(Font font, FontRenderContext ctx,
+ int[] glyphCodes)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public GlyphVector layoutGlyphVector(Font font, FontRenderContext frc,
+ char[] chars, int start, int limit,
+ int flags)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Returns the font metrics for the specified font.
+ *
+ * @param font the font for which to fetch the font metrics
+ *
+ * @return the font metrics for the specified font
+ */
+ public FontMetrics getFontMetrics(Font font)
+ {
+ if (font.getPeer() != this)
+ throw new AWTError("The specified font has a different peer than this");
+
+ if (fontMetrics == null)
+ fontMetrics = new XFontMetrics(font);
+ return fontMetrics;
+ }
+
+ /**
+ * Frees the font in the X server.
+ */
+ protected void finalize()
+ {
+ if (xfont != null)
+ xfont.close();
+ }
+
+ public boolean hasUniformLineMetrics(Font font)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Returns the line metrics for this font and the specified string and
+ * font render context.
+ */
+ public LineMetrics getLineMetrics(Font font, CharacterIterator ci, int begin,
+ int limit, FontRenderContext rc)
+ {
+ return new XLineMetrics();
+ }
+
+ public Rectangle2D getMaxCharBounds(Font font, FontRenderContext rc)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public Rectangle2D getStringBounds(Font font, CharacterIterator ci,
+ int begin, int limit, FontRenderContext frc)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Encodes a font name + style + size specification into a X logical font
+ * description (XLFD) as described here:
+ *
+ * http://www.meretrx.com/e93/docs/xlfd.html
+ *
+ * This is implemented to look up the font description in the
+ * fonts.properties of this package.
+ *
+ * @param name the font name
+ * @param atts the text attributes
+ *
+ * @return the encoded font description
+ */
+ static String encodeFont(String name, Map atts)
+ {
+ String family = name;
+ if (family == null || family.equals(""))
+ family = (String) atts.get(TextAttribute.FAMILY);
+ if (family == null)
+ family = "SansSerif";
+
+ int size = 12;
+ Float sizeFl = (Float) atts.get(TextAttribute.SIZE);
+ if (sizeFl != null)
+ size = sizeFl.intValue();
+
+ int style = 0;
+ // Detect italic attribute.
+ Float posture = (Float) atts.get(TextAttribute.POSTURE);
+ if (posture != null && !posture.equals(TextAttribute.POSTURE_REGULAR))
+ style |= Font.ITALIC;
+
+ // Detect bold attribute.
+ Float weight = (Float) atts.get(TextAttribute.WEIGHT);
+ if (weight != null && weight.compareTo(TextAttribute.WEIGHT_REGULAR) > 0)
+ style |= Font.BOLD;
+
+ return encodeFont(name, style, size);
+ }
+
+ /**
+ * Encodes a font name + style + size specification into a X logical font
+ * description (XLFD) as described here:
+ *
+ * http://www.meretrx.com/e93/docs/xlfd.html
+ *
+ * This is implemented to look up the font description in the
+ * fonts.properties of this package.
+ *
+ * @param name the font name
+ * @param style the font style
+ * @param size the font size
+ *
+ * @return the encoded font description
+ */
+ static String encodeFont(String name, int style, int size)
+ {
+ StringBuilder key = new StringBuilder();
+ key.append(validName(name));
+ key.append('.');
+ switch (style)
+ {
+ case Font.BOLD:
+ key.append("bold");
+ break;
+ case Font.ITALIC:
+ key.append("italic");
+ break;
+ case (Font.BOLD | Font.ITALIC):
+ key.append("bolditalic");
+ break;
+ case Font.PLAIN:
+ default:
+ key.append("plain");
+
+ }
+
+ String protoType = fontProperties.getProperty(key.toString());
+ int s = validSize(size);
+ return protoType.replaceFirst("%d", String.valueOf(s * 10));
+ }
+
+ /**
+ * Checks the specified font name for a valid font name. If the font name
+ * is not known, then this returns 'sansserif' as fallback.
+ *
+ * @param name the font name to check
+ *
+ * @return a valid font name
+ */
+ static String validName(String name)
+ {
+ String retVal;
+ if (name.equalsIgnoreCase("sansserif")
+ || name.equalsIgnoreCase("serif")
+ || name.equalsIgnoreCase("monospaced")
+ || name.equalsIgnoreCase("dialog")
+ || name.equalsIgnoreCase("dialoginput"))
+ {
+ retVal = name.toLowerCase();
+ }
+ else
+ {
+ retVal = "sansserif";
+ }
+ return retVal;
+ }
+
+ /**
+ * Translates an arbitrary point size to a size that is typically available
+ * on an X server. These are the sizes 8, 10, 12, 14, 18 and 24.
+ *
+ * @param size the queried size
+ * @return the real available size
+ */
+ private static final int validSize(int size)
+ {
+ int val;
+ if (size <= 9)
+ val = 8;
+ else if (size <= 11)
+ val = 10;
+ else if (size <= 13)
+ val = 12;
+ else if (size <= 17)
+ val = 14;
+ else if (size <= 23)
+ val = 18;
+ else
+ val = 24;
+ return val;
+ }
+
+ /**
+ * Returns the X Font reference. This lazily loads the font when first
+ * requested.
+ *
+ * @return the X Font reference
+ */
+ gnu.x11.Font getXFont()
+ {
+ if (xfont == null)
+ {
+ init(name, style, size);
+ }
+ return xfont;
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XFontPeer2.java b/libjava/classpath/gnu/java/awt/peer/x/XFontPeer2.java
new file mode 100644
index 0000000..25371de
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XFontPeer2.java
@@ -0,0 +1,335 @@
+/* XFontPeer2.java -- A Java based TTF font peer for X
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.font.FontRenderContext;
+import java.awt.font.GlyphVector;
+import java.awt.font.LineMetrics;
+import java.awt.geom.AffineTransform;
+import java.awt.geom.Point2D;
+import java.awt.geom.Rectangle2D;
+import java.io.File;
+import java.io.FileInputStream;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.text.CharacterIterator;
+import java.text.StringCharacterIterator;
+import java.util.Locale;
+import java.util.Map;
+
+import gnu.java.awt.font.FontDelegate;
+import gnu.java.awt.font.FontFactory;
+import gnu.java.awt.peer.ClasspathFontPeer;
+
+public class XFontPeer2
+ extends ClasspathFontPeer
+{
+
+ private class XLineMetrics
+ extends LineMetrics
+ {
+
+ private Font font;
+// private CharacterIterator characterIterator;
+// private int begin;
+// private int limit;
+ private FontRenderContext fontRenderContext;
+ XLineMetrics(Font f, CharacterIterator ci, int b, int l,
+ FontRenderContext rc)
+ {
+ font = f;
+// characterIterator = ci;
+// begin = b;
+// limit = l;
+ fontRenderContext = rc;
+ }
+
+ public float getAscent()
+ {
+ return fontDelegate.getAscent(font.getSize(), fontRenderContext.getTransform(),
+ fontRenderContext.isAntiAliased(),
+ fontRenderContext.usesFractionalMetrics(), true);
+ }
+
+ public int getBaselineIndex()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public float[] getBaselineOffsets()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public float getDescent()
+ {
+ return (int) fontDelegate.getDescent(font.getSize(),
+ new AffineTransform(), false, false,
+ false);
+ }
+
+ public float getHeight()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public float getLeading()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public int getNumChars()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public float getStrikethroughOffset()
+ {
+ return 0.F;
+ }
+
+ public float getStrikethroughThickness()
+ {
+ return 0.F;
+ }
+
+ public float getUnderlineOffset()
+ {
+ return 0.F;
+ }
+
+ public float getUnderlineThickness()
+ {
+ return 0.F;
+ }
+
+ }
+
+ private class XFontMetrics
+ extends FontMetrics
+ {
+ XFontMetrics(Font f)
+ {
+ super(f);
+ }
+
+ public int getAscent()
+ {
+ return (int) fontDelegate.getAscent(getFont().getSize(),
+ new AffineTransform(), false, false,
+ false);
+ }
+
+ public int getDescent()
+ {
+ return (int) fontDelegate.getDescent(getFont().getSize(),
+ new AffineTransform(), false, false,
+ false);
+ }
+
+ public int getHeight()
+ {
+ GlyphVector gv = fontDelegate.createGlyphVector(getFont(),
+ new FontRenderContext(new AffineTransform(), false, false),
+ new StringCharacterIterator("m"));
+ Rectangle2D b = gv.getVisualBounds();
+ return (int) b.getHeight();
+ }
+
+ public int charWidth(char c)
+ {
+ Point2D advance = new Point2D.Double();
+ fontDelegate.getAdvance(c, getFont().getSize(), new AffineTransform(),
+ false, false, true, advance);
+ return (int) advance.getX();
+ }
+
+ public int charsWidth(char[] chars, int offs, int len)
+ {
+ return stringWidth(new String(chars, offs, len));
+ }
+
+ public int stringWidth(String s)
+ {
+ GlyphVector gv = fontDelegate.createGlyphVector(getFont(),
+ new FontRenderContext(new AffineTransform(), false, false),
+ new StringCharacterIterator(s));
+ Rectangle2D b = gv.getVisualBounds();
+ return (int) b.getWidth();
+ }
+ }
+
+ private FontDelegate fontDelegate;
+
+ XFontPeer2(String name, int style, int size)
+ {
+ super(name, style, size);
+ try
+ {
+ File fontfile = new File("/usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf");
+ FileInputStream in = new FileInputStream(fontfile);
+ FileChannel ch = in.getChannel();
+ ByteBuffer buffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
+ fontfile.length());
+ fontDelegate = FontFactory.createFonts(buffer)[0];
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+
+ XFontPeer2(String name, Map atts)
+ {
+ super(name, atts);
+ try
+ {
+ File fontfile = new File("/usr/share/fonts/truetype/freefont/FreeSans.ttf");
+ FileInputStream in = new FileInputStream(fontfile);
+ FileChannel ch = in.getChannel();
+ ByteBuffer buffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
+ fontfile.length());
+ fontDelegate = FontFactory.createFonts(buffer)[0];
+ }
+ catch (Exception ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+
+ public boolean canDisplay(Font font, char c)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public int canDisplayUpTo(Font font, CharacterIterator i, int start, int limit)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public String getSubFamilyName(Font font, Locale locale)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public String getPostScriptName(Font font)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public int getNumGlyphs(Font font)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public int getMissingGlyphCode(Font font)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public byte getBaselineFor(Font font, char c)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public String getGlyphName(Font font, int glyphIndex)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public GlyphVector createGlyphVector(Font font, FontRenderContext frc, CharacterIterator ci)
+ {
+ return fontDelegate.createGlyphVector(font, frc, ci);
+ }
+
+ public GlyphVector createGlyphVector(Font font, FontRenderContext ctx, int[] glyphCodes)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public GlyphVector layoutGlyphVector(Font font, FontRenderContext frc, char[] chars, int start, int limit, int flags)
+ {
+ StringCharacterIterator i = new StringCharacterIterator(new String(chars), start, limit, 0);
+ return fontDelegate.createGlyphVector(font, frc, i);
+ }
+
+ public FontMetrics getFontMetrics(Font font)
+ {
+ return new XFontMetrics(font);
+ }
+
+ public boolean hasUniformLineMetrics(Font font)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public LineMetrics getLineMetrics(Font font, CharacterIterator ci, int begin, int limit, FontRenderContext rc)
+ {
+ return new XLineMetrics(font, ci, begin, limit, rc);
+ }
+
+ public Rectangle2D getMaxCharBounds(Font font, FontRenderContext rc)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public Rectangle2D getStringBounds(Font font, CharacterIterator ci, int begin, int limit, FontRenderContext frc)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XFramePeer.java b/libjava/classpath/gnu/java/awt/peer/x/XFramePeer.java
new file mode 100644
index 0000000..439a2a7
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XFramePeer.java
@@ -0,0 +1,140 @@
+/* XFramePeer.java -- The X FramePeer implementation
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Component;
+import java.awt.EventQueue;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Image;
+import java.awt.Insets;
+import java.awt.MenuBar;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.event.PaintEvent;
+import java.awt.event.WindowEvent;
+import java.awt.peer.FramePeer;
+
+import gnu.java.awt.peer.swing.SwingFramePeer;
+import gnu.x11.Window;
+import gnu.x11.event.Event;
+
+public class XFramePeer
+ extends XWindowPeer
+ implements FramePeer
+{
+
+ XFramePeer(Frame f)
+ {
+ super(f);
+ }
+
+ public void setIconImage(Image image)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public void setMenuBar(MenuBar mb)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public void setResizable(boolean resizable)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public void setTitle(String title)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public int getState()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public void setState(int state)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public void setMaximizedBounds(Rectangle r)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Check if this frame peer supports being restacked.
+ *
+ * @return true if this frame peer can be restacked,
+ * false otherwise
+ * @since 1.5
+ */
+ public boolean isRestackSupported()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Sets the bounds of this frame peer.
+ *
+ * @param x the new x co-ordinate
+ * @param y the new y co-ordinate
+ * @param width the new width
+ * @param height the new height
+ * @since 1.5
+ */
+ public void setBoundsPrivate(int x, int y, int width, int height)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XGraphics.java b/libjava/classpath/gnu/java/awt/peer/x/XGraphics.java
new file mode 100644
index 0000000..134d7d3
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XGraphics.java
@@ -0,0 +1,792 @@
+/* XGraphics.java -- The Graphics implementation for X
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import gnu.x11.Colormap;
+import gnu.x11.Data;
+import gnu.x11.Display;
+import gnu.x11.Drawable;
+import gnu.x11.GC;
+import gnu.x11.Pixmap;
+import gnu.x11.Point;
+import gnu.x11.image.ZPixmap;
+
+import java.awt.AWTError;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.awt.Image;
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.Toolkit;
+import java.awt.Transparency;
+import java.awt.image.BufferedImage;
+import java.awt.image.ImageObserver;
+import java.awt.image.ImageProducer;
+import java.text.AttributedCharacterIterator;
+import java.util.HashMap;
+
+public class XGraphics
+ extends Graphics
+ implements Cloneable
+{
+
+ /**
+ * The X Drawable to draw on.
+ */
+ private Drawable xdrawable;
+
+ /**
+ * The X graphics context (GC).
+ */
+ private GC xgc;
+
+ /**
+ * The current translation.
+ */
+ private int translateX;
+ private int translateY;
+
+ /**
+ * The current clip. Possibly null.
+ */
+ private Rectangle clip;
+
+ /**
+ * The current font, possibly null.
+ */
+ private Font font;
+
+ /**
+ * The current foreground color, possibly null.
+ */
+ private Color foreground;
+
+ /**
+ * Indicates if this object has been disposed.
+ */
+ private boolean disposed = false;
+
+ // TODO: Workaround for limitation in current Escher.
+ private Pixmap.Format pixmapFormat;
+ private int imageByteOrder;
+ private int pixelByteCount;
+
+ /**
+ * Creates a new XGraphics on the specified X Drawable.
+ *
+ * @param d the X Drawable for which we create the Graphics
+ */
+ XGraphics(Drawable d)
+ {
+ xdrawable = d;
+ xgc = new GC(d);
+ translateX = 0;
+ translateY = 0;
+ clip = new Rectangle(0, 0, d.width, d.height);
+
+ Display display = xdrawable.display;
+ pixmapFormat = display.default_pixmap_format;
+ imageByteOrder = display.image_byte_order;
+ pixelByteCount = pixmapFormat.bits_per_pixel () / 8;
+ }
+
+ /**
+ * Creates an exact copy of this graphics context.
+ *
+ * @return an exact copy of this graphics context
+ */
+ public Graphics create()
+ {
+ XGraphics copy = (XGraphics) clone();
+ return copy;
+ }
+
+ /**
+ * Translates the origin by (x, y).
+ */
+ public void translate(int x, int y)
+ {
+ translateX += x;
+ translateY += y;
+ if (clip != null)
+ {
+ clip.x -= x;
+ clip.y -= y;
+ }
+ }
+
+ /**
+ * Returns the current foreground color, possibly null
.
+ *
+ * @return the current foreground color, possibly null
+ */
+ public Color getColor()
+ {
+ return foreground;
+ }
+
+ /**
+ * Sets the current foreground color. A null
value doesn't
+ * change the current setting.
+ *
+ * @param c the foreground color to set
+ */
+ public void setColor(Color c)
+ {
+ if (c != null)
+ {
+ XToolkit tk = (XToolkit) Toolkit.getDefaultToolkit();
+ HashMap colorMap = tk.colorMap;
+ gnu.x11.Color col = (gnu.x11.Color) colorMap.get(c);
+ if (col == null)
+ {
+ Colormap map = xdrawable.display.default_colormap;
+ col = map.alloc_color (c.getRed() * 256,
+ c.getGreen() * 256,
+ c.getBlue() * 256);
+ colorMap.put(c, col);
+ }
+ xgc.set_foreground(col);
+ foreground = c;
+ }
+ }
+
+ public void setPaintMode()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public void setXORMode(Color color)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ /**
+ * Returns the current font, possibly null
.
+ *
+ * @return the current font, possibly null
+ */
+ public Font getFont()
+ {
+ return font;
+ }
+
+ /**
+ * Sets the font on the graphics context. A null
value doesn't
+ * change the current setting.
+ *
+ * @param f the font to set
+ */
+ public void setFont(Font f)
+ {
+ if (f != null)
+ {
+ XFontPeer xFontPeer = (XFontPeer) f.getPeer();
+ xgc.set_font(xFontPeer.getXFont());
+ font = f;
+ }
+ }
+
+ /**
+ * Returns the font metrics for the specified font.
+ *
+ * @param font the font for which we want the font metrics
+ *
+ * @return the font metrics for the specified font
+ */
+ public FontMetrics getFontMetrics(Font font)
+ {
+ if (font == null)
+ {
+ if (this.font == null)
+ setFont(new Font("Dialog", Font.PLAIN, 12));
+ font = this.font;
+ }
+ XFontPeer xFontPeer = (XFontPeer) font.getPeer();
+ return xFontPeer.getFontMetrics(font);
+ }
+
+ /**
+ * Returns the bounds of the current clip.
+ *
+ * @return the bounds of the current clip
+ */
+ public Rectangle getClipBounds()
+ {
+ return clip != null ? clip.getBounds() : null;
+ }
+
+ /**
+ * Clips the current clip with the specified clip.
+ */
+ public void clipRect(int x, int y, int width, int height)
+ {
+ if (clip == null)
+ {
+ clip = new Rectangle(x, y, width, height);
+ }
+ else
+ {
+ computeIntersection(x, y, width, height, clip);
+ }
+ // Update the X clip setting.
+ setXClip(clip.x, clip.y, clip.width, clip.height);
+ }
+
+ /**
+ * Returns true
when the specified rectangle intersects with
+ * the current clip, false
otherwise. This is overridden to
+ * avoid unnecessary creation of Rectangles via getBounds().
+ *
+ * @param x the x coordinate of the rectangle
+ * @param y the y coordinate of the rectangle
+ * @param w the width of the rectangle
+ * @param h the height of the rectangle
+ *
+ * @return true
when the specified rectangle intersects with
+ * the current clip, false
otherwise
+ */
+ public boolean hitClip(int x, int y, int w, int h)
+ {
+ boolean hit;
+ if (clip == null)
+ {
+ hit = true;
+ }
+ else
+ {
+ // It's easier to determine if the rectangle lies outside the clip,
+ // so we determine that and reverse the result (if it's not completely
+ // outside, it most likely hits the clip rectangle).
+ int x2 = x + w;
+ int y2 = y + h;
+ int clipX2 = clip.x + clip.width;
+ int clipY2 = clip.y + clip.height;
+ boolean outside = (x < clip.x && x2 < clip.x) // Left.
+ || (x > clipX2 && x2 > clipX2) // Right.
+ || (y < clip.y && y2 < clip.y) // Top.
+ || (y > clipY2 && y2 > clipY2); // Bottom.
+ hit = ! outside;
+ }
+ return hit;
+ }
+
+ public void setClip(int x, int y, int width, int height)
+ {
+ if (clip != null)
+ clip.setBounds(x, y, width, height);
+ else
+ clip = new Rectangle(x, y, width, height);
+ setXClip(clip.x, clip.y, clip.width, clip.height);
+ }
+
+ /**
+ * Sets the clip on the X server GC. The coordinates are not yet translated,
+ * this will be performed by the X server.
+ *
+ * @param x the clip, X coordinate
+ * @param y the clip, Y coordinate
+ * @param w the clip, width
+ * @param h the clip, height
+ */
+ private void setXClip(int x, int y, int w, int h)
+ {
+ gnu.x11.Rectangle[] clipRects = new gnu.x11.Rectangle[] {
+ new gnu.x11.Rectangle(x, y, w, h) };
+ xgc.set_clip_rectangles(translateX, translateY, clipRects, GC.YX_BANDED);
+ }
+
+ public Shape getClip()
+ {
+ // Return a copy here, so nobody can trash our clip.
+ return clip == null ? null : clip.getBounds();
+ }
+
+ /**
+ * Sets the current clip.
+ *
+ * @param c the clip to set
+ */
+ public void setClip(Shape c)
+ {
+ if (c != null)
+ {
+ Rectangle b;
+ if (c instanceof Rectangle)
+ {
+ b = (Rectangle) c;
+ }
+ else
+ {
+ b = c.getBounds();
+ }
+ clip.setBounds(b);
+ setXClip(b.x, b.y, b.width, b.height);
+ }
+ else
+ {
+ clip.setBounds(0, 0, xdrawable.width, xdrawable.height);
+ setXClip(0, 0, xdrawable.width, xdrawable.height);
+ }
+ }
+
+ public void copyArea(int x, int y, int width, int height, int dx, int dy)
+ {
+ // Clip and translate src rectangle.
+ int srcX = Math.min(Math.max(x, clip.x), clip.x + clip.width)
+ + translateX;
+ int srcY = Math.min(Math.max(y, clip.y), clip.y + clip.height)
+ + translateY;
+ int srcWidth = Math.min(Math.max(x + width, clip.x),
+ clip.x + clip.width) - x;
+ int srcHeight = Math.min(Math.max(y + height, clip.y),
+ clip.y + clip.height) - y;
+ xdrawable.copy_area(xdrawable, xgc, srcX, srcY, srcWidth, srcHeight,
+ srcX + dx, srcY + dy);
+ }
+
+ /**
+ * Draws a line from point (x1, y1) to point (x2, y2).
+ */
+ public void drawLine(int x1, int y1, int x2, int y2)
+ {
+ //System.err.println("drawLine: " + (x1 + translateX) + ", " + ( y1 + translateY) + ", " + (x2 + translateX) + ", " + (y2 + translateY) + " on: " + xdrawable);
+ xdrawable.line(xgc, x1 + translateX, y1 + translateY,
+ x2 + translateX, y2 + translateY);
+ }
+
+ /**
+ * Fills the specified rectangle.
+ */
+ public void fillRect(int x, int y, int width, int height)
+ {
+ xdrawable.rectangle(xgc, x + translateX, y + translateY,
+ width, height, true);
+ }
+
+ public void clearRect(int x, int y, int width, int height)
+ {
+ xgc.set_foreground(Color.WHITE.getRGB());
+ xdrawable.rectangle(xgc, x, y, width, height, true);
+ if (foreground != null)
+ xgc.set_foreground(foreground.getRGB());
+ }
+
+ public void drawRoundRect(int x, int y, int width, int height, int arcWidth,
+ int arcHeight)
+ {
+ // Draw 4 lines.
+ int arcRadiusX = arcWidth / 2;
+ int arcRadiusY = arcHeight / 2;
+ drawLine(x + arcRadiusX, y, x + width - arcRadiusX, y);
+ drawLine(x, y + arcRadiusY, x, y + height - arcRadiusY);
+ drawLine(x + arcRadiusX, y + height, x + width - arcRadiusX, y + height);
+ drawLine(x + width, y + arcRadiusY, x + width, y + height - arcRadiusY);
+
+ // Draw the 4 arcs at the corners.
+ // Upper left.
+ drawArc(x, y, arcWidth, arcHeight, 90, 90);
+ // Lower left.
+ drawArc(x, y + height - arcHeight, arcWidth, arcHeight, 180, 90);
+ // Upper right.
+ drawArc(x + width - arcWidth, y, arcWidth, arcHeight, 0, 90);
+ // Lower right.
+ drawArc(x + width - arcWidth, y + height - arcHeight, arcWidth, arcHeight,
+ 270, 90);
+ }
+
+ public void fillRoundRect(int x, int y, int width, int height, int arcWidth,
+ int arcHeight)
+ {
+ // Fill the 3 rectangles that make up the inner area.
+ int arcRadiusX = arcWidth / 2;
+ int arcRadiusY = arcHeight / 2;
+ // Left.
+ fillRect(x, y + arcRadiusY, arcRadiusX, height - arcHeight);
+ // Middle.
+ fillRect(x + arcRadiusX, y, width - arcWidth, height);
+ // Right.
+ fillRect(x + width - arcRadiusX, y + arcRadiusY, arcRadiusX,
+ height - arcHeight);
+
+ // Fill the 4 arcs in the corners.
+ // Upper left.
+ fillArc(x, y, arcWidth, arcHeight, 90, 90);
+ // Lower left.
+ fillArc(x, y + height - arcHeight, arcWidth, arcHeight, 180, 90);
+ // Upper right.
+ fillArc(x + width - arcWidth, y, arcWidth, arcHeight, 0, 90);
+ // Lower right.
+ fillArc(x + width - arcWidth, y + height - arcHeight, arcWidth, arcHeight,
+ 270, 90);
+ }
+
+ public void drawOval(int x, int y, int width, int height)
+ {
+ xdrawable.arc(xgc, x, y, width, height, 0, 360 * 64, false);
+ }
+
+ public void fillOval(int x, int y, int width, int height)
+ {
+ xdrawable.arc(xgc, x, y, width, height, 0, 360 * 64, true);
+ }
+
+ public void drawArc(int x, int y, int width, int height, int arcStart,
+ int arcAngle)
+ {
+ xdrawable.arc(xgc, x, y, width, height, arcStart * 64, arcAngle * 64, false);
+ }
+
+ public void fillArc(int x, int y, int width, int height, int arcStart,
+ int arcAngle)
+ {
+ xdrawable.arc(xgc, x, y, width, height, arcStart * 64, arcAngle * 64, true);
+ }
+
+ public void drawPolyline(int[] xPoints, int[] yPoints, int npoints)
+ {
+ int numPoints = Math.min(xPoints.length, yPoints.length);
+ Point[] points = new Point[numPoints];
+ // FIXME: Improve Escher API to accept arrays to avoid creation
+ // of many Point objects.
+ for (int i = 0; i < numPoints; i++)
+ points[i] = new Point(xPoints[i], yPoints[i]);
+ xdrawable.poly_line(xgc, points, Drawable.ORIGIN);
+ }
+
+ public void drawPolygon(int[] xPoints, int[] yPoints, int npoints)
+ {
+ int numPoints = Math.min(xPoints.length, yPoints.length);
+ Point[] points = new Point[numPoints];
+ // FIXME: Improve Escher API to accept arrays to avoid creation
+ // of many Point objects.
+ for (int i = 0; i < numPoints; i++)
+ points[i] = new Point(xPoints[i], yPoints[i]);
+ xdrawable.poly_line(xgc, points, Drawable.ORIGIN);
+ }
+
+ public void fillPolygon(int[] xPoints, int[] yPoints, int npoints)
+ {
+ int numPoints = Math.min(xPoints.length, yPoints.length);
+ Point[] points = new Point[numPoints];
+ // FIXME: Improve Escher API to accept arrays to avoid creation
+ // of many Point objects.
+ for (int i = 0; i < numPoints; i++)
+ points[i] = new Point(xPoints[i], yPoints[i]);
+ xdrawable.fill_poly(xgc, points, Drawable.COMPLEX, Drawable.ORIGIN);
+ }
+
+ /**
+ * Draws the specified string at (x, y).
+ */
+ public void drawString(String string, int x, int y)
+ {
+ if (disposed)
+ throw new AWTError("XGraphics already disposed");
+
+ xdrawable.text(xgc, x + translateX, y + translateY, string);
+ }
+
+ public void drawString(AttributedCharacterIterator ci, int x, int y)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ /**
+ * Draws the specified image on the drawable at position (x,y).
+ */
+ public boolean drawImage(Image image, int x, int y, ImageObserver observer)
+ {
+ if (image instanceof XImage)
+ {
+ XImage xim = (XImage) image;
+ Pixmap pm = xim.pixmap;
+ xdrawable.copy_area(pm, xgc, 0, 0, pm.width, pm.height,
+ x + translateX, y + translateY);
+ }
+ else if (image instanceof BufferedImage
+ && ((BufferedImage) image).getTransparency() != Transparency.OPAQUE)
+ {
+ BufferedImage bi = (BufferedImage) image;
+ int width = bi.getWidth();
+ int height = bi.getHeight();
+ Data img = xdrawable.image(x + translateX, y + translateY,
+ width, height, 0xFFFFFFFF, 2);
+
+ // Compute line byte count.
+ int lineBitCount = width * pixmapFormat.bits_per_pixel ();
+ int rem = lineBitCount % pixmapFormat.scanline_pad ();
+ int linePadCount = lineBitCount / pixmapFormat.scanline_pad ()
+ + (rem == 0 ? 0 : 1);
+ int lineByteCount = linePadCount * pixmapFormat.scanline_pad () / 8;
+
+ // Composite source and destination pixel data.
+ int[] trgb = new int[3]; // The device rgb pixels.
+ for (int yy = 0; yy < height; yy++)
+ {
+ for (int xx = 0; xx < width; xx++)
+ {
+ getRGB(xx, yy, img, trgb, lineByteCount);
+ int srgb = bi.getRGB(xx, yy);
+ float alpha = ((srgb >> 24) & 0xff) / 256F;
+ float tAlpha = 1.F - alpha;
+ int red = (srgb >> 16) & 0xFF;
+ int green = (srgb >> 8) & 0xFF;
+ int blue = (srgb) & 0xFF;
+ trgb[0] = (int) (trgb[0] * tAlpha + red * alpha);
+ trgb[1] = (int) (trgb[1] * tAlpha + green * alpha);
+ trgb[2] = (int) (trgb[2] * tAlpha + blue * alpha);
+ setRGB(xx, yy, img, trgb, lineByteCount);
+ }
+ }
+
+ // Now we have the transparent image composited onto the target
+ // Image, now we only must copy it to the Drawable.
+ ZPixmap pm = new ZPixmap(xdrawable.display);
+ pm.width = width;
+ pm.height = height;
+ pm.init();
+ System.arraycopy(img.data, 32, pm.data, 0, img.data.length - 32);
+ xdrawable.put_image(xgc, pm, x + translateX, y + translateY);
+ }
+ else
+ {
+ // Pre-render the image into an XImage.
+ ImageProducer source = image.getSource();
+ ImageConverter conv = new ImageConverter();
+ source.startProduction(conv);
+ XImage xim = conv.getXImage();
+ Pixmap pm = xim.pixmap;
+ xdrawable.copy_area(pm, xgc, 0, 0, pm.width, pm.height,
+ x + translateX, y + translateY);
+ }
+ return true;
+ }
+
+ /**
+ * Helper method to work around limitation in the current Escher impl.
+ *
+ * @param x the x position
+ * @param y the y position
+ * @param img the image data
+ * @param rgb an 3-size array that holds the rgb values on method exit
+ */
+ private void getRGB(int x, int y, Data img, int[] rgb, int lineByteCount)
+ {
+ // TODO: Does this also work on non-RGB devices?
+ int i = y * lineByteCount + pixelByteCount * x;
+ if (imageByteOrder == gnu.x11.image.Image.LSB_FIRST)
+ {//if (i >= 5716-33) System.err.println("lbc: " + lineByteCount + ", " + pixelByteCount);
+ rgb[2] = img.data[32 + i];
+ rgb[1] = img.data[32 + i + 1];
+ rgb[0] = img.data[32 + i + 2];
+ }
+ else
+ { // MSB_FIRST
+ rgb[0] = img.data[32 + i];
+ rgb[1] = img.data[32 + i + 1];
+ rgb[2] = img.data[32 + i + 2];
+ }
+
+ }
+
+ /**
+ * Helper method to work around limitation in the current Escher impl.
+ *
+ * @param x the x position
+ * @param y the y position
+ * @param img the image data
+ * @param rgb an 3-size array that holds the rgb values on method exit
+ */
+ private void setRGB(int x, int y, Data img, int[] rgb, int lineByteCount)
+ {
+ // TODO: Does this also work on non-RGB devices?
+ int i = y * lineByteCount + pixelByteCount * x;
+ if (imageByteOrder == gnu.x11.image.Image.LSB_FIRST)
+ {
+ img.data[32 + i] = (byte) rgb[2];
+ img.data[32 + i + 1] = (byte) rgb[1];
+ img.data[32 + i + 2] = (byte) rgb[0];
+ }
+ else
+ { // MSB_FIRST
+ img.data[32 + i] = (byte) rgb[0];
+ img.data[32 + i + 1] = (byte) rgb[1];
+ img.data[32 + i + 2] = (byte) rgb[2];
+ }
+ }
+
+ public boolean drawImage(Image image, int x, int y, int width, int height,
+ ImageObserver observer)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public boolean drawImage(Image image, int x, int y, Color bgcolor,
+ ImageObserver observer)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public boolean drawImage(Image image, int x, int y, int width, int height,
+ Color bgcolor, ImageObserver observer)
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2,
+ int sx1, int sy1, int sx2, int sy2,
+ ImageObserver observer)
+ {
+ return drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null,
+ observer);
+ }
+
+ public boolean drawImage(Image image, int dx1, int dy1, int dx2, int dy2,
+ int sx1, int sy1, int sx2, int sy2, Color bgcolor,
+ ImageObserver observer)
+ {
+
+ // FIXME: What to do with bgcolor?
+
+ // Scale the image.
+ int sw = image.getWidth(observer);
+ int sh = image.getHeight(observer);
+ double scaleX = Math.abs(dx2 - dx1) / (double) Math.abs(sx2 - sx1);
+ double scaleY = Math.abs(dy2 - dy1) / (double) Math.abs(sy2 - sy1);
+ Image scaled = image.getScaledInstance((int) (scaleX * sw),
+ (int) (scaleY * sh),
+ Image.SCALE_FAST);
+
+ // Scaled source coordinates.
+ int sx1s = (int) (scaleX * Math.min(sx1, sx2));
+ int sx2s = (int) (scaleX * Math.max(sx1, sx2));
+
+ // Temporarily clip to the target rectangle.
+ Rectangle old = clip;
+ clipRect(dx1, dy1, dx2 - dx1, dy2 - dy1);
+
+ // Draw scaled image.
+ boolean res = drawImage(scaled, dx1 - sx1s, dy1 - sx2s, observer);
+
+ // Reset clip.
+ setClip(old);
+
+ return res;
+ }
+
+ /**
+ * Frees any resources associated with this object.
+ */
+ public void dispose()
+ {
+ if (! disposed)
+ {
+ xgc.free();
+ xdrawable.display.flush();
+ disposed = true;
+ }
+ }
+
+ // Additional helper methods.
+
+ /**
+ * Creates and returns an exact copy of this XGraphics.
+ */
+ protected Object clone()
+ {
+ try
+ {
+ XGraphics copy = (XGraphics) super.clone();
+ copy.xgc = xgc.copy();
+ if (clip != null)
+ {
+ copy.clip = new Rectangle(clip);
+ copy.setXClip(clip.x, clip.y, clip.width, clip.height);
+ }
+ return copy;
+ }
+ catch (CloneNotSupportedException ex)
+ {
+ assert false;
+ }
+ return null;
+ }
+
+ /**
+ * Computes the intersection between two rectangles and stores the result
+ * int the second rectangle.
+ *
+ * This method has been copied from {@link javax.swing.SwingUtilities}.
+ *
+ * @param x the x coordinate of the rectangle #1
+ * @param y the y coordinate of the rectangle #1
+ * @param w the width of the rectangle #1
+ * @param h the height of the rectangle #1
+ * @param rect the rectangle #2 and output rectangle
+ */
+ private static void computeIntersection(int x, int y, int w, int h,
+ Rectangle rect)
+ {
+ int x2 = (int) rect.x;
+ int y2 = (int) rect.y;
+ int w2 = (int) rect.width;
+ int h2 = (int) rect.height;
+
+ int dx = (x > x2) ? x : x2;
+ int dy = (y > y2) ? y : y2;
+ int dw = (x + w < x2 + w2) ? (x + w - dx) : (x2 + w2 - dx);
+ int dh = (y + h < y2 + h2) ? (y + h - dy) : (y2 + h2 - dy);
+
+ if (dw >= 0 && dh >= 0)
+ rect.setBounds(dx, dy, dw, dh);
+ else
+ rect.setBounds(0, 0, 0, 0);
+ }
+
+
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XGraphics2D.java b/libjava/classpath/gnu/java/awt/peer/x/XGraphics2D.java
new file mode 100644
index 0000000..5dc79ff
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XGraphics2D.java
@@ -0,0 +1,295 @@
+/* XGraphics2D.java -- A Java based Graphics2D impl for X
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Graphics;
+import java.awt.GraphicsConfiguration;
+import java.awt.Rectangle;
+import java.awt.Shape;
+import java.awt.Toolkit;
+import java.awt.geom.AffineTransform;
+import java.awt.image.ColorModel;
+import java.awt.image.Raster;
+
+import gnu.java.awt.java2d.AbstractGraphics2D;
+import gnu.x11.Drawable;
+import gnu.x11.GC;
+import gnu.x11.image.ZPixmap;
+
+public class XGraphics2D
+ extends AbstractGraphics2D
+{
+
+ /**
+ * The X Drawable to draw on.
+ */
+ private Drawable xdrawable;
+
+ /**
+ * The X graphics context (GC).
+ */
+ private GC xgc;
+
+ /**
+ * Indicates if this graphics has already been disposed.
+ */
+ private boolean disposed;
+
+ XGraphics2D(Drawable d)
+ {
+ super();
+ xdrawable = d;
+ xgc = new GC(d);
+ init();
+ disposed = false;
+ //setClip(new Rectangle(0, 0, xdrawable.width, xdrawable.height));
+ }
+
+ /**
+ * Draws a pixel in the target coordinate space using the specified color.
+ *
+ * @param x the x coordinate
+ * @param y the y coordinate
+ */
+ protected void rawSetPixel(int x, int y)
+ {
+ xdrawable.point(xgc, x, y);
+ }
+
+// protected void rawFillPolygon(double[] xpoints, double[] ypoints, int npoints)
+// {
+// Point[] points = new Point[npoints];
+// for (int n = 0; n < npoints; n++)
+// {
+// points[n] = new Point((int) xpoints[n], (int) ypoints[n]);
+// }
+// xdrawable.fill_poly(xgc, points, Drawable.COMPLEX, Drawable.ORIGIN);
+// xdrawable.display.flush();
+// }
+
+ protected void rawDrawLine(int x0, int y0, int x1, int y1)
+ {
+ xdrawable.line(xgc, x0, y0, x1, y1);
+ }
+
+ protected void rawFillRect(int x, int y, int w, int h)
+ {
+ xdrawable.rectangle(xgc, x, y, w, h, true);
+ }
+
+ protected void rawSetForeground(java.awt.Color c)
+ {
+ if (c != null)
+ xgc.set_foreground(c.getRGB());
+ }
+
+ protected void rawSetForeground(int r, int g, int b)
+ {
+ xgc.set_foreground( r << 16 | g << 8 | b );
+ }
+
+ /**
+ * Returns the color model of this Graphics object.
+ *
+ * @return the color model of this Graphics object
+ */
+ protected ColorModel getColorModel()
+ {
+ return Toolkit.getDefaultToolkit().getColorModel();
+ }
+
+ /**
+ * Returns the color model of the target device.
+ *
+ * @return the color model of the target device
+ */
+ protected ColorModel getDestinationColorModel()
+ {
+ return Toolkit.getDefaultToolkit().getColorModel();
+ }
+
+ /**
+ * Returns the bounds of the target.
+ *
+ * @return the bounds of the target
+ */
+ protected Rectangle getDeviceBounds()
+ {
+ return new Rectangle(0, 0, xdrawable.width, xdrawable.height);
+ }
+
+ public GraphicsConfiguration getDeviceConfiguration()
+ {
+ // FIXME: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ public void dispose()
+ {
+ if (!disposed)
+ {
+ xgc.free();
+ xdrawable.display.flush();
+ disposed = true;
+ }
+ }
+
+ public Graphics create()
+ {
+ // super.create() returns a copy created by clone(), so it should
+ // be a XGraphics2D.
+ XGraphics2D copy = (XGraphics2D) super.create();
+ copy.xgc = xgc.copy();
+ return copy;
+ }
+
+// /**
+// * Draws the specified image on the drawable at position (x,y).
+// */
+//
+// public boolean drawImage(Image image, int x, int y, ImageObserver observer)
+// {
+// AffineTransform transform = getTransform();
+// int translateX = (int) transform.getTranslateX();
+// int translateY = (int) transform.getTranslateY();
+// if (image instanceof XImage)
+// {
+// XImage xim = (XImage) image;
+// Pixmap pm = xim.pixmap;
+// xdrawable.copy_area(pm, xgc, 0, 0, pm.width, pm.height,
+// x + translateX, y + translateY);
+// }
+// else if (image instanceof BufferedImage)
+// {
+// BufferedImage bufferedImage = (BufferedImage) image;
+// Raster raster = bufferedImage.getData();
+// int w = bufferedImage.getWidth();
+// int h = bufferedImage.getHeight();
+// // Push data to X server.
+// ZPixmap zPixmap = new ZPixmap(xdrawable.display, w, h,
+// xdrawable.display.default_pixmap_format);
+// System.err.println("data buffer length: " + zPixmap.data.length);
+// int[] pixel = new int[4];
+// for (int tx = 0; tx < w; tx++)
+// {
+// for (int ty = 0; ty < h; ty++)
+// {
+// pixel = raster.getPixel(tx, ty, pixel);
+//// System.err.print("r: " + pixel[0]);
+//// System.err.print(", g: " + pixel[1]);
+//// System.err.println(", b: " + pixel[2]);
+// zPixmap.set_red(tx, ty, pixel[0]);
+// zPixmap.set_green(tx, ty, pixel[1]);
+// zPixmap.set_blue(tx, ty, pixel[2]);
+// }
+// }
+// xdrawable.put_image(xgc, zPixmap, x, y);
+// }
+// else
+// {
+// throw new UnsupportedOperationException("Not yet implemented.");
+// }
+// return true;
+// }
+//
+ public void setClip(Shape c)
+ {
+ super.setClip(c);
+ if (c instanceof Rectangle)
+ {
+ Rectangle r = (Rectangle) c;
+ AffineTransform t = getTransform();
+ int translateX = (int) t.getTranslateX();
+ //System.err.println("translateX: " + translateX);
+ int translateY = (int) t.getTranslateY();
+ //System.err.println("translateY: " + translateY);
+ //System.err.println("clip: " + c);
+ gnu.x11.Rectangle clip = new gnu.x11.Rectangle(r.x, r.y, r.width,
+ r.height);
+ xgc.set_clip_rectangles(translateX, translateY,
+ new gnu.x11.Rectangle[]{clip}, GC.UN_SORTED);
+ }
+ }
+
+ /**
+ * Notifies the backend that the raster has changed in the specified
+ * rectangular area. The raster that is provided in this method is always
+ * the same as the one returned in {@link #getDestinationRaster}.
+ * Backends that reflect changes to this raster directly don't need to do
+ * anything here.
+ *
+ * @param raster the updated raster, identical to the raster returned
+ * by {@link #getDestinationRaster()}
+ * @param x the upper left corner of the updated region, X coordinate
+ * @param y the upper lef corner of the updated region, Y coordinate
+ * @param w the width of the updated region
+ * @param h the height of the updated region
+ */
+ protected void updateRaster(Raster raster, int x, int y, int w, int h)
+ {
+ if (w > 0 && h > 0)
+ {
+ ZPixmap zPixmap = new ZPixmap(xdrawable.display, w, h,
+ xdrawable.display.default_pixmap_format);
+ int[] pixel = null;
+ int x1 = x + w;
+ int y1 = y + h;
+ for (int tx = x; tx < x1; tx++)
+ {
+ for (int ty = y; ty < y1; ty++)
+ {
+ pixel = raster.getPixel(tx, ty, pixel);
+ //System.err.println("tx: " + tx + ", ty: " + ty + ", pixel: " + pixel[0] + ", " + pixel[1] + ", " + pixel[2]);
+// System.err.print("r: " + pixel[0]);
+// System.err.print(", g: " + pixel[1]);
+// System.err.println(", b: " + pixel[2]);
+ zPixmap.set_red(tx - x, ty - y, pixel[0]);
+ zPixmap.set_green(tx - x, ty - y, pixel[1]);
+ zPixmap.set_blue(tx - x, ty - y, pixel[2]);
+ }
+ }
+ xdrawable.put_image(xgc, zPixmap, x, y);
+ }
+ }
+
+
+ protected void init()
+ {
+ super.init();
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XGraphicsConfiguration.java b/libjava/classpath/gnu/java/awt/peer/x/XGraphicsConfiguration.java
new file mode 100644
index 0000000..d6e66cb
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XGraphicsConfiguration.java
@@ -0,0 +1,118 @@
+/* XGraphicsConfiguration.java -- GraphicsConfiguration for X
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.x;
+
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.awt.Rectangle;
+import java.awt.geom.AffineTransform;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorModel;
+import java.awt.image.VolatileImage;
+
+public class XGraphicsConfiguration
+ extends GraphicsConfiguration
+{
+
+ XGraphicsDevice device;
+
+ XGraphicsConfiguration(XGraphicsDevice dev)
+ {
+ device = dev;
+ }
+
+ public GraphicsDevice getDevice()
+ {
+ return device;
+ }
+
+ public BufferedImage createCompatibleImage(int w, int h)
+ {
+ return new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
+ }
+
+ public VolatileImage createCompatibleVolatileImage(int w, int h)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public VolatileImage createCompatibleVolatileImage(int width, int height,
+ int transparency)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public BufferedImage createCompatibleImage(int w, int h, int transparency)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public ColorModel getColorModel()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public ColorModel getColorModel(int transparency)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public AffineTransform getDefaultTransform()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public AffineTransform getNormalizingTransform()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public Rectangle getBounds()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XGraphicsDevice.java b/libjava/classpath/gnu/java/awt/peer/x/XGraphicsDevice.java
new file mode 100644
index 0000000..6a020ec
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XGraphicsDevice.java
@@ -0,0 +1,166 @@
+/* XGraphicsDevice.java -- GraphicsDevice for X
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.awt.peer.x;
+
+import gnu.classpath.SystemProperties;
+import gnu.java.net.local.LocalSocket;
+import gnu.java.net.local.LocalSocketAddress;
+import gnu.x11.Connection;
+import gnu.x11.Display;
+
+import java.awt.AWTError;
+import java.awt.GraphicsConfiguration;
+import java.awt.GraphicsDevice;
+import java.net.SocketException;
+
+/**
+ * This class represents an X Display. The actual connection is established
+ * lazily when it is first needed.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class XGraphicsDevice
+ extends GraphicsDevice
+{
+
+ private XGraphicsConfiguration defaultConfiguration;
+
+ /**
+ * The X display associated with the XGraphicsDevice. This is established
+ * when {@link #getDisplay} is first called.
+ */
+ private Display display;
+
+ /**
+ * The display name from which the display will be initialized.
+ */
+ private Display.Name displayName;
+
+ /**
+ * The event pump for this X Display.
+ */
+ private XEventPump eventPump;
+
+ /**
+ * Creates a new XGraphicsDevice.
+ */
+ XGraphicsDevice(Display.Name dn)
+ {
+ displayName = dn;
+ }
+
+ public int getType()
+ {
+ return TYPE_RASTER_SCREEN;
+ }
+
+ public String getIDstring()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public GraphicsConfiguration[] getConfigurations()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public GraphicsConfiguration getDefaultConfiguration()
+ {
+ if (defaultConfiguration == null)
+ defaultConfiguration = new XGraphicsConfiguration(this);
+ return defaultConfiguration;
+ }
+
+ /**
+ * Returns the X Display associated with this XGraphicsDevice.
+ * This establishes the connection to the X server on the first invocation.
+ *
+ * @return the X Display associated with this XGraphicsDevice
+ */
+ Display getDisplay()
+ {
+ if (display == null)
+ {
+ if (displayName.hostname.equals(""))
+ displayName.hostname = "localhost";
+ if (XToolkit.DEBUG)
+ System.err.println("connecting to : " + displayName);
+ // Try to connect via unix domain sockets when host == localhost.
+ if ((displayName.hostname.equals("localhost")
+ || displayName.hostname.equals(""))
+ && SystemProperties.getProperty("gnu.xawt.no_local_sockets") == null)
+ {
+ // TODO: Is this 100% ok?
+ String sockPath = "/tmp/.X11-unix/X" + displayName.display_no;
+ LocalSocketAddress addr = new LocalSocketAddress(sockPath);
+ try
+ {
+ if (XToolkit.DEBUG)
+ System.err.println("connecting to local socket: "
+ + sockPath);
+ LocalSocket socket = new LocalSocket(addr);
+ display = new Display(socket, "localhost",
+ displayName.display_no,
+ displayName.screen_no);
+ display.connection.send_mode = Connection.ASYNCHRONOUS;
+ if (XToolkit.DEBUG)
+ System.err.println("connected to local socket");
+ }
+ catch (SocketException ex)
+ {
+ AWTError err = new AWTError("could not connect to X server");
+ err.initCause(ex);
+ throw err;
+ }
+ }
+ else
+ {
+ display = new Display(displayName);
+ }
+ eventPump = new XEventPump(display);
+ }
+ return display;
+ }
+
+ XEventPump getEventPump()
+ {
+ return eventPump;
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XGraphicsEnvironment.java b/libjava/classpath/gnu/java/awt/peer/x/XGraphicsEnvironment.java
new file mode 100644
index 0000000..65383a6
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XGraphicsEnvironment.java
@@ -0,0 +1,202 @@
+/* XGraphicsEnvironment.java -- Represents the X environment
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import gnu.java.awt.java2d.RasterGraphics;
+import gnu.x11.Display;
+
+import java.awt.Font;
+import java.awt.Graphics2D;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Locale;
+import java.util.Properties;
+
+/**
+ * Represents the X environment for AWT.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class XGraphicsEnvironment
+ extends GraphicsEnvironment
+{
+
+ /**
+ * The default graphics device. This is normally the local main X
+ * Display, but can be configured to be any X connection.
+ */
+ private XGraphicsDevice defaultDevice;
+
+ /**
+ * All configured devices.
+ */
+ private XGraphicsDevice[] devices;
+
+ /**
+ * Creates a new XGraphicsEnvironment. This loads the configuration if
+ * there is one present and initializes the XGraphicsDevices in the
+ * environment. If there is no configuration, then there is one
+ * default device initialized with the local main X device.
+ */
+ public XGraphicsEnvironment()
+ {
+ // Initiliaze the devices.
+ Properties props = new Properties();
+ File config = new File(System.getProperty("user.home"),
+ ".xawt.properties");
+
+ try
+ {
+ FileInputStream configIn = new FileInputStream(config);
+ props.load(configIn);
+ int dev = 1;
+ ArrayList deviceList = new ArrayList();
+ while (true)
+ {
+ String propName = "display." + dev;
+ String propValue = props.getProperty(propName);
+ if (propValue != null)
+ {
+ Display.Name displayName = new Display.Name(propValue);
+ XGraphicsDevice device = new XGraphicsDevice(displayName);
+ if (dev == 1)
+ defaultDevice = device;
+ deviceList.add(device);
+ dev++;
+ }
+ else
+ {
+ if (dev == 1)
+ {
+ defaultDevice = initDefaultDevice();
+ deviceList.add(defaultDevice);
+ }
+ break;
+ }
+ }
+ devices = (XGraphicsDevice[]) deviceList.toArray
+ (new XGraphicsDevice[deviceList.size()]);
+ }
+ catch (FileNotFoundException ex)
+ {
+ defaultDevice = initDefaultDevice();
+ devices = new XGraphicsDevice[]{ defaultDevice };
+ }
+ catch (IOException ex)
+ {
+ defaultDevice = initDefaultDevice();
+ devices = new XGraphicsDevice[]{ defaultDevice };
+ }
+
+ }
+
+ /**
+ * Helper method that initializes the default device in the case when there
+ * is no configuration for the default.
+ */
+ private XGraphicsDevice initDefaultDevice()
+ {
+ String display = System.getenv("DISPLAY");
+ if (display == null)
+ display = ":0.0";
+ Display.Name displayName = new Display.Name(display);
+ return new XGraphicsDevice(displayName);
+ }
+
+ /**
+ * Returns all configured screen devices.
+ *
+ * @return all configured screen devices
+ */
+ public GraphicsDevice[] getScreenDevices()
+ {
+ // We return a copy so that nobody can fiddle with our devices.
+ XGraphicsDevice[] copy = new XGraphicsDevice[devices.length];
+ System.arraycopy(devices, 0, copy, 0, devices.length);
+ return copy;
+ }
+
+ /**
+ * Returns the default screen device.
+ *
+ * @return the default screen device
+ */
+ public GraphicsDevice getDefaultScreenDevice()
+ {
+ return defaultDevice;
+ }
+
+ /**
+ * Returns a Graphics instance suitable for drawing on top of the
+ * BufferedImage.
+ *
+ * @param image the buffered image to create a graphics for
+ *
+ * @return a Graphics2D instance for drawing on the BufferedImage
+ */
+ public Graphics2D createGraphics(BufferedImage image)
+ {
+ return new RasterGraphics(image.getRaster(), image.getColorModel());
+ }
+
+ public Font[] getAllFonts()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public String[] getAvailableFontFamilyNames()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public String[] getAvailableFontFamilyNames(Locale l)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XImage.java b/libjava/classpath/gnu/java/awt/peer/x/XImage.java
new file mode 100644
index 0000000..b9e9936
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XImage.java
@@ -0,0 +1,111 @@
+/* XImage.java -- Image impl for X Pixmaps
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import gnu.x11.Pixmap;
+
+import java.awt.Graphics;
+import java.awt.GraphicsEnvironment;
+import java.awt.Image;
+import java.awt.image.ImageObserver;
+import java.awt.image.ImageProducer;
+import java.util.Hashtable;
+
+public class XImage
+ extends Image
+{
+
+ Pixmap pixmap;
+
+ private Hashtable properties;
+
+ XImage(int w, int h)
+ {
+ GraphicsEnvironment env =
+ GraphicsEnvironment.getLocalGraphicsEnvironment();
+ XGraphicsDevice dev = (XGraphicsDevice) env.getDefaultScreenDevice();
+ pixmap = new Pixmap(dev.getDisplay(), w, h);
+ }
+
+ public int getWidth(ImageObserver observer)
+ {
+ return pixmap.width;
+ }
+
+ public int getHeight(ImageObserver observer)
+ {
+ return pixmap.height;
+ }
+
+ public ImageProducer getSource()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Creates an XGraphics for drawing on this XImage.
+ *
+ * @return an XGraphics for drawing on this XImage
+ */
+ public Graphics getGraphics()
+ {
+ XGraphics g = new XGraphics(pixmap);
+ return g;
+ }
+
+ public Object getProperty(String name, ImageObserver observer)
+ {
+ Object val = null;
+ if (properties != null)
+ val = properties.get(val);
+ return val;
+ }
+
+ public void flush()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected void finalize()
+ {
+ pixmap.free();
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XLightweightPeer.java b/libjava/classpath/gnu/java/awt/peer/x/XLightweightPeer.java
new file mode 100644
index 0000000..2613d84
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XLightweightPeer.java
@@ -0,0 +1,56 @@
+/* XLightweightPeer.java -- A lightweight peer for X
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Component;
+import java.awt.peer.LightweightPeer;
+
+import gnu.java.awt.peer.swing.SwingContainerPeer;
+
+public class XLightweightPeer
+ extends SwingContainerPeer
+ implements LightweightPeer
+{
+
+ XLightweightPeer(Component c)
+ {
+ super(c);
+ init(c, null);
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XToolkit.java b/libjava/classpath/gnu/java/awt/peer/x/XToolkit.java
new file mode 100644
index 0000000..a286fd6
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XToolkit.java
@@ -0,0 +1,608 @@
+/* XToolkit.java -- The central AWT Toolkit for the X peers
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import java.awt.AWTException;
+import java.awt.Button;
+import java.awt.Canvas;
+import java.awt.Checkbox;
+import java.awt.CheckboxMenuItem;
+import java.awt.Choice;
+import java.awt.Component;
+import java.awt.Dialog;
+import java.awt.Dimension;
+import java.awt.EventQueue;
+import java.awt.FileDialog;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Frame;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.Image;
+import java.awt.Label;
+import java.awt.List;
+import java.awt.Menu;
+import java.awt.MenuBar;
+import java.awt.MenuItem;
+import java.awt.Panel;
+import java.awt.PopupMenu;
+import java.awt.PrintJob;
+import java.awt.ScrollPane;
+import java.awt.Scrollbar;
+import java.awt.TextArea;
+import java.awt.TextField;
+import java.awt.Transparency;
+import java.awt.Window;
+import java.awt.datatransfer.Clipboard;
+import java.awt.dnd.DragGestureEvent;
+import java.awt.dnd.peer.DragSourceContextPeer;
+import java.awt.im.InputMethodHighlight;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorModel;
+import java.awt.image.DirectColorModel;
+import java.awt.image.ImageObserver;
+import java.awt.image.ImageProducer;
+import java.awt.peer.ButtonPeer;
+import java.awt.peer.CanvasPeer;
+import java.awt.peer.CheckboxMenuItemPeer;
+import java.awt.peer.CheckboxPeer;
+import java.awt.peer.ChoicePeer;
+import java.awt.peer.DialogPeer;
+import java.awt.peer.FileDialogPeer;
+import java.awt.peer.FontPeer;
+import java.awt.peer.FramePeer;
+import java.awt.peer.LabelPeer;
+import java.awt.peer.LightweightPeer;
+import java.awt.peer.ListPeer;
+import java.awt.peer.MenuBarPeer;
+import java.awt.peer.MenuItemPeer;
+import java.awt.peer.MenuPeer;
+import java.awt.peer.PanelPeer;
+import java.awt.peer.PopupMenuPeer;
+import java.awt.peer.RobotPeer;
+import java.awt.peer.ScrollPanePeer;
+import java.awt.peer.ScrollbarPeer;
+import java.awt.peer.TextAreaPeer;
+import java.awt.peer.TextFieldPeer;
+import java.awt.peer.WindowPeer;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.WeakHashMap;
+
+import javax.imageio.ImageIO;
+
+import gnu.classpath.SystemProperties;
+import gnu.java.awt.ClasspathToolkit;
+import gnu.java.awt.EmbeddedWindow;
+import gnu.java.awt.peer.ClasspathFontPeer;
+import gnu.java.awt.peer.EmbeddedWindowPeer;
+import gnu.java.awt.peer.swing.SwingCanvasPeer;
+import gnu.java.awt.peer.swing.SwingLabelPeer;
+import gnu.java.awt.peer.swing.SwingPanelPeer;
+
+public class XToolkit
+ extends ClasspathToolkit
+{
+
+ /**
+ * Set to true to enable debug output.
+ */
+ static boolean DEBUG = false;
+
+ /**
+ * Maps AWT colors to X colors.
+ */
+ HashMap colorMap = new HashMap();
+
+ /**
+ * The system event queue.
+ */
+ private EventQueue eventQueue;
+
+ /**
+ * The default color model of this toolkit.
+ */
+ private ColorModel colorModel;
+
+ /**
+ * Maps image URLs to Image instances.
+ */
+ private HashMap imageCache = new HashMap();
+
+ /**
+ * The cached fonts.
+ */
+ private WeakHashMap fontCache = new WeakHashMap();
+
+ public XToolkit()
+ {
+ SystemProperties.setProperty("gnu.javax.swing.noGraphics2D", "true");
+ SystemProperties.setProperty("java.awt.graphicsenv",
+ "gnu.java.awt.peer.x.XGraphicsEnvironment");
+ }
+
+ public GraphicsEnvironment getLocalGraphicsEnvironment()
+ {
+ return new XGraphicsEnvironment();
+ }
+
+ /**
+ * Returns the font peer for a font with the specified name and attributes.
+ *
+ * @param name the font name
+ * @param attrs the font attributes
+ *
+ * @return the font peer for a font with the specified name and attributes
+ */
+ public ClasspathFontPeer getClasspathFontPeer(String name, Map attrs)
+ {
+ String canonical = XFontPeer.encodeFont(name, attrs);
+ ClasspathFontPeer font;
+ if (!fontCache.containsKey(canonical))
+ {
+ String graphics2d =
+ SystemProperties.getProperty("gnu.xawt.graphics2d");
+ if (graphics2d != null && graphics2d.equals("gl"))
+ font = new XFontPeer2(name, attrs);
+ else
+ font = new XFontPeer(name, attrs);
+ fontCache.put(canonical, font);
+ }
+ else
+ {
+ font = (ClasspathFontPeer) fontCache.get(canonical);
+ }
+ return font;
+ }
+
+ public Font createFont(int format, InputStream stream)
+ {
+ return null;
+ }
+
+ public RobotPeer createRobot(GraphicsDevice screen) throws AWTException
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public EmbeddedWindowPeer createEmbeddedWindow(EmbeddedWindow w)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected ButtonPeer createButton(Button target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected TextFieldPeer createTextField(TextField target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected LabelPeer createLabel(Label target)
+ {
+ return new SwingLabelPeer(target);
+ }
+
+ protected ListPeer createList(List target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected CheckboxPeer createCheckbox(Checkbox target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected ScrollbarPeer createScrollbar(Scrollbar target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected ScrollPanePeer createScrollPane(ScrollPane target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected TextAreaPeer createTextArea(TextArea target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected ChoicePeer createChoice(Choice target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected FramePeer createFrame(Frame target)
+ {
+ XFramePeer frame = new XFramePeer(target);
+ return frame;
+ }
+
+ protected CanvasPeer createCanvas(Canvas target)
+ {
+ return new SwingCanvasPeer(target);
+ }
+
+ protected PanelPeer createPanel(Panel target)
+ {
+ return new SwingPanelPeer(target);
+ }
+
+ protected WindowPeer createWindow(Window target)
+ {
+ return new XWindowPeer(target);
+ }
+
+ protected DialogPeer createDialog(Dialog target)
+ {
+ return new XDialogPeer(target);
+ }
+
+ protected MenuBarPeer createMenuBar(MenuBar target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected MenuPeer createMenu(Menu target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected PopupMenuPeer createPopupMenu(PopupMenu target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected MenuItemPeer createMenuItem(MenuItem target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected FileDialogPeer createFileDialog(FileDialog target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ protected FontPeer getFontPeer(String name, int style)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public Dimension getScreenSize()
+ {
+ // FIXME: This is only a hack to get some apps working.
+ return new Dimension(1024, 768);
+ }
+
+ public int getScreenResolution()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Returns the color model used by this toolkit.
+ *
+ * @return the color model used by this toolkit
+ */
+ public ColorModel getColorModel()
+ {
+ // TODO: I assume 24 bit depth here, we can do this better.
+ if (colorModel == null)
+ colorModel = new DirectColorModel(24, 0xFF0000, 0xFF00, 0xFF);
+ return colorModel;
+ }
+
+ public String[] getFontList()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public FontMetrics getFontMetrics(Font name)
+ {
+ ClasspathFontPeer peer = (ClasspathFontPeer) name.getPeer();
+ return peer.getFontMetrics(name);
+ }
+
+ public void sync()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Returns an image that has its pixel data loaded from a file with the
+ * specified name. If that file doesn't exist, an empty or error image
+ * is returned instead.
+ *
+ * @param name the filename of the file that contains the pixel data
+ *
+ * @return the image
+ */
+ public Image getImage(String name)
+ {
+ Image image;
+ try
+ {
+ File file = new File(name);
+ image = getImage(file.toURL());
+ }
+ catch (MalformedURLException ex)
+ {
+ // TODO: Replace by a more meaningful error image instead.
+ image = null;
+ }
+ return image;
+ }
+
+ /**
+ * Returns an image that has its pixel data loaded from the specified URL.
+ * If the image cannot be loaded for some reason, an empty or error image
+ * is returned instead.
+ *
+ * @param url the URL to the image data
+ *
+ * @return the image
+ */
+ public Image getImage(URL url)
+ {
+ Image image;
+ if (imageCache.containsKey(url))
+ {
+ image = (Image) imageCache.get(url);
+ }
+ else
+ {
+ image = createImage(url);
+ imageCache.put(url, image);
+ }
+ return image;
+ }
+
+ /**
+ * Returns an image that has its pixel data loaded from a file with the
+ * specified name. If that file doesn't exist, an empty or error image
+ * is returned instead.
+ *
+ * @param filename the filename of the file that contains the pixel data
+ *
+ * @return the image
+ */
+ public Image createImage(String filename)
+ {
+ Image im;
+ try
+ {
+ File file = new File(filename);
+ URL url = file.toURL();
+ im = createImage(url);
+ }
+ catch (MalformedURLException ex)
+ {
+ im = createErrorImage();
+ }
+ return im;
+ }
+
+ /**
+ * Returns an image that has its pixel data loaded from the specified URL.
+ * If the image cannot be loaded for some reason, an empty or error image
+ * is returned instead.
+ *
+ * @param url the URL to the image data
+ *
+ * @return the image
+ */
+ public Image createImage(URL url)
+ {
+ Image image;
+ try
+ {
+ image = createImage(url.openStream());
+ }
+ catch (IOException ex)
+ {
+ image = createErrorImage();
+ }
+ return image;
+ }
+
+ /**
+ * Creates an image that is returned when calls to createImage() yields an
+ * error.
+ *
+ * @return an image that is returned when calls to createImage() yields an
+ * error
+ */
+ private Image createErrorImage()
+ {
+ // TODO: Create better error image.
+ return new XImage(1, 1);
+ }
+
+ public boolean prepareImage(Image image, int width, int height, ImageObserver observer)
+ {
+ // Images are loaded synchronously, so we don't bother and return true.
+ return true;
+ }
+
+ public int checkImage(Image image, int width, int height, ImageObserver observer)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public Image createImage(ImageProducer producer)
+ {
+ ImageConverter conv = new ImageConverter();
+ producer.startProduction(conv);
+ Image image = conv.getXImage();
+ return image;
+ }
+
+ public Image createImage(byte[] data, int offset, int len)
+ {
+ Image image;
+ try
+ {
+ ByteArrayInputStream i = new ByteArrayInputStream(data, offset, len);
+ image = createImage(i);
+ }
+ catch (IOException ex)
+ {
+ image = createErrorImage();
+ }
+ return image;
+ }
+
+ private Image createImage(InputStream i)
+ throws IOException
+ {
+ Image image;
+ BufferedImage buffered = ImageIO.read(i);
+ // If the bufferedimage is opaque, then we can copy it over to an
+ // X Pixmap for faster drawing.
+ if (buffered != null && buffered.getTransparency() == Transparency.OPAQUE)
+ {
+ ImageProducer source = buffered.getSource();
+ image = createImage(source);
+ }
+ else if (buffered != null)
+ {
+ image = buffered;
+ }
+ else
+ {
+ image = createErrorImage();
+ }
+ return image;
+ }
+
+ public PrintJob getPrintJob(Frame frame, String title, Properties props)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public void beep()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public Clipboard getSystemClipboard()
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Returns the eventqueue used by the XLib peers.
+ *
+ * @return the eventqueue used by the XLib peers
+ */
+ protected EventQueue getSystemEventQueueImpl()
+ {
+ if (eventQueue == null)
+ eventQueue = new EventQueue();
+ return eventQueue;
+ }
+
+ public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent e)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ public Map mapInputMethodHighlight(InputMethodHighlight highlight)
+ {
+ // TODO: Implement this.
+ throw new UnsupportedOperationException("Not yet implemented.");
+ }
+
+ /**
+ * Helper method to quickly fetch the default device (X Display).
+ *
+ * @return the default XGraphicsDevice
+ */
+ static XGraphicsDevice getDefaultDevice()
+ {
+ XGraphicsEnvironment env = (XGraphicsEnvironment)
+ XGraphicsEnvironment.getLocalGraphicsEnvironment();
+ return (XGraphicsDevice) env.getDefaultScreenDevice();
+ }
+
+ protected LightweightPeer createComponent(Component c)
+ {
+ return new XLightweightPeer(c);
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/peer/x/XWindowPeer.java b/libjava/classpath/gnu/java/awt/peer/x/XWindowPeer.java
new file mode 100644
index 0000000..28cc5a5
--- /dev/null
+++ b/libjava/classpath/gnu/java/awt/peer/x/XWindowPeer.java
@@ -0,0 +1,255 @@
+/* XWindowPeer.java -- Window peer for X
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.awt.peer.x;
+
+import java.awt.Component;
+import java.awt.EventQueue;
+import java.awt.Font;
+import java.awt.FontMetrics;
+import java.awt.Graphics;
+import java.awt.Image;
+import java.awt.Insets;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.event.PaintEvent;
+import java.awt.event.WindowEvent;
+
+import gnu.x11.Window;
+import gnu.x11.event.Event;
+
+import gnu.java.awt.peer.swing.SwingWindowPeer;
+
+public class XWindowPeer
+ extends SwingWindowPeer
+{
+
+ private static int standardSelect = Event.BUTTON_PRESS_MASK
+ | Event.BUTTON_RELEASE_MASK
+ | Event.POINTER_MOTION_MASK
+ //| Event.RESIZE_REDIRECT_MASK
+ | Event.EXPOSURE_MASK
+ //| Event.PROPERTY_CHANGE_MASK
+ | Event.STRUCTURE_NOTIFY_MASK
+ | Event.KEY_PRESS_MASK
+ | Event.KEY_RELEASE_MASK
+ ;
+
+ /**
+ * Indicates if we are in callback mode, that is when a property (like size)
+ * is changed in reponse to a request from the X server and doesn't need
+ * to be propagated back to the X server.
+ */
+ boolean callback = false;
+
+ /**
+ * The X window.
+ */
+ private Window xwindow;
+
+ XWindowPeer(java.awt.Window window)
+ {
+ super(window);
+ XGraphicsDevice dev = XToolkit.getDefaultDevice();
+
+ // TODO: Maybe initialize lazily in show().
+ // FIXME: Howto generate a Window without decorations?
+ int x = Math.max(window.getX(), 0);
+ int y = Math.max(window.getY(), 0);
+ int w = Math.max(window.getWidth(), 1);
+ int h = Math.max(window.getHeight(), 1);
+ xwindow = new Window(dev.getDisplay().default_root, x, y, w, h);
+ xwindow.create();
+ xwindow.select_input(standardSelect);
+ dev.getEventPump().registerWindow(xwindow, window);
+ }
+
+ public void toBack()
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void toFront()
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public void updateAlwaysOnTop()
+ {
+ // TODO Auto-generated method stub
+
+ }
+
+ public boolean requestWindowFocus()
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ public Point getLocationOnScreen()
+ {
+ return new Point(xwindow.x, xwindow.y);
+ }
+
+ /**
+ * Returns a XGraphics suitable for drawing on this frame.
+ *
+ * @return a XGraphics suitable for drawing on this frame
+ */
+ public Graphics getGraphics()
+ {
+ return new XGraphics(xwindow);
+ }
+
+ public Image createImage(int w, int h)
+ {
+ return new XImage(w, h);
+ }
+
+ /**
+ * Makes the component visible. This is called by {@link Component#show()}.
+ *
+ * This is implemented to call setVisible(true) on the Swing component.
+ */
+ public void show()
+ {
+// // Prevent ResizeRedirect events.
+// //xwindow.select_input(noResizeRedirectSelect);
+// Window.Attributes atts = new Window.Attributes();
+// atts.set_override_redirect(true);
+// xwindow.change_attributes(atts);
+
+ // Prevent ResizeRedirect events.
+ //xwindow.select_input(Event.NO_EVENT_MASK);
+ //xwindow.select_input(noResizeRedirectSelect);
+
+ xwindow.map();
+ EventQueue eq = XToolkit.getDefaultToolkit().getSystemEventQueue();
+ java.awt.Window w = (java.awt.Window) super.awtComponent;
+ eq.postEvent(new WindowEvent(w, WindowEvent.WINDOW_OPENED));
+ eq.postEvent(new PaintEvent(w, PaintEvent.PAINT,
+ new Rectangle(0, 0, w.getWidth(),
+ w.getHeight())));
+
+// // Reset input selection.
+// atts.set_override_redirect(false);
+// xwindow.change_attributes(atts);
+ }
+
+ /**
+ * Makes the component invisible. This is called from
+ * {@link Component#hide()}.
+ *
+ * This is implemented to call setVisible(false) on the Swing component.
+ */
+ public void hide()
+ {
+ xwindow.unmap();
+ }
+
+ /**
+ * Notifies the peer that the bounds of this component have changed. This
+ * is called by {@link Component#reshape(int, int, int, int)}.
+ *
+ * This is implemented to call setBounds() on the Swing component.
+ *
+ * @param x the X coordinate of the upper left corner of the component
+ * @param y the Y coordinate of the upper left corner of the component
+ * @param width the width of the component
+ * @param height the height of the component
+ */
+ public void reshape(int x, int y, int width, int height)
+ {
+ // Prevent ResizeRedirect events.
+// //xwindow.select_input(noResizeRedirectSelect);
+// Window.Attributes atts = new Window.Attributes();
+// atts.set_override_redirect(true);
+// xwindow.change_attributes(atts);
+
+ // Need to substract insets because AWT size is including insets,
+ // and X size is excuding insets.
+ Insets i = insets();
+ xwindow.move_resize(x - i.left, y - i.right, width - i.left - i.right,
+ height - i.top - i.bottom);
+
+ // Reset input selection.
+// atts = new Window.Attributes();
+// atts.set_override_redirect(false);
+// xwindow.change_attributes(atts);
+ }
+
+ public Insets insets()
+ {
+ Insets i = new Insets(0, 0, 0, 0);
+// Window.GeometryReply g = xwindow.geometry();
+// int b = g.border_width();
+// Insets i = new Insets(b, b, b, b);
+// Window.WMSizeHints wmSize = xwindow.wm_normal_hints();
+// if (wmSize != null)
+// {
+// i.left = wmSize.x() - g.x();
+// i.right = wmSize.width() - g.width() - i.left ;
+// i.top = wmSize.y() - g.y();
+// i.bottom = wmSize.height() - g.height() - i.top;
+// }
+// System.err.println("insets: " + i);
+ return i;
+ }
+
+ /**
+ * Returns the font metrics for the specified font.
+ *
+ * @return the font metrics for the specified font
+ */
+ public FontMetrics getFontMetrics(Font font)
+ {
+ XFontPeer fontPeer = (XFontPeer) font.getPeer();
+ return fontPeer.getFontMetrics(font);
+ }
+
+ /**
+ * Unregisters the window in the event pump when it is closed.
+ */
+ protected void finalize()
+ {
+ XGraphicsDevice dev = XToolkit.getDefaultDevice();
+ dev.getEventPump().unregisterWindow(xwindow);
+ }
+}
diff --git a/libjava/classpath/gnu/java/awt/print/PostScriptGraphics2D.java b/libjava/classpath/gnu/java/awt/print/PostScriptGraphics2D.java
index 2303f44..e4cc819 100644
--- a/libjava/classpath/gnu/java/awt/print/PostScriptGraphics2D.java
+++ b/libjava/classpath/gnu/java/awt/print/PostScriptGraphics2D.java
@@ -668,7 +668,7 @@ class PostScriptGraphics2D extends Graphics2D
saveAndInvertAxis();
// draw the shape s with an inverted Y axis.
- PathIterator pi = s.getPathIterator(new AffineTransform());
+ PathIterator pi = s.getPathIterator(null);
float[] coords = new float[6];
while (! pi.isDone())
@@ -872,7 +872,7 @@ class PostScriptGraphics2D extends Graphics2D
/** write a shape to the file */
private void writeShape(Shape s)
{
- PathIterator pi = s.getPathIterator(new AffineTransform());
+ PathIterator pi = s.getPathIterator(null);
float[] coords = new float[6];
while (! pi.isDone())
diff --git a/libjava/classpath/gnu/java/io/PlatformHelper.java b/libjava/classpath/gnu/java/io/PlatformHelper.java
index 79ce6e8..e54c56d 100644
--- a/libjava/classpath/gnu/java/io/PlatformHelper.java
+++ b/libjava/classpath/gnu/java/io/PlatformHelper.java
@@ -1,5 +1,5 @@
/* PlatformHelper.java -- Isolate OS-specific IO helper methods and variables
- Copyright (C) 1998, 2002 Free Software Foundation, Inc.
+ Copyright (C) 1998, 2002, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -97,98 +97,6 @@ public class PlatformHelper
}
/**
- * This routine canonicalizes input param "path" to formal path representation
- * for current platform, including interpreting ".." and "." .
- */
- public static final String toCanonicalForm(String path)
- {
- /*??
- if(path.indexOf('.') < 0 && path.indexOf("..") < 0)
- return path;
- */
- String tmppath = path.replace('/', separatorChar);
- StringBuffer canonpath;
-
- int i;
-
- if ((i = beginWithRootPathPrefix(tmppath)) == 0 )
- return path;
-
- /* The original
- "canonpath = new StringBuffer(tmppath.substring(0, i))"
- isn't very efficient because StringBuffer's
- ensureCapacity_unsynchronized will fail definitely each time
- and will enlarge buffer and copy contents. .
- */
- canonpath = new StringBuffer(INITIAL_MAX_PATH);
- canonpath.append(tmppath.substring(0, i));
- tmppath = tmppath.substring(i);
- // pathdepth==0 indicates there're only root path in the buffer
- int pathdepth = 0;
-
- StringTokenizer st = new StringTokenizer(tmppath, separator);
-
- // Traverse each element of the path, handling "." and ".."
- // Should handle "~" too?
- if (st.hasMoreTokens())
- do
- {
- String s = st.nextToken();
-
- // Handle "." or an empty element.
- if (s.equals(".") || s.equals(""))
- continue;
-
- // Handle ".." by deleting the last element from the path
- if (s.equals(".."))
- {
- if (pathdepth == 0)
- continue;
-
- // Strip of trailing separator
- canonpath.setLength(canonpath.length() - 1/*separator.length()*/);
- String tmpstr = canonpath.toString();
- int idx = tmpstr.lastIndexOf(separator);
-
- if ((idx == -1) || ((idx + 1/*separator.length()*/) > tmpstr.length()))
- //throw new IOException("Can't happen error");
- return path; // Shouldn't happen
-
- canonpath.setLength(idx + 1/*separator.length()*/);
- pathdepth--;
- continue;
- }
-
- canonpath.append(s);
- pathdepth++; //now it's more than root path
-
- if (st.hasMoreTokens())
- canonpath.append(separator);
- }
- while (st.hasMoreTokens());
-
- if (endWithSeparator(path))
- canonpath.append(separator);
-
- String tmpstr = canonpath.toString();
- //if (pathdepth > 0 && endWithSeparator(tmpstr) )
- // tmpstr = tmpstr.substring(0, tmpstr.length() - 1/*separator.length()*/);
-
- return tmpstr;
- }
-
- /**
- * This routine canonicalizes input param "path" to formal path representation
- * for current platform, and normalize all separators to "sepchar".
- */
- public static final String toCanonicalForm(String path, char sepchar)
- {
- String tmpstr = toCanonicalForm(path);
- tmpstr = tmpstr.replace(separatorChar, sepchar);
- return tmpstr;
- }
-
- /**
* This routine checks whether input param "path" ends with separator
*/
public static final boolean endWithSeparator(String path)
diff --git a/libjava/classpath/gnu/java/lang/management/BeanImpl.java b/libjava/classpath/gnu/java/lang/management/BeanImpl.java
new file mode 100644
index 0000000..24572a2
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/BeanImpl.java
@@ -0,0 +1,84 @@
+/* BeanImpl.java - A common superclass for bean implementations.
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import java.lang.management.ManagementPermission;
+
+import javax.management.NotCompliantMBeanException;
+import javax.management.StandardMBean;
+
+/**
+ * A common superclass for bean implementations.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public class BeanImpl
+ extends StandardMBean
+{
+
+ /**
+ * Constructs a new BeanImpl
.
+ *
+ * @param iface the bean interface being implemented.
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ protected BeanImpl(Class iface)
+ throws NotCompliantMBeanException
+ {
+ super(iface);
+ }
+
+ protected void checkMonitorPermissions()
+ {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPermission(new ManagementPermission("monitor"));
+ }
+
+ protected void checkControlPermissions()
+ {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPermission(new ManagementPermission("control"));
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/lang/management/ClassLoadingMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/ClassLoadingMXBeanImpl.java
new file mode 100644
index 0000000..92e68ae
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/ClassLoadingMXBeanImpl.java
@@ -0,0 +1,99 @@
+/* ClassLoadingMXBeanImpl.java - Implementation of a class loading bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import java.lang.management.ClassLoadingMXBean;
+
+import javax.management.NotCompliantMBeanException;
+
+/**
+ * Provides access to information about the class loading
+ * behaviour of the current invocation of the virtual
+ * machine. Instances of this bean are obtained by calling
+ * {@link ManagementFactory#getClassLoadingMXBean()}.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public final class ClassLoadingMXBeanImpl
+ extends BeanImpl
+ implements ClassLoadingMXBean
+{
+
+ /**
+ * Constructs a new ClassLoadingMXBeanImpl
.
+ *
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public ClassLoadingMXBeanImpl()
+ throws NotCompliantMBeanException
+ {
+ super(ClassLoadingMXBean.class);
+ }
+
+ public int getLoadedClassCount()
+ {
+ return VMClassLoadingMXBeanImpl.getLoadedClassCount();
+ }
+
+ public long getTotalLoadedClassCount()
+ {
+ return getLoadedClassCount() + getUnloadedClassCount();
+ }
+
+ public long getUnloadedClassCount()
+ {
+ return VMClassLoadingMXBeanImpl.getUnloadedClassCount();
+ }
+
+ public boolean isVerbose()
+ {
+ return VMClassLoadingMXBeanImpl.isVerbose();
+ }
+
+ public void setVerbose(boolean verbose)
+ {
+ checkControlPermissions();
+ VMClassLoadingMXBeanImpl.setVerbose(verbose);
+ }
+
+}
+
diff --git a/libjava/classpath/gnu/java/lang/management/CompilationMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/CompilationMXBeanImpl.java
new file mode 100644
index 0000000..b3ad898
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/CompilationMXBeanImpl.java
@@ -0,0 +1,105 @@
+/* CompilationMXBeanImpl.java - Implementation of a compilation bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import gnu.classpath.SystemProperties;
+
+import java.lang.management.CompilationMXBean;
+
+import javax.management.NotCompliantMBeanException;
+
+/**
+ * Provides access to information about the JIT
+ * compiler of the virtual machine, if one exists.
+ * Instances of this bean are obtained by calling
+ * {@link ManagementFactory#getCompilationMXBean()},
+ * if this is the case.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public final class CompilationMXBeanImpl
+ extends BeanImpl
+ implements CompilationMXBean
+{
+
+ /**
+ * Constant for compiler name.
+ */
+ private static final String COMPILER_NAME = "gnu.java.compiler.name";
+
+ /**
+ * Constant for compilation time support.
+ */
+ private static final String COMPILATION_TIME_SUPPORT =
+ "gnu.java.lang.management.CompilationTimeSupport";
+
+ /**
+ * Constructs a new CompilationMXBeanImpl
.
+ *
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public CompilationMXBeanImpl()
+ throws NotCompliantMBeanException
+ {
+ super(CompilationMXBean.class);
+ }
+
+ public String getName()
+ {
+ return SystemProperties.getProperty(COMPILER_NAME);
+ }
+
+ public boolean isCompilationTimeMonitoringSupported()
+ {
+ return SystemProperties.getProperty(COMPILATION_TIME_SUPPORT) != null;
+ }
+
+ public long getTotalCompilationTime()
+ {
+ if (isCompilationTimeMonitoringSupported())
+ return VMCompilationMXBeanImpl.getTotalCompilationTime();
+ else
+ throw new UnsupportedOperationException("Compilation time monitoring "
+ + "is not supported");
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/lang/management/GarbageCollectorMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/GarbageCollectorMXBeanImpl.java
new file mode 100644
index 0000000..b752e6b
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/GarbageCollectorMXBeanImpl.java
@@ -0,0 +1,84 @@
+/* GarbageCollectorMXBeanImpl.java - Implementation of a GC bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import java.lang.management.GarbageCollectorMXBean;
+
+import javax.management.NotCompliantMBeanException;
+
+/**
+ * Provides access to information about one of the garbage
+ * collectors used by the current invocation of the
+ * virtual machine. An instance of this bean for each garbage
+ * collector is obtained by calling
+ * {@link ManagementFactory#getGarbageCollectorMXBeans()}.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public final class GarbageCollectorMXBeanImpl
+ extends MemoryManagerMXBeanImpl
+ implements GarbageCollectorMXBean
+{
+
+ /**
+ * Constructs a new GarbageCollectorMXBeanImpl
.
+ *
+ * @param name the name of the garbage collector this bean represents.
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public GarbageCollectorMXBeanImpl(String name)
+ throws NotCompliantMBeanException
+ {
+ super(name, GarbageCollectorMXBean.class);
+ }
+
+ public long getCollectionCount()
+ {
+ return VMGarbageCollectorMXBeanImpl.getCollectionCount(name);
+ }
+
+ public long getCollectionTime()
+ {
+ return VMGarbageCollectorMXBeanImpl.getCollectionTime(name);
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/lang/management/MemoryMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/MemoryMXBeanImpl.java
new file mode 100644
index 0000000..064e19a
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/MemoryMXBeanImpl.java
@@ -0,0 +1,322 @@
+/* MemoryMXBeanImpl.java - Implementation of a memory bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import java.lang.management.MemoryMXBean;
+import java.lang.management.MemoryNotificationInfo;
+import java.lang.management.MemoryUsage;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.management.ListenerNotFoundException;
+import javax.management.MBeanNotificationInfo;
+import javax.management.NotCompliantMBeanException;
+import javax.management.Notification;
+import javax.management.NotificationEmitter;
+import javax.management.NotificationFilter;
+import javax.management.NotificationListener;
+
+import javax.management.openmbean.CompositeData;
+import javax.management.openmbean.CompositeDataSupport;
+import javax.management.openmbean.CompositeType;
+import javax.management.openmbean.OpenDataException;
+import javax.management.openmbean.OpenType;
+import javax.management.openmbean.SimpleType;
+
+/**
+ * Provides access to information about the memory
+ * management of the current invocation of the virtual
+ * machine. Instances of this bean are obtained by calling
+ * {@link ManagementFactory#getMemoryMXBean()}.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public final class MemoryMXBeanImpl
+ extends BeanImpl
+ implements MemoryMXBean, NotificationEmitter
+{
+
+ private List listeners;
+
+ private long notificationCount;
+
+ public static CompositeType notifType;
+
+ public static CompositeType usageType;
+
+ static
+ {
+ try
+ {
+ CompositeType usageType =
+ new CompositeType(MemoryUsage.class.getName(),
+ "Describes the usage levels of a pool",
+ new String[] { "init", "used",
+ "committed", "max"
+ },
+ new String[] { "Initial level",
+ "Used level",
+ "Committed level",
+ "Maximum level"
+ },
+ new OpenType[] {
+ SimpleType.LONG, SimpleType.LONG,
+ SimpleType.LONG, SimpleType.LONG
+ });
+ CompositeType notifType =
+ new CompositeType(MemoryNotificationInfo.class.getName(),
+ "Provides the notification info on memory usage",
+ new String[] { "poolName", "usage", "count" },
+ new String[] { "Name of the memory pool",
+ "Usage level of the memory pool",
+ "Number of times the threshold " +
+ "has been crossed"
+ },
+ new OpenType[] {
+ SimpleType.STRING, usageType, SimpleType.LONG
+ });
+ }
+ catch (OpenDataException e)
+ {
+ throw new IllegalStateException("Something went wrong in creating " +
+ "the composite data types.", e);
+ }
+ }
+
+ /**
+ * Constructs a new MemoryMXBeanImpl
.
+ *
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public MemoryMXBeanImpl()
+ throws NotCompliantMBeanException
+ {
+ super(MemoryMXBean.class);
+ listeners = new ArrayList();
+ notificationCount = 0;
+ }
+
+ public void gc()
+ {
+ System.gc();
+ }
+
+ public MemoryUsage getHeapMemoryUsage()
+ {
+ return VMMemoryMXBeanImpl.getHeapMemoryUsage();
+ }
+
+ public MemoryUsage getNonHeapMemoryUsage()
+ {
+ return VMMemoryMXBeanImpl.getNonHeapMemoryUsage();
+ }
+
+ public int getObjectPendingFinalizationCount()
+ {
+ return VMMemoryMXBeanImpl.getObjectPendingFinalizationCount();
+ }
+
+ public boolean isVerbose()
+ {
+ return VMMemoryMXBeanImpl.isVerbose();
+ }
+
+ public void setVerbose(boolean verbose)
+ {
+ checkControlPermissions();
+ VMMemoryMXBeanImpl.setVerbose(verbose);
+ }
+
+ private class ListenerData
+ {
+ private NotificationListener listener;
+ private NotificationFilter filter;
+ private Object passback;
+
+ public ListenerData(NotificationListener listener,
+ NotificationFilter filter, Object passback)
+ {
+ this.listener = listener;
+ this.filter = filter;
+ this.passback = passback;
+ }
+
+ public NotificationListener getListener()
+ {
+ return listener;
+ }
+
+ public NotificationFilter getFilter()
+ {
+ return filter;
+ }
+
+ public Object getPassback()
+ {
+ return passback;
+ }
+
+ public boolean equals(Object obj)
+ {
+ if (obj instanceof ListenerData)
+ {
+ ListenerData data = (ListenerData) obj;
+ return (data.getListener() == listener &&
+ data.getFilter() == filter &&
+ data.getPassback() == passback);
+ }
+ return false;
+ }
+
+ }
+
+ public void addNotificationListener(NotificationListener listener,
+ NotificationFilter filter,
+ Object passback)
+ {
+ if (listener == null)
+ throw new IllegalArgumentException("Null listener added to bean.");
+ listeners.add(new ListenerData(listener, filter, passback));
+ }
+
+ public MBeanNotificationInfo[] getNotificationInfo()
+ {
+ return new MBeanNotificationInfo[]
+ {
+ new MBeanNotificationInfo(new String[]
+ {
+ MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED,
+ MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED
+ },
+ Notification.class.getName(),
+ "Memory Usage Notifications")
+ };
+ }
+
+ public void removeNotificationListener(NotificationListener listener)
+ throws ListenerNotFoundException
+ {
+ Iterator it = listeners.iterator();
+ boolean foundOne = false;
+ while (it.hasNext())
+ {
+ ListenerData data = (ListenerData) it.next();
+ if (data.getListener() == listener)
+ {
+ it.remove();
+ foundOne = true;
+ }
+ }
+ if (!foundOne)
+ throw new ListenerNotFoundException("The specified listener, " + listener +
+ "is not registered with this bean.");
+ }
+
+ public void removeNotificationListener(NotificationListener listener,
+ NotificationFilter filter,
+ Object passback)
+ throws ListenerNotFoundException
+ {
+ if (!(listeners.remove(new ListenerData(listener, filter, passback))))
+ {
+ throw new ListenerNotFoundException("The specified listener, " + listener +
+ " with filter " + filter +
+ "and passback " + passback +
+ ", is not registered with this bean.");
+ }
+ }
+
+ void fireNotification(String type, String poolName, long init, long used,
+ long committed, long max, long count)
+ {
+ Notification notif = new Notification(type, this, notificationCount);
+ MemoryUsage usage = new MemoryUsage(init, used, committed, max);
+ CompositeData data;
+ try
+ {
+ data = new CompositeDataSupport(notifType,
+ new String[] {
+ "poolName", "usage", "count"
+ },
+ new Object[] {
+ poolName, usage, Long.valueOf(count)
+ });
+ }
+ catch (OpenDataException e)
+ {
+ throw new IllegalStateException("Something went wrong in creating " +
+ "the composite data instance.", e);
+ }
+ notif.setUserData(data);
+ Iterator it = listeners.iterator();
+ while (it.hasNext())
+ {
+ ListenerData ldata = (ListenerData) it.next();
+ NotificationFilter filter = ldata.getFilter();
+ if (filter == null || filter.isNotificationEnabled(notif))
+ ldata.getListener().handleNotification(notif, ldata.getPassback());
+ }
+ ++notificationCount;
+ }
+
+ void fireThresholdExceededNotification(String poolName, long init,
+ long used, long committed,
+ long max, long count)
+ {
+ fireNotification(MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED,
+ poolName, init, used, committed, max, count);
+ }
+
+ void fireCollectionThresholdExceededNotification(String poolName,
+ long init,
+ long used,
+ long committed,
+ long max,
+ long count)
+ {
+ fireNotification(MemoryNotificationInfo.MEMORY_COLLECTION_THRESHOLD_EXCEEDED,
+ poolName, init, used, committed, max, count);
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/lang/management/MemoryManagerMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/MemoryManagerMXBeanImpl.java
new file mode 100644
index 0000000..5766af9
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/MemoryManagerMXBeanImpl.java
@@ -0,0 +1,112 @@
+/* MemoryManagerMXBeanImpl.java - Implementation of a memory manager bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import java.lang.management.MemoryManagerMXBean;
+
+import javax.management.NotCompliantMBeanException;
+
+/**
+ * Provides access to information about one of the memory
+ * managers used by the current invocation of the
+ * virtual machine. An instance of this bean for each memory
+ * manager is obtained by calling
+ * {@link ManagementFactory#getMemoryPoolMXBeans()}.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public class MemoryManagerMXBeanImpl
+ extends BeanImpl
+ implements MemoryManagerMXBean
+{
+
+ /**
+ * The name of the memory manager.
+ */
+ protected String name;
+
+ /**
+ * Constructs a new MemoryManagerMXBeanImpl
.
+ *
+ * @param name the name of the manager this bean represents.
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public MemoryManagerMXBeanImpl(String name)
+ throws NotCompliantMBeanException
+ {
+ this(name, MemoryManagerMXBean.class);
+ }
+
+ /**
+ * Constructs a new MemoryManagerMXBeanImpl
+ * implementing the specified bean interface.
+ *
+ * @param name the name of the manager this bean represents.
+ * @param iface the bean interface being implemented.
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ protected MemoryManagerMXBeanImpl(String name, Class iface)
+ throws NotCompliantMBeanException
+ {
+ super(iface);
+ this.name = name;
+ }
+
+ public String[] getMemoryPoolNames()
+ {
+ return VMMemoryManagerMXBeanImpl.getMemoryPoolNames(name);
+ }
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public boolean isValid()
+ {
+ return VMMemoryManagerMXBeanImpl.isValid(name);
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/lang/management/MemoryPoolMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/MemoryPoolMXBeanImpl.java
new file mode 100644
index 0000000..ed4dccd
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/MemoryPoolMXBeanImpl.java
@@ -0,0 +1,225 @@
+/* MemoryPoolMXBeanImpl.java - Implementation of a memory pool bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import gnu.classpath.SystemProperties;
+
+import java.lang.management.MemoryPoolMXBean;
+import java.lang.management.MemoryUsage;
+
+import javax.management.NotCompliantMBeanException;
+
+/**
+ * Provides access to information about one of the memory
+ * resources or pools used by the current invocation of the
+ * virtual machine. An instance of this bean for each memory
+ * pool is obtained by calling
+ * {@link ManagementFactory#getMemoryPoolMXBeans()}.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public final class MemoryPoolMXBeanImpl
+ extends BeanImpl
+ implements MemoryPoolMXBean
+{
+
+ /**
+ * The name of the pool.
+ */
+ private String name;
+
+ /**
+ * Constant for collection usage threshold.
+ */
+ private static final String COLLECTION_USAGE_THRESHOLD =
+ "gnu.java.lang.management.CollectionUsageThresholdSupport";
+
+ /**
+ * Constant for thread time support.
+ */
+ private static final String USAGE_THRESHOLD =
+ "gnu.java.lang.management.UsageThresholdSupport";
+
+ /**
+ * Constructs a new MemoryPoolMXBeanImpl
.
+ *
+ * @param name the name of the pool this bean represents.
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public MemoryPoolMXBeanImpl(String name)
+ throws NotCompliantMBeanException
+ {
+ super(MemoryPoolMXBean.class);
+ this.name = name;
+ }
+
+ public MemoryUsage getCollectionUsage()
+ {
+ return VMMemoryPoolMXBeanImpl.getCollectionUsage(name);
+ }
+
+ public long getCollectionUsageThreshold()
+ {
+ if (isCollectionUsageThresholdSupported())
+ return VMMemoryPoolMXBeanImpl.getCollectionUsageThreshold(name);
+ else
+ throw new UnsupportedOperationException("A collection usage "+
+ "threshold is not supported.");
+ }
+
+ public long getCollectionUsageThresholdCount()
+ {
+ if (isCollectionUsageThresholdSupported())
+ return VMMemoryPoolMXBeanImpl.getCollectionUsageThresholdCount(name);
+ else
+ throw new UnsupportedOperationException("A collection usage "+
+ "threshold is not supported.");
+ }
+
+ public String[] getMemoryManagerNames()
+ {
+ return VMMemoryPoolMXBeanImpl.getMemoryManagerNames(name);
+ }
+
+ public String getName()
+ {
+ return name;
+ }
+
+ public MemoryUsage getPeakUsage()
+ {
+ if (isValid())
+ return VMMemoryPoolMXBeanImpl.getPeakUsage(name);
+ else
+ return null;
+ }
+
+ public String getType()
+ {
+ return VMMemoryPoolMXBeanImpl.getType(name);
+ }
+
+ public MemoryUsage getUsage()
+ {
+ if (isValid())
+ return VMMemoryPoolMXBeanImpl.getUsage(name);
+ else
+ return null;
+ }
+
+ public long getUsageThreshold()
+ {
+ if (isUsageThresholdSupported())
+ return VMMemoryPoolMXBeanImpl.getUsageThreshold(name);
+ else
+ throw new UnsupportedOperationException("A usage threshold " +
+ "is not supported.");
+ }
+
+ public long getUsageThresholdCount()
+ {
+ if (isUsageThresholdSupported())
+ return VMMemoryPoolMXBeanImpl.getUsageThresholdCount(name);
+ else
+ throw new UnsupportedOperationException("A usage threshold " +
+ "is not supported.");
+ }
+
+ public boolean isCollectionUsageThresholdExceeded()
+ {
+ return getCollectionUsage().getUsed() >= getCollectionUsageThreshold();
+ }
+
+ public boolean isCollectionUsageThresholdSupported()
+ {
+ return SystemProperties.getProperty(COLLECTION_USAGE_THRESHOLD) != null;
+ }
+
+ public boolean isUsageThresholdExceeded()
+ {
+ return getUsage().getUsed() >= getUsageThreshold();
+ }
+
+ public boolean isUsageThresholdSupported()
+ {
+ return SystemProperties.getProperty(USAGE_THRESHOLD) != null;
+ }
+
+ public boolean isValid()
+ {
+ return VMMemoryPoolMXBeanImpl.isValid(name);
+ }
+
+ public void resetPeakUsage()
+ {
+ checkControlPermissions();
+ VMMemoryPoolMXBeanImpl.resetPeakUsage(name);
+ }
+
+ public void setCollectionUsageThreshold(long threshold)
+ {
+ checkControlPermissions();
+ if (threshold < 0)
+ throw new IllegalArgumentException("Threshold of " + threshold +
+ "is less than zero.");
+ if (isCollectionUsageThresholdSupported())
+ VMMemoryPoolMXBeanImpl.setCollectionUsageThreshold(name, threshold);
+ else
+ throw new UnsupportedOperationException("A collection usage "+
+ "threshold is not supported.");
+ }
+
+ public void setUsageThreshold(long threshold)
+ {
+ checkControlPermissions();
+ if (threshold < 0)
+ throw new IllegalArgumentException("Threshold of " + threshold +
+ "is less than zero.");
+ if (isUsageThresholdSupported())
+ VMMemoryPoolMXBeanImpl.setUsageThreshold(name, threshold);
+ else
+ throw new UnsupportedOperationException("A usage threshold " +
+ "is not supported.");
+ }
+
+}
+
diff --git a/libjava/classpath/gnu/java/lang/management/OperatingSystemMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/OperatingSystemMXBeanImpl.java
new file mode 100644
index 0000000..9eefc0d
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/OperatingSystemMXBeanImpl.java
@@ -0,0 +1,90 @@
+/* OperatingSystemMXBeanImpl.java - Implementation of an operating system bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import java.lang.management.OperatingSystemMXBean;
+
+import javax.management.NotCompliantMBeanException;
+
+/**
+ * Provides access to information about the underlying operating
+ * system.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public final class OperatingSystemMXBeanImpl
+ extends BeanImpl
+ implements OperatingSystemMXBean
+{
+
+ /**
+ * Constructs a new OperatingSystemMXBeanImpl
.
+ *
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public OperatingSystemMXBeanImpl()
+ throws NotCompliantMBeanException
+ {
+ super(OperatingSystemMXBean.class);
+ }
+
+ public String getArch()
+ {
+ return System.getProperty("os.arch");
+ }
+
+ public int getAvailableProcessors()
+ {
+ return Runtime.getRuntime().availableProcessors();
+ }
+
+ public String getName()
+ {
+ return System.getProperty("os.name");
+ }
+
+ public String getVersion()
+ {
+ return System.getProperty("os.version");
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/lang/management/RuntimeMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/RuntimeMXBeanImpl.java
new file mode 100644
index 0000000..e3ebd16
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/RuntimeMXBeanImpl.java
@@ -0,0 +1,197 @@
+/* RuntimeMXBeanImpl.java - Implementation of an runtime bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import gnu.classpath.SystemProperties;
+
+import java.lang.management.RuntimeMXBean;
+
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.management.NotCompliantMBeanException;
+
+/**
+ * Provides access to information about the virtual machine.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public final class RuntimeMXBeanImpl
+ extends BeanImpl
+ implements RuntimeMXBean
+{
+
+ private static final String SUN_BOOT_CLASS_PATH = "sun.boot.class.path";
+ private static final String JAVA_BOOT_CLASS_PATH = "java.boot.class.path";
+
+ private long startTime = -1;
+
+ private String bootClassPath = null;
+
+ private boolean bootClassPathSupported = true;
+
+ /**
+ * Constructs a new RuntimeMXBeanImpl
.
+ *
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public RuntimeMXBeanImpl()
+ throws NotCompliantMBeanException
+ {
+ super(RuntimeMXBean.class);
+ }
+
+ public String getBootClassPath()
+ {
+ checkMonitorPermissions();
+ if (isBootClassPathSupported())
+ return bootClassPath;
+ else
+ throw
+ new UnsupportedOperationException("Retrieving the boot " +
+ "classpath is not supported.");
+ }
+
+ public String getClassPath()
+ {
+ return System.getProperty("java.class.path");
+ }
+
+ public List getInputArguments()
+ {
+ checkMonitorPermissions();
+ return Arrays.asList(VMRuntimeMXBeanImpl.getInputArguments());
+ }
+
+ public String getLibraryPath()
+ {
+ return System.getProperty("java.library.path");
+ }
+
+ public String getManagementSpecVersion()
+ {
+ return "1.0";
+ }
+
+ public String getName()
+ {
+ return VMRuntimeMXBeanImpl.getName();
+ }
+
+ public String getSpecName()
+ {
+ return System.getProperty("java.vm.specification.name");
+ }
+
+ public String getSpecVendor()
+ {
+ return System.getProperty("java.vm.specification.vendor");
+ }
+
+ public String getSpecVersion()
+ {
+ return System.getProperty("java.vm.specification.version");
+ }
+
+ public long getStartTime()
+ {
+ if (startTime == -1)
+ startTime = VMRuntimeMXBeanImpl.getStartTime();
+ return startTime;
+ }
+
+ public Map getSystemProperties()
+ {
+ Map map = new HashMap();
+ Properties props = System.getProperties();
+ Iterator entries = props.entrySet().iterator();
+ while (entries.hasNext())
+ {
+ Map.Entry next = (Map.Entry) entries.next();
+ Object key = next.getKey();
+ Object value = next.getValue();
+ if (key instanceof String &&
+ value instanceof String)
+ map.put(key, value);
+ }
+ return map;
+ }
+
+ public long getUptime()
+ {
+ return new Date().getTime() - getStartTime();
+ }
+
+ public String getVmName()
+ {
+ return System.getProperty("java.vm.name");
+ }
+
+ public String getVmVendor()
+ {
+ return System.getProperty("java.vm.vendor");
+ }
+
+ public String getVmVersion()
+ {
+ return System.getProperty("java.vm.version");
+ }
+
+ public boolean isBootClassPathSupported()
+ {
+ if (bootClassPath == null)
+ {
+ bootClassPath = SystemProperties.getProperty(JAVA_BOOT_CLASS_PATH);
+ if (bootClassPath == null)
+ bootClassPath = SystemProperties.getProperty(SUN_BOOT_CLASS_PATH);
+ if (bootClassPath == null)
+ bootClassPathSupported = false;
+ }
+ return bootClassPathSupported;
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/lang/management/ThreadMXBeanImpl.java b/libjava/classpath/gnu/java/lang/management/ThreadMXBeanImpl.java
new file mode 100644
index 0000000..609b58d
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/ThreadMXBeanImpl.java
@@ -0,0 +1,291 @@
+/* ThreadMXBeanImpl.java - Implementation of a thread bean
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.lang.management;
+
+import gnu.classpath.SystemProperties;
+
+import java.lang.management.ThreadInfo;
+import java.lang.management.ThreadMXBean;
+
+import javax.management.NotCompliantMBeanException;
+
+/**
+ * Provides access to information about the threads
+ * of the virtual machine. An instance of this bean is
+ * obtained by calling
+ * {@link ManagementFactory#getThreadMXBean()}.
+ * See {@link java.lang.management.ThreadMXBean} for
+ * full documentation.
+ *
+ * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
+ * @since 1.5
+ */
+public final class ThreadMXBeanImpl
+ extends BeanImpl
+ implements ThreadMXBean
+{
+
+ /**
+ * Constant for current thread time support.
+ */
+ private static final String CURRENT_THREAD_TIME_SUPPORT =
+ "gnu.java.lang.management.CurrentThreadTimeSupport";
+
+ /**
+ * Constant for thread time support.
+ */
+ private static final String THREAD_TIME_SUPPORT =
+ "gnu.java.lang.management.ThreadTimeSupport";
+
+ /**
+ * Constant for thread contention support.
+ */
+ private static final String CONTENTION_SUPPORT =
+ "gnu.java.lang.management.ThreadContentionSupport";
+
+ /**
+ * Constant for initial value of thread time support.
+ */
+ private static final String TIME_ENABLED =
+ "gnu.java.lang.management.ThreadTimeInitallyEnabled";
+
+ /**
+ * Flag to indicate whether time monitoring is enabled or not.
+ */
+ private boolean timeEnabled;
+
+ /**
+ * Flag to indicate whether contention monitoring is enabled or not.
+ */
+ private boolean contentionEnabled;
+
+ /**
+ * Default constructor to set up flag states. The
+ * VM has to specify whether time monitoring is initially
+ * enabled or not.
+ *
+ * @throws NotCompliantMBeanException if this class doesn't implement
+ * the interface or a method appears
+ * in the interface that doesn't comply
+ * with the naming conventions.
+ */
+ public ThreadMXBeanImpl()
+ throws NotCompliantMBeanException
+ {
+ super(ThreadMXBean.class);
+ timeEnabled = Boolean.parseBoolean(SystemProperties.getProperty(TIME_ENABLED));
+ contentionEnabled = false;
+ }
+
+ public long[] findMonitorDeadlockedThreads()
+ {
+ checkMonitorPermissions();
+ return VMThreadMXBeanImpl.findMonitorDeadlockedThreads();
+ }
+
+ public long[] getAllThreadIds()
+ {
+ checkMonitorPermissions();
+ return VMThreadMXBeanImpl.getAllThreadIds();
+ }
+
+ public long getCurrentThreadCpuTime()
+ {
+ if (!isCurrentThreadCpuTimeSupported())
+ throw new UnsupportedOperationException("Current thread CPU " +
+ "time not supported.");
+ if (!timeEnabled)
+ return -1;
+ return VMThreadMXBeanImpl.getCurrentThreadCpuTime();
+ }
+
+ public long getCurrentThreadUserTime()
+ {
+ if (!isCurrentThreadCpuTimeSupported())
+ throw new UnsupportedOperationException("Current thread user " +
+ "time not supported.");
+ if (!timeEnabled)
+ return -1;
+ return VMThreadMXBeanImpl.getCurrentThreadUserTime();
+ }
+
+ public int getDaemonThreadCount()
+ {
+ return VMThreadMXBeanImpl.getDaemonThreadCount();
+ }
+
+ public int getPeakThreadCount()
+ {
+ return VMThreadMXBeanImpl.getPeakThreadCount();
+ }
+
+ public int getThreadCount()
+ {
+ return VMThreadMXBeanImpl.getThreadCount();
+ }
+
+ public long getThreadCpuTime(long id)
+ {
+ if (!isThreadCpuTimeSupported())
+ throw new UnsupportedOperationException("Thread CPU time not " +
+ "supported.");
+ if (id <= 0)
+ throw new IllegalArgumentException("Invalid thread id: " + id);
+ if (!timeEnabled)
+ return -1;
+ return VMThreadMXBeanImpl.getThreadCpuTime(id);
+ }
+
+ public ThreadInfo getThreadInfo(long id)
+ {
+ return getThreadInfo(id, 0);
+ }
+
+ public ThreadInfo[] getThreadInfo(long[] ids)
+ {
+ return getThreadInfo(ids, 0);
+ }
+
+ public ThreadInfo getThreadInfo(long id, int maxDepth)
+ {
+ checkMonitorPermissions();
+ if (id <= 0)
+ throw new IllegalArgumentException("Invalid thread id: " + id);
+ if (maxDepth < 0)
+ throw new IllegalArgumentException("Invalid depth: " + maxDepth);
+ return VMThreadMXBeanImpl.getThreadInfoForId(id, maxDepth);
+ }
+
+ public ThreadInfo[] getThreadInfo(long[] ids, int maxDepth)
+ {
+ checkMonitorPermissions();
+ if (maxDepth < 0)
+ throw new IllegalArgumentException("Invalid depth: " + maxDepth);
+ ThreadInfo[] infos = new ThreadInfo[ids.length];
+ for (int a = 0; a < ids.length; ++a)
+ {
+ if (ids[a] <= 0)
+ throw new IllegalArgumentException("Invalid thread id " + a +
+ ": " + ids[a]);
+ infos[a] = VMThreadMXBeanImpl.getThreadInfoForId(ids[a], maxDepth);
+ }
+ return infos;
+ }
+
+ public long getThreadUserTime(long id)
+ {
+ if (!isThreadCpuTimeSupported())
+ throw new UnsupportedOperationException("Thread user time not " +
+ "supported.");
+ if (id <= 0)
+ throw new IllegalArgumentException("Invalid thread id: " + id);
+ if (!timeEnabled)
+ return -1;
+ return VMThreadMXBeanImpl.getThreadUserTime(id);
+ }
+
+ public long getTotalStartedThreadCount()
+ {
+ return VMThreadMXBeanImpl.getTotalStartedThreadCount();
+ }
+
+ public boolean isCurrentThreadCpuTimeSupported()
+ {
+ if (isThreadCpuTimeSupported())
+ return true;
+ return SystemProperties.getProperty(CURRENT_THREAD_TIME_SUPPORT) != null;
+ }
+
+ public boolean isThreadContentionMonitoringEnabled()
+ {
+ if (isThreadContentionMonitoringSupported())
+ return contentionEnabled;
+ else
+ throw new UnsupportedOperationException("Contention monitoring " +
+ "not supported.");
+ }
+
+ public boolean isThreadContentionMonitoringSupported()
+ {
+ return SystemProperties.getProperty(CONTENTION_SUPPORT) != null;
+ }
+
+ public boolean isThreadCpuTimeEnabled()
+ {
+ if (isThreadCpuTimeSupported() ||
+ isCurrentThreadCpuTimeSupported())
+ return timeEnabled;
+ else
+ throw new UnsupportedOperationException("Thread time not " +
+ "supported.");
+ }
+
+ public boolean isThreadCpuTimeSupported()
+ {
+ return SystemProperties.getProperty(THREAD_TIME_SUPPORT) != null;
+ }
+
+ public void resetPeakThreadCount()
+ {
+ checkControlPermissions();
+ VMThreadMXBeanImpl.resetPeakThreadCount();
+ }
+
+ public void setThreadContentionMonitoringEnabled(boolean enable)
+ {
+ checkControlPermissions();
+ if (isThreadContentionMonitoringSupported())
+ contentionEnabled = enable;
+ else
+ throw new UnsupportedOperationException("Contention monitoring " +
+ "not supported.");
+ }
+
+ public void setThreadCpuTimeEnabled(boolean enable)
+ {
+ checkControlPermissions();
+ if (isThreadCpuTimeSupported() ||
+ isCurrentThreadCpuTimeSupported())
+ timeEnabled = enable;
+ else
+ throw new UnsupportedOperationException("Thread time not " +
+ "supported.");
+ }
+
+}
+
diff --git a/libjava/classpath/gnu/java/lang/management/package.html b/libjava/classpath/gnu/java/lang/management/package.html
new file mode 100644
index 0000000..fc1bafc
--- /dev/null
+++ b/libjava/classpath/gnu/java/lang/management/package.html
@@ -0,0 +1,46 @@
+
+
+
+
+FileURLLoader
is a type of URLLoader
+ * only loading from file url.
+ */
+public final class FileURLLoader extends URLLoader
+{
+ File dir; //the file for this file url
+
+ public FileURLLoader(URLClassLoader classloader,
+ URLStreamHandlerCache cache,
+ URLStreamHandlerFactory factory,
+ URL url, URL absoluteUrl)
+ {
+ super(classloader, cache, factory, url, absoluteUrl);
+ dir = new File(absoluteUrl.getFile());
+ }
+
+ /** get resource with the name "name" in the file url */
+ public Resource getResource(String name)
+ {
+ try
+ {
+ // Make sure that all components in name are valid by walking through
+ // them
+ File file = walkPathComponents(name);
+
+ if (file == null)
+ return null;
+
+ return new FileResource(this, file);
+ }
+ catch (IOException e)
+ {
+ // Fall through...
+ }
+ return null;
+ }
+
+ /**
+ * Walk all path tokens and check them for validity. At no moment, we are
+ * allowed to reach a directory located "above" the root directory, stored
+ * in "dir" property. We are also not allowed to enter a non existing
+ * directory or a non directory component (plain file, symbolic link, ...).
+ * An empty or null path is valid. Pathnames components are separated by
+ * File.separatorChar
+ *
+ * @param resourceFileName the name to be checked for validity.
+ * @return the canonical file pointed by the resourceFileName or null if the
+ * walking failed
+ * @throws IOException in case of issue when creating the canonical
+ * resulting file
+ * @see File#separatorChar
+ */
+ private File walkPathComponents(String resourceFileName) throws IOException
+ {
+ StringTokenizer stringTokenizer = new StringTokenizer(resourceFileName, File.separator);
+ File currentFile = dir;
+ int tokenCount = stringTokenizer.countTokens();
+
+ for (int i = 0; i < tokenCount - 1; i++)
+ {
+ String currentToken = stringTokenizer.nextToken();
+
+ // If we are at the root directory and trying to go up, the walking is
+ // finished with an error
+ if ("..".equals(currentToken) && currentFile.equals(dir))
+ return null;
+
+ currentFile = new File(currentFile, currentToken);
+
+ // If the current file doesn't exist or is not a directory, the walking is
+ // finished with an error
+ if (! (currentFile.exists() && currentFile.isDirectory()))
+ return null;
+
+ }
+
+ // Treat the last token differently, if it exists, because it does not need
+ // to be a directory
+ if (tokenCount > 0)
+ {
+ String currentToken = stringTokenizer.nextToken();
+
+ if ("..".equals(currentToken) && currentFile.equals(dir))
+ return null;
+
+ currentFile = new File(currentFile, currentToken);
+
+ // If the current file doesn't exist, the walking is
+ // finished with an error
+ if (! currentFile.exists())
+ return null;
+ }
+
+ return currentFile.getCanonicalFile();
+ }
+}
\ No newline at end of file
diff --git a/libjava/classpath/gnu/java/net/loader/JarURLLoader.java b/libjava/classpath/gnu/java/net/loader/JarURLLoader.java
new file mode 100644
index 0000000..9385760
--- /dev/null
+++ b/libjava/classpath/gnu/java/net/loader/JarURLLoader.java
@@ -0,0 +1,215 @@
+package gnu.java.net.loader;
+
+import gnu.java.net.IndexListParser;
+
+import java.io.IOException;
+import java.net.JarURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.net.URLStreamHandlerFactory;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+/**
+ * A JarURLLoader
is a type of URLLoader
+ * only loading from jar url.
+ */
+public final class JarURLLoader extends URLLoader
+{
+ // True if we've initialized -- i.e., tried open the jar file.
+ boolean initialized;
+ // The jar file for this url.
+ JarFile jarfile;
+ // Base jar: url for all resources loaded from jar.
+ final URL baseJarURL;
+ // The "Class-Path" attribute of this Jar's manifest.
+ ArrayList classPath;
+ // If not null, a mapping from INDEX.LIST for this jar only.
+ // This is a set of all prefixes and top-level files that
+ // ought to be available in this jar.
+ Set indexSet;
+
+ // This constructor is used internally. It purposely does not open
+ // the jar file -- it defers this until later. This allows us to
+ // implement INDEX.LIST lazy-loading semantics.
+ private JarURLLoader(URLClassLoader classloader, URLStreamHandlerCache cache,
+ URLStreamHandlerFactory factory,
+ URL baseURL, URL absoluteUrl,
+ Set indexSet)
+ {
+ super(classloader, cache, factory, baseURL, absoluteUrl);
+
+ URL newBaseURL = null;
+ try
+ {
+ // Cache url prefix for all resources in this jar url.
+ String base = baseURL.toExternalForm() + "!/";
+ newBaseURL = new URL("jar", "", -1, base, cache.get(factory, "jar"));
+ }
+ catch (MalformedURLException ignore)
+ {
+ // Ignore.
+ }
+ this.baseJarURL = newBaseURL;
+ this.classPath = null;
+ this.indexSet = indexSet;
+ }
+
+ // This constructor is used by URLClassLoader. It will immediately
+ // try to read the jar file, in case we've found an index or a class-path
+ // setting. FIXME: it would be nice to defer this as well, but URLClassLoader
+ // makes this hard.
+ public JarURLLoader(URLClassLoader classloader, URLStreamHandlerCache cache,
+ URLStreamHandlerFactory factory,
+ URL baseURL, URL absoluteUrl)
+ {
+ this(classloader, cache, factory, baseURL, absoluteUrl, null);
+ initialize();
+ }
+
+ private void initialize()
+ {
+ JarFile jarfile = null;
+ try
+ {
+ jarfile =
+ ((JarURLConnection) baseJarURL.openConnection()).getJarFile();
+
+ Manifest manifest;
+ Attributes attributes;
+ String classPathString;
+
+ IndexListParser parser = new IndexListParser(jarfile, baseJarURL,
+ baseURL);
+ LinkedHashMap indexMap = parser.getHeaders();
+ if (indexMap != null)
+ {
+ // Note that the index also computes
+ // the resulting Class-Path -- there are jars out there
+ // where the index lists some required jars which do
+ // not appear in the Class-Path attribute in the manifest.
+ this.classPath = new ArrayList();
+ Iterator it = indexMap.entrySet().iterator();
+ while (it.hasNext())
+ {
+ Map.Entry entry = (Map.Entry) it.next();
+ URL subURL = (URL) entry.getKey();
+ Set prefixes = (Set) entry.getValue();
+ if (subURL.equals(baseURL))
+ this.indexSet = prefixes;
+ else
+ {
+ JarURLLoader subLoader = new JarURLLoader(classloader,
+ cache,
+ factory, subURL,
+ subURL,
+ prefixes);
+ // Note that we don't care if the sub-loader itself has an
+ // index or a class-path -- only the top-level jar
+ // file gets this treatment; its index should cover
+ // everything.
+ this.classPath.add(subLoader);
+ }
+ }
+ }
+ else if ((manifest = jarfile.getManifest()) != null
+ && (attributes = manifest.getMainAttributes()) != null
+ && ((classPathString
+ = attributes.getValue(Attributes.Name.CLASS_PATH))
+ != null))
+ {
+ this.classPath = new ArrayList();
+ StringTokenizer st = new StringTokenizer(classPathString, " ");
+ while (st.hasMoreElements ())
+ {
+ String e = st.nextToken ();
+ try
+ {
+ URL subURL = new URL(baseURL, e);
+ // We've seen at least one jar file whose Class-Path
+ // attribute includes the original jar. If we process
+ // that normally we end up with infinite recursion.
+ if (subURL.equals(baseURL))
+ continue;
+ JarURLLoader subLoader = new JarURLLoader(classloader,
+ cache, factory,
+ subURL, subURL);
+ this.classPath.add(subLoader);
+ ArrayList extra = subLoader.getClassPath();
+ if (extra != null)
+ this.classPath.addAll(extra);
+ }
+ catch (java.net.MalformedURLException xx)
+ {
+ // Give up
+ }
+ }
+ }
+ }
+ catch (IOException ioe)
+ {
+ /* ignored */
+ }
+
+ this.jarfile = jarfile;
+ this.initialized = true;
+ }
+
+ /** get resource with the name "name" in the jar url */
+ public Resource getResource(String name)
+ {
+ if (name.startsWith("/"))
+ name = name.substring(1);
+ if (indexSet != null)
+ {
+ // Trust the index.
+ String basename = name;
+ int offset = basename.lastIndexOf('/');
+ if (offset != -1)
+ basename = basename.substring(0, offset);
+ if (! indexSet.contains(basename))
+ return null;
+ // FIXME: if the index claim to hold the resource, and jar file
+ // doesn't have it, we're supposed to throw an exception. However,
+ // in our model this is tricky to implement, as another URLLoader from
+ // the same top-level jar may have an overlapping index entry.
+ }
+
+ if (! initialized)
+ initialize();
+ if (jarfile == null)
+ return null;
+
+ JarEntry je = jarfile.getJarEntry(name);
+ if (je != null)
+ return new JarURLResource(this, name, je);
+ else
+ return null;
+ }
+
+ public Manifest getManifest()
+ {
+ try
+ {
+ return (jarfile == null) ? null : jarfile.getManifest();
+ }
+ catch (IOException ioe)
+ {
+ return null;
+ }
+ }
+
+ public ArrayList getClassPath()
+ {
+ return classPath;
+ }
+}
diff --git a/libjava/classpath/gnu/java/net/loader/JarURLResource.java b/libjava/classpath/gnu/java/net/loader/JarURLResource.java
new file mode 100644
index 0000000..a9db5ce
--- /dev/null
+++ b/libjava/classpath/gnu/java/net/loader/JarURLResource.java
@@ -0,0 +1,94 @@
+/* JarURLResource.java -- a Resource for jar URLs
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.net.loader;
+
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.cert.Certificate;
+import java.util.jar.JarEntry;
+
+public final class JarURLResource extends Resource
+{
+ private final JarEntry entry;
+ private final String name;
+
+ public JarURLResource(JarURLLoader loader, String name, JarEntry entry)
+ {
+ super(loader);
+ this.entry = entry;
+ this.name = name;
+ }
+
+ public InputStream getInputStream() throws IOException
+ {
+ return ((JarURLLoader) loader).jarfile.getInputStream(entry);
+ }
+
+ public int getLength()
+ {
+ return (int) entry.getSize();
+ }
+
+ public Certificate[] getCertificates()
+ {
+ // We have to get the entry from the jar file again, because the
+ // certificates will not be available until the entire entry has
+ // been read.
+ return ((JarEntry) ((JarURLLoader) loader).jarfile.getEntry(name))
+ .getCertificates();
+ }
+
+ public URL getURL()
+ {
+ try
+ {
+ return new URL(((JarURLLoader) loader).baseJarURL, name,
+ loader.cache.get(loader.factory, "jar"));
+ }
+ catch (MalformedURLException e)
+ {
+ InternalError ie = new InternalError();
+ ie.initCause(e);
+ throw ie;
+ }
+ }
+}
\ No newline at end of file
diff --git a/libjava/classpath/gnu/java/net/loader/RemoteResource.java b/libjava/classpath/gnu/java/net/loader/RemoteResource.java
new file mode 100644
index 0000000..f180315
--- /dev/null
+++ b/libjava/classpath/gnu/java/net/loader/RemoteResource.java
@@ -0,0 +1,78 @@
+/* Resource.java -- a Resource for "remote" URLs
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.net.loader;
+
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+/**
+ * A resource from some remote location.
+ */
+public final class RemoteResource extends Resource
+{
+ private final URL url;
+ private final InputStream stream;
+ final int length;
+
+ public RemoteResource(RemoteURLLoader loader, String name, URL url,
+ InputStream stream, int length)
+ {
+ super(loader);
+ this.url = url;
+ this.stream = stream;
+ this.length = length;
+ }
+
+ public InputStream getInputStream() throws IOException
+ {
+ return stream;
+ }
+
+ public int getLength()
+ {
+ return length;
+ }
+
+ public URL getURL()
+ {
+ return url;
+ }
+}
\ No newline at end of file
diff --git a/libjava/classpath/gnu/java/net/loader/RemoteURLLoader.java b/libjava/classpath/gnu/java/net/loader/RemoteURLLoader.java
new file mode 100644
index 0000000..f044740
--- /dev/null
+++ b/libjava/classpath/gnu/java/net/loader/RemoteURLLoader.java
@@ -0,0 +1,101 @@
+/* RemoteURLLoader.java -- a URLLoader for "remote" objects
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.net.loader;
+
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.net.URLConnection;
+import java.net.URLStreamHandlerFactory;
+
+/**
+ * Loader for remote directories.
+ */
+public final class RemoteURLLoader extends URLLoader
+{
+ private final String protocol;
+
+ public RemoteURLLoader(URLClassLoader classloader,
+ URLStreamHandlerCache cache,
+ URLStreamHandlerFactory factory,
+ URL url)
+ {
+ super(classloader, cache, factory, url);
+ protocol = url.getProtocol();
+ }
+
+ /**
+ * Get a remote resource.
+ * Returns null if no such resource exists.
+ */
+ public Resource getResource(String name)
+ {
+ try
+ {
+ URL url = new URL(baseURL, name, cache.get(factory, protocol));
+ URLConnection connection = url.openConnection();
+
+ // Open the connection and check the stream
+ // just to be sure it exists.
+ int length = connection.getContentLength();
+ InputStream stream = connection.getInputStream();
+
+ // We can do some extra checking if it is a http request
+ if (connection instanceof HttpURLConnection)
+ {
+ int response =
+ ((HttpURLConnection) connection).getResponseCode();
+ if (response / 100 != 2)
+ return null;
+ }
+
+ if (stream != null)
+ return new RemoteResource(this, name, url, stream, length);
+ else
+ return null;
+ }
+ catch (IOException ioe)
+ {
+ return null;
+ }
+ }
+}
\ No newline at end of file
diff --git a/libjava/classpath/gnu/java/net/loader/Resource.java b/libjava/classpath/gnu/java/net/loader/Resource.java
new file mode 100644
index 0000000..e367a33
--- /dev/null
+++ b/libjava/classpath/gnu/java/net/loader/Resource.java
@@ -0,0 +1,110 @@
+/* Resource.java -- a resource for URLLoader
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.net.loader;
+
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.CodeSource;
+import java.security.cert.Certificate;
+
+/**
+ * A Resource
represents a resource in some
+ * URLLoader
. It also contains all information (e.g.,
+ * URL
, CodeSource
, Manifest
and
+ * InputStream
) that is necessary for loading resources
+ * and creating classes from a URL
.
+ */
+public abstract class Resource
+{
+ final URLLoader loader;
+
+ public Resource(URLLoader loader)
+ {
+ this.loader = loader;
+ }
+
+ /**
+ * Returns the non-null CodeSource
associated with
+ * this resource.
+ */
+ public CodeSource getCodeSource()
+ {
+ Certificate[] certs = getCertificates();
+ if (certs == null)
+ return loader.noCertCodeSource;
+ else
+ return new CodeSource(loader.baseURL, certs);
+ }
+
+ /**
+ * Returns Certificates
associated with this
+ * resource, or null when there are none.
+ */
+ public Certificate[] getCertificates()
+ {
+ return null;
+ }
+
+ /**
+ * Return the URLLoader for this resource.
+ */
+ public final URLLoader getLoader()
+ {
+ return loader;
+ }
+
+ /**
+ * Return a URL
that can be used to access this resource.
+ */
+ public abstract URL getURL();
+
+ /**
+ * Returns the size of this Resource
in bytes or
+ * -1
when unknown.
+ */
+ public abstract int getLength();
+
+ /**
+ * Returns the non-null InputStream
through which
+ * this resource can be loaded.
+ */
+ public abstract InputStream getInputStream() throws IOException;
+}
\ No newline at end of file
diff --git a/libjava/classpath/gnu/java/net/loader/URLLoader.java b/libjava/classpath/gnu/java/net/loader/URLLoader.java
new file mode 100644
index 0000000..d073c54
--- /dev/null
+++ b/libjava/classpath/gnu/java/net/loader/URLLoader.java
@@ -0,0 +1,147 @@
+/* URLLoader.java -- base helper class for URLClassLoader
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.net.loader;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.net.URLStreamHandlerFactory;
+import java.security.CodeSource;
+import java.util.ArrayList;
+import java.util.jar.Manifest;
+
+/**
+ * A URLLoader
contains all logic to load resources from a
+ * given base URL
.
+ */
+public abstract class URLLoader
+{
+ /**
+ * Our classloader to get info from if needed.
+ */
+ final URLClassLoader classloader;
+
+ /**
+ * The base URL from which all resources are loaded.
+ */
+ final URL baseURL;
+
+ /**
+ * The stream handler factory.
+ */
+ final URLStreamHandlerFactory factory;
+
+ /**
+ * The source for stream handlers.
+ */
+ final URLStreamHandlerCache cache;
+
+ /**
+ * A CodeSource
without any associated certificates.
+ * It is common for classes to not have certificates associated
+ * with them. If they come from the same URLLoader
+ * then it is safe to share the associated CodeSource
+ * between them since CodeSource
is immutable.
+ */
+ final CodeSource noCertCodeSource;
+
+ public URLLoader(URLClassLoader classloader, URLStreamHandlerCache cache,
+ URLStreamHandlerFactory factory,
+ URL baseURL)
+ {
+ this(classloader, cache, factory, baseURL, baseURL);
+ }
+
+ public URLLoader(URLClassLoader classloader, URLStreamHandlerCache cache,
+ URLStreamHandlerFactory factory,
+ URL baseURL, URL overrideURL)
+ {
+ this.classloader = classloader;
+ this.baseURL = baseURL;
+ this.factory = factory;
+ this.cache = cache;
+ this.noCertCodeSource = new CodeSource(overrideURL, null);
+ }
+
+ /**
+ * Return the base URL of this loader.
+ */
+ public final URL getBaseURL()
+ {
+ return baseURL;
+ }
+
+ /**
+ * Returns a Class
loaded by this
+ * URLLoader
, or null
when this loader
+ * either can't load the class or doesn't know how to load classes
+ * at all. Most subclasses do not need to override this; it is only
+ * useful in situations where the subclass has a more direct way of
+ * making Class
objects.
+ */
+ public Class getClass(String className)
+ {
+ return null;
+ }
+
+ /**
+ * Returns a Resource
loaded by this
+ * URLLoader
, or null
when no
+ * Resource
with the given name exists.
+ */
+ public abstract Resource getResource(String s);
+
+ /**
+ * Returns the Manifest
associated with the
+ * Resource
s loaded by this URLLoader
or
+ * null
there is no such Manifest
.
+ */
+ public Manifest getManifest()
+ {
+ return null;
+ }
+
+ /**
+ * Return a list of new URLLoader objects representing any
+ * class path entries added by this container.
+ */
+ public ArrayList getClassPath()
+ {
+ return null;
+ }
+}
\ No newline at end of file
diff --git a/libjava/classpath/gnu/java/net/loader/URLStreamHandlerCache.java b/libjava/classpath/gnu/java/net/loader/URLStreamHandlerCache.java
new file mode 100644
index 0000000..295a15d
--- /dev/null
+++ b/libjava/classpath/gnu/java/net/loader/URLStreamHandlerCache.java
@@ -0,0 +1,84 @@
+/* URLStreamHandlerCache.java -- a cache for URLStreamHandlers
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.net.loader;
+
+import java.net.URLStreamHandler;
+import java.net.URLStreamHandlerFactory;
+import java.util.HashMap;
+
+/**
+ */
+public class URLStreamHandlerCache
+{
+ /**
+ * A cache to store mappings between handler factory and its
+ * private protocol handler cache (also a HashMap), so we can avoid
+ * creating handlers each time the same protocol comes.
+ */
+ private HashMap factoryCache = new HashMap(5);
+
+ public URLStreamHandlerCache()
+ {
+ }
+
+ public synchronized void add(URLStreamHandlerFactory factory)
+ {
+ // Since we only support three protocols so far, 5 is enough
+ // for cache initial size.
+ if (factory != null && factoryCache.get(factory) == null)
+ factoryCache.put(factory, new HashMap(5));
+ }
+
+ public synchronized URLStreamHandler get(URLStreamHandlerFactory factory,
+ String protocol)
+ {
+ if (factory == null)
+ return null;
+ // Check if there're handler for the same protocol in cache.
+ HashMap cache = (HashMap) factoryCache.get(factory);
+ URLStreamHandler handler = (URLStreamHandler) cache.get(protocol);
+ if (handler == null)
+ {
+ // Add it to cache.
+ handler = factory.createURLStreamHandler(protocol);
+ cache.put(protocol, handler);
+ }
+ return handler;
+ }
+}
diff --git a/libjava/classpath/gnu/java/net/local/LocalSocket.java b/libjava/classpath/gnu/java/net/local/LocalSocket.java
index b977d69..b262c79 100644
--- a/libjava/classpath/gnu/java/net/local/LocalSocket.java
+++ b/libjava/classpath/gnu/java/net/local/LocalSocket.java
@@ -247,12 +247,13 @@ public final class LocalSocket extends Socket
public void setSoTimeout (int i) throws SocketException
{
- throw new SocketException ("local sockets do not support this option");
+ // Ignore.
}
public int getSoTimeout () throws SocketException
{
- throw new SocketException ("local sockets do not support this option");
+ // We don't support timeout, so we return 0.
+ return 0;
}
public void setSendBufferSize (int i) throws SocketException
diff --git a/libjava/classpath/gnu/java/net/local/LocalSocketImpl.java b/libjava/classpath/gnu/java/net/local/LocalSocketImpl.java
index f907e5f..f43305a 100644
--- a/libjava/classpath/gnu/java/net/local/LocalSocketImpl.java
+++ b/libjava/classpath/gnu/java/net/local/LocalSocketImpl.java
@@ -57,7 +57,8 @@ final class LocalSocketImpl extends SocketImpl
private boolean created;
private InputStream in;
private OutputStream out;
- private int socket_fd;
+ // Package private to avoid synthetic accessor method.
+ int socket_fd;
private LocalSocketAddress local;
private LocalSocketAddress remote;
@@ -104,7 +105,7 @@ final class LocalSocketImpl extends SocketImpl
protected native void create (boolean stream) throws IOException;
protected native void listen (int timeout) throws IOException;
protected native void accept (LocalSocketImpl socket) throws IOException;
- protected native int available () throws IOException;
+ protected native int available (int fd) throws IOException;
protected native void close () throws IOException;
protected native void sendUrgentData (int data) throws IOException;
protected native void shutdownInput () throws IOException;
@@ -113,8 +114,14 @@ final class LocalSocketImpl extends SocketImpl
native void unlink () throws IOException;
native void localBind (LocalSocketAddress addr) throws IOException;
native void localConnect (LocalSocketAddress addr) throws IOException;
- native int read (byte[] buf, int off, int len) throws IOException;
- native void write (byte[] buf, int off, int len) throws IOException;
+ native int read (int fd, byte[] buf, int off, int len) throws IOException;
+ native void write (int fd, byte[] buf, int off, int len) throws IOException;
+
+ protected int available()
+ throws IOException
+ {
+ return available(socket_fd);
+ }
void doCreate () throws IOException
{
@@ -263,7 +270,7 @@ final class LocalSocketImpl extends SocketImpl
public int read (byte[] buf, int off, int len) throws IOException
{
- int ret = impl.read (buf, off, len);
+ int ret = impl.read (socket_fd, buf, off, len);
if (ret == 0)
{
@@ -316,7 +323,7 @@ final class LocalSocketImpl extends SocketImpl
public void write (byte[] buf, int off, int len) throws IOException
{
- impl.write (buf, off, len);
+ impl.write (socket_fd, buf, off, len);
}
}
}
diff --git a/libjava/classpath/gnu/java/net/protocol/http/HTTPConnection.java b/libjava/classpath/gnu/java/net/protocol/http/HTTPConnection.java
index 33d9756a..f5e831c 100644
--- a/libjava/classpath/gnu/java/net/protocol/http/HTTPConnection.java
+++ b/libjava/classpath/gnu/java/net/protocol/http/HTTPConnection.java
@@ -466,7 +466,8 @@ public class HTTPConnection
*/
synchronized HTTPConnection get(String host,
int port,
- boolean secure)
+ boolean secure,
+ int connectionTimeout, int timeout)
{
String ttl =
SystemProperties.getProperty("classpath.net.http.keepAliveTTL");
@@ -494,7 +495,7 @@ public class HTTPConnection
}
if (c == null)
{
- c = new HTTPConnection(host, port, secure);
+ c = new HTTPConnection(host, port, secure, connectionTimeout, timeout);
c.setPool(this);
}
return c;
diff --git a/libjava/classpath/gnu/java/net/protocol/http/HTTPURLConnection.java b/libjava/classpath/gnu/java/net/protocol/http/HTTPURLConnection.java
index 0dce7c7..a46d120 100644
--- a/libjava/classpath/gnu/java/net/protocol/http/HTTPURLConnection.java
+++ b/libjava/classpath/gnu/java/net/protocol/http/HTTPURLConnection.java
@@ -65,7 +65,7 @@ import javax.net.ssl.SSLSocketFactory;
* @author Chris Burdess (dog@gnu.org)
*/
public class HTTPURLConnection
- extends HttpsURLConnection
+ extends HttpsURLConnection
implements HandshakeCompletedListener
{
/*
@@ -346,11 +346,11 @@ public class HTTPURLConnection
HTTPConnection connection;
if (keepAlive)
{
- connection = HTTPConnection.Pool.instance.get(host, port, secure);
+ connection = HTTPConnection.Pool.instance.get(host, port, secure, getConnectTimeout(), 0);
}
else
{
- connection = new HTTPConnection(host, port, secure);
+ connection = new HTTPConnection(host, port, secure, 0, getConnectTimeout());
}
return connection;
}
@@ -653,5 +653,27 @@ public class HTTPURLConnection
handshakeEvent = event;
}
+ /**
+ * Set the connection timeout speed, in milliseconds, or zero if the timeout
+ * is to be considered infinite.
+ *
+ * Overloaded.
+ *
+ */
+ public void setConnectTimeout(int timeout)
+ throws IllegalArgumentException
+ {
+ super.setConnectTimeout( timeout );
+ if( connection == null )
+ return;
+ try
+ {
+ connection.getSocket().setSoTimeout( timeout );
+ }
+ catch(IOException se)
+ {
+ // Ignore socket exceptions.
+ }
+ }
}
diff --git a/libjava/classpath/gnu/java/net/protocol/jar/Connection.java b/libjava/classpath/gnu/java/net/protocol/jar/Connection.java
index 41c5d6d..f99806a 100644
--- a/libjava/classpath/gnu/java/net/protocol/jar/Connection.java
+++ b/libjava/classpath/gnu/java/net/protocol/jar/Connection.java
@@ -188,7 +188,7 @@ public final class Connection extends JarURLConnection
else if (field.equals("last-modified"))
{
// Both creating and manipulating dateFormat need synchronization.
- synchronized (this.getClass())
+ synchronized (Connection.class)
{
if (dateFormat == null)
dateFormat = new SimpleDateFormat
diff --git a/libjava/classpath/gnu/java/nio/PipeImpl.java b/libjava/classpath/gnu/java/nio/PipeImpl.java
index f7b01c8..cccaa39 100644
--- a/libjava/classpath/gnu/java/nio/PipeImpl.java
+++ b/libjava/classpath/gnu/java/nio/PipeImpl.java
@@ -37,6 +37,7 @@ exception statement from your version. */
package gnu.java.nio;
+
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
@@ -47,12 +48,14 @@ class PipeImpl extends Pipe
public static final class SourceChannelImpl extends Pipe.SourceChannel
{
private int native_fd;
+ private VMChannel vmch;
public SourceChannelImpl (SelectorProvider selectorProvider,
int native_fd)
{
super (selectorProvider);
this.native_fd = native_fd;
+ vmch = VMChannel.getVMChannel(this);
}
protected final void implCloseSelectableChannel()
@@ -64,19 +67,19 @@ class PipeImpl extends Pipe
protected void implConfigureBlocking (boolean blocking)
throws IOException
{
- throw new Error ("Not implemented");
+ vmch.setBlocking(blocking);
}
public final int read (ByteBuffer src)
throws IOException
{
- throw new Error ("Not implemented");
+ return vmch.read(src);
}
public final long read (ByteBuffer[] srcs)
throws IOException
{
- return read (srcs, 0, srcs.length);
+ return vmch.readScattering(srcs, 0, srcs.length);
}
public final synchronized long read (ByteBuffer[] srcs, int offset,
@@ -89,13 +92,7 @@ class PipeImpl extends Pipe
|| len > srcs.length - offset)
throw new IndexOutOfBoundsException();
- long bytesRead = 0;
-
- for (int index = 0; index < len; index++)
- bytesRead += read (srcs [offset + index]);
-
- return bytesRead;
-
+ return vmch.readScattering(srcs, offset, len);
}
public final int getNativeFD()
@@ -107,12 +104,14 @@ class PipeImpl extends Pipe
public static final class SinkChannelImpl extends Pipe.SinkChannel
{
private int native_fd;
+ private VMChannel vmch;
public SinkChannelImpl (SelectorProvider selectorProvider,
int native_fd)
{
super (selectorProvider);
this.native_fd = native_fd;
+ vmch = VMChannel.getVMChannel(this);
}
protected final void implCloseSelectableChannel()
@@ -124,19 +123,19 @@ class PipeImpl extends Pipe
protected final void implConfigureBlocking (boolean blocking)
throws IOException
{
- throw new Error ("Not implemented");
+ vmch.setBlocking(blocking);
}
public final int write (ByteBuffer dst)
throws IOException
{
- throw new Error ("Not implemented");
+ return vmch.write(dst);
}
public final long write (ByteBuffer[] srcs)
throws IOException
{
- return write (srcs, 0, srcs.length);
+ return vmch.writeGathering(srcs, 0, srcs.length);
}
public final synchronized long write (ByteBuffer[] srcs, int offset, int len)
@@ -147,13 +146,8 @@ class PipeImpl extends Pipe
|| len < 0
|| len > srcs.length - offset)
throw new IndexOutOfBoundsException();
-
- long bytesWritten = 0;
- for (int index = 0; index < len; index++)
- bytesWritten += write (srcs [offset + index]);
-
- return bytesWritten;
+ return vmch.writeGathering(srcs, offset, len);
}
public final int getNativeFD()
diff --git a/libjava/classpath/gnu/java/nio/SelectionKeyImpl.java b/libjava/classpath/gnu/java/nio/SelectionKeyImpl.java
index a1f125e..8745377 100644
--- a/libjava/classpath/gnu/java/nio/SelectionKeyImpl.java
+++ b/libjava/classpath/gnu/java/nio/SelectionKeyImpl.java
@@ -1,5 +1,5 @@
/* SelectionKeyImpl.java --
- Copyright (C) 2002, 2003 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2003, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -47,8 +47,8 @@ public abstract class SelectionKeyImpl extends AbstractSelectionKey
{
private int readyOps;
private int interestOps;
- private SelectorImpl impl;
- SelectableChannel ch;
+ private final SelectorImpl impl;
+ final SelectableChannel ch;
public SelectionKeyImpl (SelectableChannel ch, SelectorImpl impl)
{
@@ -61,7 +61,7 @@ public abstract class SelectionKeyImpl extends AbstractSelectionKey
return ch;
}
- public int readyOps ()
+ public synchronized int readyOps ()
{
if (!isValid())
throw new CancelledKeyException();
@@ -69,7 +69,7 @@ public abstract class SelectionKeyImpl extends AbstractSelectionKey
return readyOps;
}
- public SelectionKey readyOps (int ops)
+ public synchronized SelectionKey readyOps (int ops)
{
if (!isValid())
throw new CancelledKeyException();
@@ -83,15 +83,21 @@ public abstract class SelectionKeyImpl extends AbstractSelectionKey
if (!isValid())
throw new CancelledKeyException();
- return interestOps;
+ synchronized (impl.selectedKeys())
+ {
+ return interestOps;
+ }
}
public SelectionKey interestOps (int ops)
{
if (!isValid())
throw new CancelledKeyException();
-
- interestOps = ops;
+
+ synchronized (impl.selectedKeys())
+ {
+ interestOps = ops;
+ }
return this;
}
diff --git a/libjava/classpath/gnu/java/nio/SelectorImpl.java b/libjava/classpath/gnu/java/nio/SelectorImpl.java
index e10f715..d0ec487 100644
--- a/libjava/classpath/gnu/java/nio/SelectorImpl.java
+++ b/libjava/classpath/gnu/java/nio/SelectorImpl.java
@@ -1,5 +1,5 @@
/* SelectorImpl.java --
- Copyright (C) 2002, 2003, 2004 Free Software Foundation, Inc.
+ Copyright (C) 2002, 2003, 2004, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -379,16 +379,19 @@ public class SelectorImpl extends AbstractSelector
result = new DatagramChannelSelectionKey (ch, this);
else if (ch instanceof ServerSocketChannelImpl)
result = new ServerSocketChannelSelectionKey (ch, this);
+ else if (ch instanceof gnu.java.nio.SocketChannelImpl)
+ result = new gnu.java.nio.SocketChannelSelectionKeyImpl((gnu.java.nio.SocketChannelImpl)ch, this);
else
throw new InternalError ("No known channel type");
synchronized (keys)
{
keys.add (result);
+
+ result.interestOps (ops);
+ result.attach (att);
}
- result.interestOps (ops);
- result.attach (att);
return result;
}
}
diff --git a/libjava/classpath/gnu/java/nio/SocketChannelSelectionKeyImpl.java b/libjava/classpath/gnu/java/nio/SocketChannelSelectionKeyImpl.java
new file mode 100644
index 0000000..30fb2df
--- /dev/null
+++ b/libjava/classpath/gnu/java/nio/SocketChannelSelectionKeyImpl.java
@@ -0,0 +1,69 @@
+/* SocketChannelSelectionKey.java -- Selection key for Socket Channel
+ Copyright (C) 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.nio;
+
+
+/**
+ * @author Michael Barker key
.key
.
+ *
* @param key the case-insensitive, non-null and non-empty name of a
- * configuration property.
+ * configuration property.
* @return the string representation of the designated property, or
- * null
if such property is not yet set, or key
is
- * empty.
+ * null
if such property is not yet set, or
+ * key
is empty.
*/
public static final synchronized String getProperty(String key)
{
@@ -132,13 +111,13 @@ public final class Properties
}
/**
- * key
.
+ * configuration property.
+ * @param value the non-null, non-empty string representation of a legal value
+ * of the configuration property named by key
.
*/
public static final synchronized void setProperty(String key, String value)
{
@@ -169,13 +148,14 @@ public final class Properties
}
/**
- * true
if the default PRNG produces the same bit stream
- * with every VM instance. Returns false
if the default PRNG is
- * seeded with the time of day of its first invocation.
+ * Generator produces, or not, the same bit stream when instantiated.
+ *
+ * @return true
if the default PRNG produces the same bit
+ * stream with every VM instance. Returns false
if the
+ * default PRNG is seeded with the time of day of its first
+ * invocation.
*/
public static final synchronized boolean isReproducible()
{
@@ -186,15 +166,15 @@ public final class Properties
}
/**
- * true
if the cipher implementations check for weak and
- * semi-weak keys. Returns false
if the cipher implementations
- * do not check for weak or semi-weak keys.
+ * A convenience method that returns, as a boolean, the library global
+ * configuration property indicating if the implementations of symmetric key
+ * block ciphers check, or not, for possible/potential weak and semi-weak keys
+ * that may be produced in the course of generating round encryption and/or
+ * decryption keys.
+ *
+ * @return true
if the cipher implementations check for weak
+ * and semi-weak keys. Returns false
if the cipher
+ * implementations do not check for weak or semi-weak keys.
*/
public static final synchronized boolean checkForWeakKeys()
{
@@ -205,13 +185,14 @@ public final class Properties
}
/**
- * true
if the RSA decryption primitive includes a
- * blinding operation. Returns false
if the RSA decryption
- * primitive does not include the additional blinding operation.
+ * blinding operation. Returns false
if the RSA
+ * decryption primitive does not include the additional blinding
+ * operation.
*/
public static final synchronized boolean doRSABlinding()
{
@@ -222,11 +203,11 @@ public final class Properties
}
/**
- * true
then the default PRNG bit stream output
- * is the same with every invocation of the VM.
+ * is the same with every invocation of the VM.
*/
public static final synchronized void setReproducible(final boolean value)
{
@@ -238,12 +219,12 @@ public final class Properties
}
/**
- * true
then the cipher implementations will
- * invoke additional checks for weak and semi-weak key values that may get
- * generated.
+ * invoke additional checks for weak and semi-weak key values that
+ * may get generated.
*/
public static final synchronized void setCheckForWeakKeys(final boolean value)
{
@@ -255,11 +236,11 @@ public final class Properties
}
/**
- * true
then the code for performing the RSA
- * decryption primitive will include a blinding operation.
+ * decryption primitive will include a blinding operation.
*/
public static final synchronized void setDoRSABlinding(final boolean value)
{
@@ -277,15 +258,12 @@ public final class Properties
return singleton;
}
- // Instance methods
- // -------------------------------------------------------------------------
private void init()
{
// default values
props.put(REPRODUCIBLE_PRNG, (reproducible ? "true" : "false"));
props.put(CHECK_WEAK_KEYS, (checkForWeakKeys ? "true" : "false"));
props.put(DO_RSA_BLINDING, (doRSABlinding ? "true" : "false"));
-
// 1. allow site-wide override by reading a properties file
String propFile = null;
try
@@ -300,9 +278,8 @@ public final class Properties
}
catch (SecurityException se)
{
- if (DEBUG)
- debug("Reading property " + PROPERTIES_FILE
- + " not allowed. Ignored.");
+ if (Configuration.DEBUG)
+ log.fine("Reading property " + PROPERTIES_FILE + " not allowed. Ignored.");
}
if (propFile != null)
{
@@ -316,27 +293,24 @@ public final class Properties
}
catch (IOException ioe)
{
- if (DEBUG)
- debug("IO error reading " + propFile + ": " + ioe.getMessage());
+ if (Configuration.DEBUG)
+ log.fine("IO error reading " + propFile + ": " + ioe.getMessage());
}
catch (SecurityException se)
{
- if (DEBUG)
- debug("Security error reading " + propFile + ": "
- + se.getMessage());
+ if (Configuration.DEBUG)
+ log.fine("Security error reading " + propFile + ": "
+ + se.getMessage());
}
}
-
// 2. allow vm-specific override by allowing -D options in launcher
handleBooleanProperty(REPRODUCIBLE_PRNG);
handleBooleanProperty(CHECK_WEAK_KEYS);
handleBooleanProperty(DO_RSA_BLINDING);
-
// re-sync the 'known' properties
reproducible = Boolean.valueOf((String) props.get(REPRODUCIBLE_PRNG)).booleanValue();
checkForWeakKeys = Boolean.valueOf((String) props.get(CHECK_WEAK_KEYS)).booleanValue();
doRSABlinding = Boolean.valueOf((String) props.get(DO_RSA_BLINDING)).booleanValue();
-
// This does not change.
props.put(VERSION, Registry.VERSION_STRING);
}
@@ -350,24 +324,24 @@ public final class Properties
}
catch (SecurityException x)
{
- if (DEBUG)
- debug("SecurityManager forbids reading system properties. Ignored");
+ if (Configuration.DEBUG)
+ log.fine("SecurityManager forbids reading system properties. Ignored");
}
if (s != null)
{
s = s.trim().toLowerCase();
- // we have to test for explicit "true" or "false". anything else may
+ // we have to test for explicit "true" or "false". anything else may
// hide valid value set previously
if (s.equals(TRUE) || s.equals(FALSE))
{
- if (DEBUG)
- debug("Setting " + name + " to '" + s + "'");
+ if (Configuration.DEBUG)
+ log.fine("Setting " + name + " to '" + s + "'");
props.put(name, s);
}
else
{
- if (DEBUG)
- debug("Invalid value for -D" + name + ": " + s + ". Ignored");
+ if (Configuration.DEBUG)
+ log.fine("Invalid value for -D" + name + ": " + s + ". Ignored");
}
}
}
diff --git a/libjava/classpath/gnu/java/security/Registry.java b/libjava/classpath/gnu/java/security/Registry.java
index 0cb9251..053d717 100644
--- a/libjava/classpath/gnu/java/security/Registry.java
+++ b/libjava/classpath/gnu/java/security/Registry.java
@@ -44,10 +44,6 @@ package gnu.java.security;
*/
public interface Registry
{
-
- // Constants
- // -------------------------------------------------------------------------
-
/** The name of our Providers. */
String GNU_SECURITY = "GNU";
String GNU_CRYPTO = "GNU-CRYPTO";
@@ -93,6 +89,18 @@ public interface Registry
String CAST_128_CIPHER = "cast-128";
+ // Key Wrapping Algorithm names and synonyms ...............................
+
+ String KWA_PREFIX = "kw-";
+ String AES_KWA = KWA_PREFIX + AES_CIPHER;
+ String AES128_KWA = AES_KWA + "128";
+ String AES192_KWA = AES_KWA + "192";
+ String AES256_KWA = AES_KWA + "256";
+ String RIJNDAEL_KWA = KWA_PREFIX + RIJNDAEL_CIPHER;
+
+ String TRIPLEDES_KWA = KWA_PREFIX + TRIPLEDES_CIPHER;
+ String DESEDE_KWA = KWA_PREFIX + DESEDE_CIPHER;
+
// Message digest algorithms and synonyms...................................
String WHIRLPOOL_HASH = "whirlpool";
@@ -177,6 +185,9 @@ public interface Registry
/** TLSv1 padding scheme. */
String TLS1_PAD = "tls1";
+ /** ISO 10126-2 padding scheme. */
+ String ISO10126_PAD = "iso10126";
+
// Pseudo-random number generators..........................................
/** (Apparently) RC4 keystream PRNG. */
@@ -300,38 +311,38 @@ public interface Registry
// D (0x44) for DSS, R (0x52) for RSA, H (0x48) for Diffie-Hellman, or S
// (0x53) for SRP-6, and finally P (0x50) for Public, p (0x70) for private,
// or S (0x53) for signature.
- byte[] MAGIC_RAW_DSS_PUBLIC_KEY = new byte[] { 0x47, RAW_ENCODING_ID, 0x44,
- 0x50 };
+ byte[] MAGIC_RAW_DSS_PUBLIC_KEY = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x44, 0x50 };
- byte[] MAGIC_RAW_DSS_PRIVATE_KEY = new byte[] { 0x47, RAW_ENCODING_ID, 0x44,
- 0x70 };
+ byte[] MAGIC_RAW_DSS_PRIVATE_KEY = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x44, 0x70 };
- byte[] MAGIC_RAW_DSS_SIGNATURE = new byte[] { 0x47, RAW_ENCODING_ID, 0x44,
- 0x53 };
+ byte[] MAGIC_RAW_DSS_SIGNATURE = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x44, 0x53 };
- byte[] MAGIC_RAW_RSA_PUBLIC_KEY = new byte[] { 0x47, RAW_ENCODING_ID, 0x52,
- 0x50 };
+ byte[] MAGIC_RAW_RSA_PUBLIC_KEY = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x52, 0x50 };
- byte[] MAGIC_RAW_RSA_PRIVATE_KEY = new byte[] { 0x47, RAW_ENCODING_ID, 0x52,
- 0x70 };
+ byte[] MAGIC_RAW_RSA_PRIVATE_KEY = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x52, 0x70 };
- byte[] MAGIC_RAW_RSA_PSS_SIGNATURE = new byte[] { 0x47, RAW_ENCODING_ID,
- 0x52, 0x53 };
+ byte[] MAGIC_RAW_RSA_PSS_SIGNATURE = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x52, 0x53 };
- byte[] MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE = new byte[] { 0x47, RAW_ENCODING_ID,
- 0x52, 0x54 };
+ byte[] MAGIC_RAW_RSA_PKCS1V1_5_SIGNATURE = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x52, 0x54 };
- byte[] MAGIC_RAW_DH_PUBLIC_KEY = new byte[] { 0x47, RAW_ENCODING_ID, 0x48,
- 0x50 };
+ byte[] MAGIC_RAW_DH_PUBLIC_KEY = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x48, 0x50 };
- byte[] MAGIC_RAW_DH_PRIVATE_KEY = new byte[] { 0x47, RAW_ENCODING_ID, 0x48,
- 0x70 };
+ byte[] MAGIC_RAW_DH_PRIVATE_KEY = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x48, 0x70 };
- byte[] MAGIC_RAW_SRP_PUBLIC_KEY = new byte[] { 0x47, RAW_ENCODING_ID, 0x53,
- 0x50 };
+ byte[] MAGIC_RAW_SRP_PUBLIC_KEY = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x53, 0x50 };
- byte[] MAGIC_RAW_SRP_PRIVATE_KEY = new byte[] { 0x47, RAW_ENCODING_ID, 0x53,
- 0x70 };
+ byte[] MAGIC_RAW_SRP_PRIVATE_KEY = new byte[] {
+ 0x47, RAW_ENCODING_ID, 0x53, 0x70 };
// SASL Property names .....................................................
@@ -344,8 +355,7 @@ public interface Registry
String SASL_PASSWORD = SASL_PREFIX + ".password";
/** Name of authentication information provider packages. */
- String SASL_AUTH_INFO_PROVIDER_PKGS = SASL_PREFIX
- + ".auth.info.provider.pkgs";
+ String SASL_AUTH_INFO_PROVIDER_PKGS = SASL_PREFIX + ".auth.info.provider.pkgs";
/** SASL authorization ID. */
String SASL_AUTHORISATION_ID = SASL_PREFIX + ".authorisation.ID";
@@ -452,7 +462,4 @@ public interface Registry
int GKR_CIPHER_AES_128_OFB = 0;
int GKR_CIPHER_AES_128_CBC = 1;
-
- // Methods
- // -------------------------------------------------------------------------
}
diff --git a/libjava/classpath/gnu/java/security/hash/BaseHash.java b/libjava/classpath/gnu/java/security/hash/BaseHash.java
index 720b835..ff1750a 100644
--- a/libjava/classpath/gnu/java/security/hash/BaseHash.java
+++ b/libjava/classpath/gnu/java/security/hash/BaseHash.java
@@ -39,14 +39,11 @@ exception statement from your version. */
package gnu.java.security.hash;
/**
- *
- *
*/
-public class Haval extends BaseHash
+public class Haval
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final int HAVAL_VERSION = 1;
public static final int HAVAL_128_BIT = 16;
@@ -88,20 +84,18 @@ public class Haval extends BaseHash
/**
* Number of HAVAL rounds. Allowed values are integers in the range
- * Advances in Cryptology - AUSCRYPT'92, Lecture Notes in Computer Science,
- * Springer-Verlag, 1993;
- * Y. Zheng, J. Pieprzyk and J. Seberry.
+ * Advances in Cryptology - AUSCRYPT'92, Lecture Notes in Computer Science,
+ * Springer-Verlag, 1993;
+ * Y. Zheng, J. Pieprzyk and J. Seberry.3
- * .. 5
. The default is 3
.
+ * .. 5.
+ * The default is 3
.
*/
private int rounds = HAVAL_3_ROUND;
/** 128-bit interim result. */
private int h0, h1, h2, h3, h4, h5, h6, h7;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- * 128
bits, and
- * {@link #HAVAL_3_ROUND} for the value of number of rounds.128
bits, and
+ * {@link #HAVAL_3_ROUND} for the value of number of rounds.
*/
public Haval()
{
@@ -109,9 +103,9 @@ public class Haval extends BaseHash
}
/**
- * Haval
instance with the designated output
- * size (in bytes). Valid output size
values are 16
,
- * 20
, 24
, 28
and 32
.
- * Valid values for rounds
are in the range 3..5
- * inclusive.Haval
instance with the designated output size
+ * (in bytes). Valid output size
values are 16
,
+ * 20
, 24
, 28
and
+ * 32
. Valid values for rounds
are in the range
+ * 3..5
inclusive.
+ *
* @param size the output size in bytes of this instance.
* @param rounds the number of rounds to apply when transforming data.
* @throws IllegalArgumentException if the designated output size is invalid,
- * or if the number of rounds is invalid.
+ * or if the number of rounds is invalid.
* @see #HAVAL_128_BIT
* @see #HAVAL_160_BIT
* @see #HAVAL_192_BIT
@@ -149,24 +143,24 @@ public class Haval extends BaseHash
{
super(Registry.HAVAL_HASH, size, BLOCK_SIZE);
- if (size != HAVAL_128_BIT && size != HAVAL_160_BIT && size != HAVAL_192_BIT
- && size != HAVAL_224_BIT && size != HAVAL_256_BIT)
- {
- throw new IllegalArgumentException("Invalid HAVAL output size");
- }
+ if (size != HAVAL_128_BIT
+ && size != HAVAL_160_BIT
+ && size != HAVAL_192_BIT
+ && size != HAVAL_224_BIT
+ && size != HAVAL_256_BIT)
+ throw new IllegalArgumentException("Invalid HAVAL output size");
- if (rounds != HAVAL_3_ROUND && rounds != HAVAL_4_ROUND
+ if (rounds != HAVAL_3_ROUND
+ && rounds != HAVAL_4_ROUND
&& rounds != HAVAL_5_ROUND)
- {
- throw new IllegalArgumentException("Invalid HAVAL number of rounds");
- }
+ throw new IllegalArgumentException("Invalid HAVAL number of rounds");
this.rounds = rounds;
}
/**
- * true
if the implementation passes a basic self-test.
+ * Returns false
otherwise.
*/
boolean selfTest();
/**
- *
*
*/
-public class MD2 extends BaseHash
+public class MD2
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** An MD2 message digest is always 128-bits long, or 16 bytes. */
private static final int DIGEST_LENGTH = 16;
@@ -70,34 +66,39 @@ public class MD2 extends BaseHash
private static final int BLOCK_LENGTH = 16;
/** 256 byte "random" permutation of the digits of pi. */
- private static final byte[] PI = { 41, 46, 67, -55, -94, -40, 124, 1, 61, 54,
- 84, -95, -20, -16, 6, 19, 98, -89, 5, -13,
- -64, -57, 115, -116, -104, -109, 43, -39,
- -68, 76, -126, -54, 30, -101, 87, 60, -3,
- -44, -32, 22, 103, 66, 111, 24, -118, 23,
- -27, 18, -66, 78, -60, -42, -38, -98, -34,
- 73, -96, -5, -11, -114, -69, 47, -18, 122,
- -87, 104, 121, -111, 21, -78, 7, 63, -108,
- -62, 16, -119, 11, 34, 95, 33, -128, 127,
- 93, -102, 90, -112, 50, 39, 53, 62, -52,
- -25, -65, -9, -105, 3, -1, 25, 48, -77, 72,
- -91, -75, -47, -41, 94, -110, 42, -84, 86,
- -86, -58, 79, -72, 56, -46, -106, -92, 125,
- -74, 118, -4, 107, -30, -100, 116, 4, -15,
- 69, -99, 112, 89, 100, 113, -121, 32, -122,
- 91, -49, 101, -26, 45, -88, 2, 27, 96, 37,
- -83, -82, -80, -71, -10, 28, 70, 97, 105,
- 52, 64, 126, 15, 85, 71, -93, 35, -35, 81,
- -81, 58, -61, 92, -7, -50, -70, -59, -22,
- 38, 44, 83, 13, 110, -123, 40, -124, 9,
- -45, -33, -51, -12, 65, -127, 77, 82, 106,
- -36, 55, -56, 108, -63, -85, -6, 36, -31,
- 123, 8, 12, -67, -79, 74, 120, -120, -107,
- -117, -29, 99, -24, 109, -23, -53, -43, -2,
- 59, 0, 29, 57, -14, -17, -73, 14, 102, 88,
- -48, -28, -90, 119, 114, -8, -21, 117, 75,
- 10, 49, 68, 80, -76, -113, -19, 31, 26,
- -37, -103, -115, 51, -97, 17, -125, 20 };
+ private static final byte[] PI = {
+ 41, 46, 67, -55, -94, -40, 124, 1,
+ 61, 54, 84, -95, -20, -16, 6, 19,
+ 98, -89, 5, -13, -64, -57, 115, -116,
+ -104, -109, 43, -39, -68, 76, -126, -54,
+ 30, -101, 87, 60, -3, -44, -32, 22,
+ 103, 66, 111, 24, -118, 23, -27, 18,
+ -66, 78, -60, -42, -38, -98, -34, 73,
+ -96, -5, -11, -114, -69, 47, -18, 122,
+ -87, 104, 121, -111, 21, -78, 7, 63,
+ -108, -62, 16, -119, 11, 34, 95, 33,
+ -128, 127, 93, -102, 90, -112, 50, 39,
+ 53, 62, -52, -25, -65, -9, -105, 3,
+ -1, 25, 48, -77, 72, -91, -75, -47,
+ -41, 94, -110, 42, -84, 86, -86, -58,
+ 79, -72, 56, -46, -106, -92, 125, -74,
+ 118, -4, 107, -30, -100, 116, 4, -15,
+ 69, -99, 112, 89, 100, 113, -121, 32,
+ -122, 91, -49, 101, -26, 45, -88, 2,
+ 27, 96, 37, -83, -82, -80, -71, -10,
+ 28, 70, 97, 105, 52, 64, 126, 15,
+ 85, 71, -93, 35, -35, 81, -81, 58,
+ -61, 92, -7, -50, -70, -59, -22, 38,
+ 44, 83, 13, 110, -123, 40, -124, 9,
+ -45, -33, -51, -12, 65, -127, 77, 82,
+ 106, -36, 55, -56, 108, -63, -85, -6,
+ 36, -31, 123, 8, 12, -67, -79, 74,
+ 120, -120, -107, -117, -29, 99, -24, 109,
+ -23, -53, -43, -2, 59, 0, 29, 57,
+ -14, -17, -73, 14, 102, 88, -48, -28,
+ -90, 119, 114, -8, -21, 117, 75, 10,
+ 49, 68, 80, -76, -113, -19, 31, 26,
+ -37, -103, -115, 51, - 97, 17, -125, 20 };
/** The output of this message digest when no data has been input. */
private static final String DIGEST0 = "8350E5A3E24C153DF2275C9F80692773";
@@ -114,9 +115,6 @@ public class MD2 extends BaseHash
*/
private byte[] work;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Creates a new MD2 digest ready for use. */
public MD2()
{
@@ -124,7 +122,7 @@ public class MD2 extends BaseHash
}
/**
- *
@@ -57,12 +56,9 @@ import gnu.java.security.util.Util;
* under section RFC 1319.i
bytes of value i
, where i
is the
* number of bytes to fill the last block of the message to
* BLOCK_LENGTH
bytes (or BLOCK_LENGTH
bytes when
- * the last block was completely full).BLOCK_LENGTH
bytes to the running digest.BLOCK_LENGTH
bytes to the running digest.
*
* @param in the byte array to take the BLOCK_LENGTH
bytes from.
* @param off the offset to start from in the given byte array.
*/
protected void transform(byte[] in, int off)
{
- // encryptBlock(in, off);
- // updateCheckSum(in, off);
updateCheckSumAndEncryptBlock(in, off);
}
- // Private instance methods ------------------------------------------------
-
- /**
- * Updates the checksum with the BLOCK_LENGTH
bytes from the
- * given array starting at off
.
- */
- /*
- private void updateCheckSum(byte[] in, int off) {
- byte l = checksum[BLOCK_LENGTH-1];
- for (int i = 0; i < BLOCK_LENGTH; i++) {
- byte b = in[off+i];
- // l = (byte)((checksum[i] & 0xFF) ^ (PI[((b & 0xFF) ^ (l & 0xFF))] & 0xFF));
- l = (byte)(checksum[i] ^ PI[(b ^ l) & 0xFF]);
- checksum[i] = l;
- }
- }
- */
/**
* Adds a new block (BLOCK_LENGTH
bytes) to the running digest
* from the given byte array starting from the given offset.
@@ -251,20 +214,17 @@ public class MD2 extends BaseHash
{
byte b = in[off + i];
work[BLOCK_LENGTH + i] = b;
- work[BLOCK_LENGTH * 2 + i] = (byte) (work[i] ^ b);
+ work[BLOCK_LENGTH * 2 + i] = (byte)(work[i] ^ b);
}
-
byte t = 0;
for (int i = 0; i < 18; i++)
{
for (int j = 0; j < 3 * BLOCK_LENGTH; j++)
{
- // t = (byte)((work[j] & 0xFF) ^ (PI[t & 0xFF] & 0xFF));
- t = (byte) (work[j] ^ PI[t & 0xFF]);
+ t = (byte)(work[j] ^ PI[t & 0xFF]);
work[j] = t;
}
- // t = (byte)((t + i) & 0xFF);
- t = (byte) (t + i);
+ t = (byte)(t + i);
}
}
@@ -278,24 +238,19 @@ public class MD2 extends BaseHash
{
byte b = in[off + i];
work[BLOCK_LENGTH + i] = b;
- // work[BLOCK_LENGTH*2+i] = (byte)((work[i] & 0xFF) ^ (b & 0xFF));
- work[BLOCK_LENGTH * 2 + i] = (byte) (work[i] ^ b);
- // l = (byte)((checksum[i] & 0xFF) ^ (PI[((b & 0xFF) ^ (l & 0xFF))] & 0xFF));
- l = (byte) (checksum[i] ^ PI[(b ^ l) & 0xFF]);
+ work[BLOCK_LENGTH * 2 + i] = (byte)(work[i] ^ b);
+ l = (byte)(checksum[i] ^ PI[(b ^ l) & 0xFF]);
checksum[i] = l;
}
-
byte t = 0;
for (int i = 0; i < 18; i++)
{
for (int j = 0; j < 3 * BLOCK_LENGTH; j++)
{
- // t = (byte)((work[j] & 0xFF) ^ (PI[t & 0xFF] & 0xFF));
- t = (byte) (work[j] ^ PI[t & 0xFF]);
+ t = (byte)(work[j] ^ PI[t & 0xFF]);
work[j] = t;
}
- // t = (byte)((t + i) & 0xFF);
- t = (byte) (t + i);
+ t = (byte)(t + i);
}
}
}
diff --git a/libjava/classpath/gnu/java/security/hash/MD4.java b/libjava/classpath/gnu/java/security/hash/MD4.java
index a09eb17..dfc1c6b 100644
--- a/libjava/classpath/gnu/java/security/hash/MD4.java
+++ b/libjava/classpath/gnu/java/security/hash/MD4.java
@@ -42,14 +42,13 @@ import gnu.java.security.Registry;
import gnu.java.security.util.Util;
/**
- *
*
*/
-public final class Whirlpool extends BaseHash
+public final class Whirlpool
+ extends BaseHash
{
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 3;
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Whirlpool.class.getName());
private static final int BLOCK_SIZE = 64; // inner block size in bytes
/** The digest of the 0-bit long message. */
@@ -83,22 +78,22 @@ public final class Whirlpool extends BaseHash
/** Whirlpool S-box; p. 19. */
private static final String S_box = // p. 19 [WHIRLPOOL]
- "\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152" +
- "\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57" +
- "\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85" +
- "\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8" +
- "\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333" +
- "\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0" +
- "\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE" +
- "\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d" +
- "\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF" +
- "\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A" +
- "\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c" +
- "\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04" +
- "\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB" +
- "\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9" +
- "\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1" +
- "\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886";
+ "\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152"
+ + "\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57"
+ + "\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85"
+ + "\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8"
+ + "\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333"
+ + "\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0"
+ + "\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE"
+ + "\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d"
+ + "\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF"
+ + "\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A"
+ + "\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c"
+ + "\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04"
+ + "\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB"
+ + "\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9"
+ + "\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1"
+ + "\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886";
/** The 64-bit lookup tables; section 7.1 p. 13. */
private static final long[] T0 = new long[256];
@@ -130,12 +125,9 @@ public final class Whirlpool extends BaseHash
/** work area for holding block cipher's intermediate values. */
private long w0, w1, w2, w3, w4, w5, w6, w7;
- // Static code - to intialise lookup tables --------------------------------
-
static
{
long time = System.currentTimeMillis();
-
int ROOT = 0x11D; // para. 2.1 [WHIRLPOOL]
int i, r, j;
long s1, s2, s4, s5, s8, s9, t;
@@ -171,7 +163,6 @@ public final class Whirlpool extends BaseHash
T6[i] = t >>> 48 | t << 16;
T7[i] = t >>> 56 | t << 8;
}
-
for (r = 0, i = 0; r < R; )
rc[r++] = (T0[i++] & 0xFF00000000000000L)
^ (T1[i++] & 0x00FF000000000000L)
@@ -181,103 +172,91 @@ public final class Whirlpool extends BaseHash
^ (T5[i++] & 0x0000000000FF0000L)
^ (T6[i++] & 0x000000000000FF00L)
^ (T7[i++] & 0x00000000000000FFL);
-
time = System.currentTimeMillis() - time;
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static data");
- System.out.println();
-
- System.out.println();
- System.out.println("T0[]:");
+ log.fine("Static data");
+ log.fine("T0[]:");
+ StringBuilder sb;
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T0[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T0[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T1[]:");
+ log.fine("T1[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T1[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T1[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T2[]:");
+ log.fine("T2[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T2[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T2[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T3[]:");
+ log.fine("T3[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T3[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T3[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T4[]:");
+ log.fine("\nT4[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T4[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T4[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T5[]:");
+ log.fine("T5[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T6[]:");
+ log.fine("T6[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T7[]:");
+ log.fine("T7[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
+ sb.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
- System.out.println();
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("rc[]:");
+ log.fine("rc[]:");
for (i = 0; i < R; i++)
- System.out.println("0x" + Util.toString(rc[i]));
-
- System.out.println();
+ log.fine("0x" + Util.toString(rc[i]));
- System.out.println();
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("Total initialization time: " + time + " ms.");
}
}
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Whirlpool()
{
@@ -285,7 +264,7 @@ public final class Whirlpool extends BaseHash
}
/**
- *
@@ -58,12 +57,9 @@ import gnu.java.security.util.Util;
*
* @author Casey Marshall (rsdio@metastatic.org)
*/
-public class MD4 extends BaseHash
+public class MD4
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** An MD4 message digest is always 128-bits long, or 16 bytes. */
private static final int DIGEST_LENGTH = 16;
@@ -86,13 +82,9 @@ public class MD4 extends BaseHash
private int a, b, c, d;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- * 0
, and creates a new block of 512
bits.
- *
*
*/
-public class MD5 extends BaseHash
+public class MD5
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final int BLOCK_SIZE = 64; // inner block size in bytes
private static final String DIGEST0 = "D41D8CD98F00B204E9800998ECF8427E";
@@ -72,9 +68,6 @@ public class MD5 extends BaseHash
/** 128-bit interim result. */
private int h0, h1, h2, h3;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public MD5()
{
@@ -82,7 +75,7 @@ public class MD5 extends BaseHash
}
/**
- *
* R. Rivest.
*
*/
-public class RipeMD128 extends BaseHash
+public class RipeMD128
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final int BLOCK_SIZE = 64; // inner block size in bytes
private static final String DIGEST0 = "CDF26213A150DC3ECB610F18F6B38B46";
/** Constants for the transform method. */
// selection of message word
- private static final int[] R = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
- 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0,
- 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8,
- 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10,
- 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 };
-
- private static final int[] Rp = { 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1,
- 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14,
- 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14,
- 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4,
- 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 };
+ private static final int[] R = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
+ 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
+ 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 };
+
+ private static final int[] Rp = {
+ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
+ 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
+ 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
+ 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 };
// amount for rotate left (rol)
- private static final int[] S = { 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15,
- 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12,
- 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9,
- 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12,
- 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5,
- 12 };
-
- private static final int[] Sp = { 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11,
- 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11,
- 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8,
- 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15,
- 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5,
- 15, 8 };
+ private static final int[] S = {
+ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
+ 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
+ 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
+ 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12 };
+
+ private static final int[] Sp = {
+ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
+ 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
+ 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
+ 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8 };
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
@@ -100,9 +94,6 @@ public class RipeMD128 extends BaseHash
/** 512 bits work buffer = 16 x 32-bit words */
private int[] X = new int[16];
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public RipeMD128()
{
@@ -110,7 +101,7 @@ public class RipeMD128 extends BaseHash
}
/**
- *
* Hans Dobbertin, Antoon Bosselaers and Bart Preneel.
*
*/
-public class RipeMD160 extends BaseHash
+public class RipeMD160
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final int BLOCK_SIZE = 64; // inner block size in bytes
private static final String DIGEST0 = "9C1185A5C5E9FC54612808977EE8F548B2258D31";
// selection of message word
- private static final int[] R = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
- 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0,
- 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8,
- 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10,
- 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0,
- 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15,
- 13 };
-
- private static final int[] Rp = { 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1,
- 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14,
- 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14,
- 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4,
- 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
- 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0,
- 3, 9, 11 };
+ private static final int[] R = {
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
+ 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
+ 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
+ 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 };
+
+ private static final int[] Rp = {
+ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
+ 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
+ 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
+ 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
+ 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 };
// amount for rotate left (rol)
- private static final int[] S = { 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15,
- 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12,
- 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9,
- 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12,
- 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5,
- 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13,
- 14, 11, 8, 5, 6 };
-
- private static final int[] Sp = { 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11,
- 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11,
- 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8,
- 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15,
- 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5,
- 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6,
- 5, 15, 13, 11, 11 };
+ private static final int[] S = {
+ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
+ 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
+ 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
+ 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
+ 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 };
+
+ private static final int[] Sp = {
+ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
+ 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
+ 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
+ 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
+ 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 };
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
@@ -105,9 +97,6 @@ public class RipeMD160 extends BaseHash
/** 512 bits work buffer = 16 x 32-bit words */
private int[] X = new int[16];
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public RipeMD160()
{
@@ -115,7 +104,7 @@ public class RipeMD160 extends BaseHash
}
/**
- *
* Hans Dobbertin, Antoon Bosselaers and Bart Preneel.
*
*/
-public class Sha160 extends BaseHash
+public class Sha160
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final int BLOCK_SIZE = 64; // inner block size in bytes
private static final String DIGEST0 = "A9993E364706816ABA3E25717850C26C9CD0D89D";
@@ -85,9 +81,6 @@ public class Sha160 extends BaseHash
/** 160-bit interim result. */
private int h0, h1, h2, h3, h4;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Sha160()
{
@@ -95,7 +88,7 @@ public class Sha160 extends BaseHash
}
/**
- *
@@ -67,12 +66,9 @@ import gnu.java.security.util.Util;
*
*
*/
-public class Sha256 extends BaseHash
+public class Sha256
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
- private static final int[] k = { 0x428a2f98, 0x71374491, 0xb5c0fbcf,
- 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
- 0x923f82a4, 0xab1c5ed5, 0xd807aa98,
- 0x12835b01, 0x243185be, 0x550c7dc3,
- 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
- 0xc19bf174, 0xe49b69c1, 0xefbe4786,
- 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
- 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
- 0x983e5152, 0xa831c66d, 0xb00327c8,
- 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
- 0x06ca6351, 0x14292967, 0x27b70a85,
- 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
- 0x650a7354, 0x766a0abb, 0x81c2c92e,
- 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
- 0xc24b8b70, 0xc76c51a3, 0xd192e819,
- 0xd6990624, 0xf40e3585, 0x106aa070,
- 0x19a4c116, 0x1e376c08, 0x2748774c,
- 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
- 0x5b9cca4f, 0x682e6ff3, 0x748f82ee,
- 0x78a5636f, 0x84c87814, 0x8cc70208,
- 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
- 0xc67178f2 };
+ private static final int[] k = {
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
+ 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
+ 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
+ 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
+ 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
+ 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
+ };
private static final int BLOCK_SIZE = 64; // inner block size in bytes
- private static final String DIGEST0 = "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD";
+ private static final String DIGEST0 =
+ "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD";
private static final int[] w = new int[64];
@@ -91,9 +86,6 @@ public class Sha256 extends BaseHash
/** 256-bit interim result. */
private int h0, h1, h2, h3, h4, h5, h6, h7;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Sha256()
{
@@ -101,7 +93,7 @@ public class Sha256 extends BaseHash
}
/**
- *
*
*/
-public class Sha384 extends BaseHash
+public class Sha384
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- private static final long[] k = { 0x428a2f98d728ae22L, 0x7137449123ef65cdL,
- 0xb5c0fbcfec4d3b2fL, 0xe9b5dba58189dbbcL,
- 0x3956c25bf348b538L, 0x59f111f1b605d019L,
- 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L,
- 0xd807aa98a3030242L, 0x12835b0145706fbeL,
- 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L,
- 0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L,
- 0x9bdc06a725c71235L, 0xc19bf174cf692694L,
- 0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L,
- 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L,
- 0x2de92c6f592b0275L, 0x4a7484aa6ea6e483L,
- 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L,
- 0x983e5152ee66dfabL, 0xa831c66d2db43210L,
- 0xb00327c898fb213fL, 0xbf597fc7beef0ee4L,
- 0xc6e00bf33da88fc2L, 0xd5a79147930aa725L,
- 0x06ca6351e003826fL, 0x142929670a0e6e70L,
- 0x27b70a8546d22ffcL, 0x2e1b21385c26c926L,
- 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL,
- 0x650a73548baf63deL, 0x766a0abb3c77b2a8L,
- 0x81c2c92e47edaee6L, 0x92722c851482353bL,
- 0xa2bfe8a14cf10364L, 0xa81a664bbc423001L,
- 0xc24b8b70d0f89791L, 0xc76c51a30654be30L,
- 0xd192e819d6ef5218L, 0xd69906245565a910L,
- 0xf40e35855771202aL, 0x106aa07032bbd1b8L,
- 0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L,
- 0x2748774cdf8eeb99L, 0x34b0bcb5e19b48a8L,
- 0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL,
- 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L,
- 0x748f82ee5defb2fcL, 0x78a5636f43172f60L,
- 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL,
- 0x90befffa23631e28L, 0xa4506cebde82bde9L,
- 0xbef9a3f7b2c67915L, 0xc67178f2e372532bL,
- 0xca273eceea26619cL, 0xd186b8c721c0c207L,
- 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L,
- 0x06f067aa72176fbaL, 0x0a637dc5a2c898a6L,
- 0x113f9804bef90daeL, 0x1b710b35131c471bL,
- 0x28db77f523047d84L, 0x32caab7b40c72493L,
- 0x3c9ebe0a15c9bebcL, 0x431d67c49c100d4cL,
- 0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL,
- 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L };
+ private static final long[] k = {
+ 0x428a2f98d728ae22L, 0x7137449123ef65cdL, 0xb5c0fbcfec4d3b2fL,
+ 0xe9b5dba58189dbbcL, 0x3956c25bf348b538L, 0x59f111f1b605d019L,
+ 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L, 0xd807aa98a3030242L,
+ 0x12835b0145706fbeL, 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L,
+ 0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L, 0x9bdc06a725c71235L,
+ 0xc19bf174cf692694L, 0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L,
+ 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L, 0x2de92c6f592b0275L,
+ 0x4a7484aa6ea6e483L, 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L,
+ 0x983e5152ee66dfabL, 0xa831c66d2db43210L, 0xb00327c898fb213fL,
+ 0xbf597fc7beef0ee4L, 0xc6e00bf33da88fc2L, 0xd5a79147930aa725L,
+ 0x06ca6351e003826fL, 0x142929670a0e6e70L, 0x27b70a8546d22ffcL,
+ 0x2e1b21385c26c926L, 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL,
+ 0x650a73548baf63deL, 0x766a0abb3c77b2a8L, 0x81c2c92e47edaee6L,
+ 0x92722c851482353bL, 0xa2bfe8a14cf10364L, 0xa81a664bbc423001L,
+ 0xc24b8b70d0f89791L, 0xc76c51a30654be30L, 0xd192e819d6ef5218L,
+ 0xd69906245565a910L, 0xf40e35855771202aL, 0x106aa07032bbd1b8L,
+ 0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L, 0x2748774cdf8eeb99L,
+ 0x34b0bcb5e19b48a8L, 0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL,
+ 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L, 0x748f82ee5defb2fcL,
+ 0x78a5636f43172f60L, 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL,
+ 0x90befffa23631e28L, 0xa4506cebde82bde9L, 0xbef9a3f7b2c67915L,
+ 0xc67178f2e372532bL, 0xca273eceea26619cL, 0xd186b8c721c0c207L,
+ 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L, 0x06f067aa72176fbaL,
+ 0x0a637dc5a2c898a6L, 0x113f9804bef90daeL, 0x1b710b35131c471bL,
+ 0x28db77f523047d84L, 0x32caab7b40c72493L, 0x3c9ebe0a15c9bebcL,
+ 0x431d67c49c100d4cL, 0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL,
+ 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L };
private static final int BLOCK_SIZE = 128; // inner block size in bytes
- private static final String DIGEST0 = "CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED"
- + "8086072BA1E7CC2358BAECA134C825A7";
+ private static final String DIGEST0 =
+ "CB00753F45A35E8BB5A03D699AC65007272C32AB0EDED1631A8B605A43FF5BED"
+ + "8086072BA1E7CC2358BAECA134C825A7";
private static final long[] w = new long[80];
@@ -111,9 +97,6 @@ public class Sha384 extends BaseHash
/** 512-bit interim result. */
private long h0, h1, h2, h3, h4, h5, h6, h7;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Sha384()
{
@@ -121,7 +104,7 @@ public class Sha384 extends BaseHash
}
/**
- *
*
*/
-public class Sha512 extends BaseHash
+public class Sha512
+ extends BaseHash
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- private static final long[] k = { 0x428a2f98d728ae22L, 0x7137449123ef65cdL,
- 0xb5c0fbcfec4d3b2fL, 0xe9b5dba58189dbbcL,
- 0x3956c25bf348b538L, 0x59f111f1b605d019L,
- 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L,
- 0xd807aa98a3030242L, 0x12835b0145706fbeL,
- 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L,
- 0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L,
- 0x9bdc06a725c71235L, 0xc19bf174cf692694L,
- 0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L,
- 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L,
- 0x2de92c6f592b0275L, 0x4a7484aa6ea6e483L,
- 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L,
- 0x983e5152ee66dfabL, 0xa831c66d2db43210L,
- 0xb00327c898fb213fL, 0xbf597fc7beef0ee4L,
- 0xc6e00bf33da88fc2L, 0xd5a79147930aa725L,
- 0x06ca6351e003826fL, 0x142929670a0e6e70L,
- 0x27b70a8546d22ffcL, 0x2e1b21385c26c926L,
- 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL,
- 0x650a73548baf63deL, 0x766a0abb3c77b2a8L,
- 0x81c2c92e47edaee6L, 0x92722c851482353bL,
- 0xa2bfe8a14cf10364L, 0xa81a664bbc423001L,
- 0xc24b8b70d0f89791L, 0xc76c51a30654be30L,
- 0xd192e819d6ef5218L, 0xd69906245565a910L,
- 0xf40e35855771202aL, 0x106aa07032bbd1b8L,
- 0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L,
- 0x2748774cdf8eeb99L, 0x34b0bcb5e19b48a8L,
- 0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL,
- 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L,
- 0x748f82ee5defb2fcL, 0x78a5636f43172f60L,
- 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL,
- 0x90befffa23631e28L, 0xa4506cebde82bde9L,
- 0xbef9a3f7b2c67915L, 0xc67178f2e372532bL,
- 0xca273eceea26619cL, 0xd186b8c721c0c207L,
- 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L,
- 0x06f067aa72176fbaL, 0x0a637dc5a2c898a6L,
- 0x113f9804bef90daeL, 0x1b710b35131c471bL,
- 0x28db77f523047d84L, 0x32caab7b40c72493L,
- 0x3c9ebe0a15c9bebcL, 0x431d67c49c100d4cL,
- 0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL,
- 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L };
+ private static final long[] k = {
+ 0x428a2f98d728ae22L, 0x7137449123ef65cdL, 0xb5c0fbcfec4d3b2fL,
+ 0xe9b5dba58189dbbcL, 0x3956c25bf348b538L, 0x59f111f1b605d019L,
+ 0x923f82a4af194f9bL, 0xab1c5ed5da6d8118L, 0xd807aa98a3030242L,
+ 0x12835b0145706fbeL, 0x243185be4ee4b28cL, 0x550c7dc3d5ffb4e2L,
+ 0x72be5d74f27b896fL, 0x80deb1fe3b1696b1L, 0x9bdc06a725c71235L,
+ 0xc19bf174cf692694L, 0xe49b69c19ef14ad2L, 0xefbe4786384f25e3L,
+ 0x0fc19dc68b8cd5b5L, 0x240ca1cc77ac9c65L, 0x2de92c6f592b0275L,
+ 0x4a7484aa6ea6e483L, 0x5cb0a9dcbd41fbd4L, 0x76f988da831153b5L,
+ 0x983e5152ee66dfabL, 0xa831c66d2db43210L, 0xb00327c898fb213fL,
+ 0xbf597fc7beef0ee4L, 0xc6e00bf33da88fc2L, 0xd5a79147930aa725L,
+ 0x06ca6351e003826fL, 0x142929670a0e6e70L, 0x27b70a8546d22ffcL,
+ 0x2e1b21385c26c926L, 0x4d2c6dfc5ac42aedL, 0x53380d139d95b3dfL,
+ 0x650a73548baf63deL, 0x766a0abb3c77b2a8L, 0x81c2c92e47edaee6L,
+ 0x92722c851482353bL, 0xa2bfe8a14cf10364L, 0xa81a664bbc423001L,
+ 0xc24b8b70d0f89791L, 0xc76c51a30654be30L, 0xd192e819d6ef5218L,
+ 0xd69906245565a910L, 0xf40e35855771202aL, 0x106aa07032bbd1b8L,
+ 0x19a4c116b8d2d0c8L, 0x1e376c085141ab53L, 0x2748774cdf8eeb99L,
+ 0x34b0bcb5e19b48a8L, 0x391c0cb3c5c95a63L, 0x4ed8aa4ae3418acbL,
+ 0x5b9cca4f7763e373L, 0x682e6ff3d6b2b8a3L, 0x748f82ee5defb2fcL,
+ 0x78a5636f43172f60L, 0x84c87814a1f0ab72L, 0x8cc702081a6439ecL,
+ 0x90befffa23631e28L, 0xa4506cebde82bde9L, 0xbef9a3f7b2c67915L,
+ 0xc67178f2e372532bL, 0xca273eceea26619cL, 0xd186b8c721c0c207L,
+ 0xeada7dd6cde0eb1eL, 0xf57d4f7fee6ed178L, 0x06f067aa72176fbaL,
+ 0x0a637dc5a2c898a6L, 0x113f9804bef90daeL, 0x1b710b35131c471bL,
+ 0x28db77f523047d84L, 0x32caab7b40c72493L, 0x3c9ebe0a15c9bebcL,
+ 0x431d67c49c100d4cL, 0x4cc5d4becb3e42b6L, 0x597f299cfc657e2aL,
+ 0x5fcb6fab3ad6faecL, 0x6c44198c4a475817L };
private static final int BLOCK_SIZE = 128; // inner block size in bytes
- private static final String DIGEST0 = "DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A"
- + "2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F";
+ private static final String DIGEST0 =
+ "DDAF35A193617ABACC417349AE20413112E6FA4E89A97EA20A9EEEE64B55D39A"
+ + "2192992A274FC1A836BA3C23A3FEEBBD454D4423643CE80E2A9AC94FA54CA49F";
private static final long[] w = new long[80];
@@ -111,9 +97,6 @@ public class Sha512 extends BaseHash
/** 512-bit interim result. */
private long h0, h1, h2, h3, h4, h5, h6, h7;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Sha512()
{
@@ -121,7 +104,7 @@ public class Sha512 extends BaseHash
}
/**
- *
*
*/
-public class Tiger extends BaseHash
+public class Tiger
+ extends BaseHash
{
-
- // Constants and variables.
- // -----------------------------------------------------------------------
-
private static final int HASH_SIZE = 24;
private static final int BLOCK_SIZE = 64;
/** Result when no data has been input. */
- private static final String DIGEST0 = "3293AC630C13F0245F92BBB1766E16167A4E58492DDE73F3";
+ private static final String DIGEST0 =
+ "3293AC630C13F0245F92BBB1766E16167A4E58492DDE73F3";
private static final long A = 0x0123456789ABCDEFL;
@@ -77,524 +75,360 @@ public class Tiger extends BaseHash
private static final long C = 0xF096A5B4C3B2E187L;
/** S-Box T1. */
- private static final long[] T1 = { 0x02AAB17CF7E90C5EL, 0xAC424B03E243A8ECL,
- 0x72CD5BE30DD5FCD3L, 0x6D019B93F6F97F3AL,
- 0xCD9978FFD21F9193L, 0x7573A1C9708029E2L,
- 0xB164326B922A83C3L, 0x46883EEE04915870L,
- 0xEAACE3057103ECE6L, 0xC54169B808A3535CL,
- 0x4CE754918DDEC47CL, 0x0AA2F4DFDC0DF40CL,
- 0x10B76F18A74DBEFAL, 0xC6CCB6235AD1AB6AL,
- 0x13726121572FE2FFL, 0x1A488C6F199D921EL,
- 0x4BC9F9F4DA0007CAL, 0x26F5E6F6E85241C7L,
- 0x859079DBEA5947B6L, 0x4F1885C5C99E8C92L,
- 0xD78E761EA96F864BL, 0x8E36428C52B5C17DL,
- 0x69CF6827373063C1L, 0xB607C93D9BB4C56EL,
- 0x7D820E760E76B5EAL, 0x645C9CC6F07FDC42L,
- 0xBF38A078243342E0L, 0x5F6B343C9D2E7D04L,
- 0xF2C28AEB600B0EC6L, 0x6C0ED85F7254BCACL,
- 0x71592281A4DB4FE5L, 0x1967FA69CE0FED9FL,
- 0xFD5293F8B96545DBL, 0xC879E9D7F2A7600BL,
- 0x860248920193194EL, 0xA4F9533B2D9CC0B3L,
- 0x9053836C15957613L, 0xDB6DCF8AFC357BF1L,
- 0x18BEEA7A7A370F57L, 0x037117CA50B99066L,
- 0x6AB30A9774424A35L, 0xF4E92F02E325249BL,
- 0x7739DB07061CCAE1L, 0xD8F3B49CECA42A05L,
- 0xBD56BE3F51382F73L, 0x45FAED5843B0BB28L,
- 0x1C813D5C11BF1F83L, 0x8AF0E4B6D75FA169L,
- 0x33EE18A487AD9999L, 0x3C26E8EAB1C94410L,
- 0xB510102BC0A822F9L, 0x141EEF310CE6123BL,
- 0xFC65B90059DDB154L, 0xE0158640C5E0E607L,
- 0x884E079826C3A3CFL, 0x930D0D9523C535FDL,
- 0x35638D754E9A2B00L, 0x4085FCCF40469DD5L,
- 0xC4B17AD28BE23A4CL, 0xCAB2F0FC6A3E6A2EL,
- 0x2860971A6B943FCDL, 0x3DDE6EE212E30446L,
- 0x6222F32AE01765AEL, 0x5D550BB5478308FEL,
- 0xA9EFA98DA0EDA22AL, 0xC351A71686C40DA7L,
- 0x1105586D9C867C84L, 0xDCFFEE85FDA22853L,
- 0xCCFBD0262C5EEF76L, 0xBAF294CB8990D201L,
- 0xE69464F52AFAD975L, 0x94B013AFDF133E14L,
- 0x06A7D1A32823C958L, 0x6F95FE5130F61119L,
- 0xD92AB34E462C06C0L, 0xED7BDE33887C71D2L,
- 0x79746D6E6518393EL, 0x5BA419385D713329L,
- 0x7C1BA6B948A97564L, 0x31987C197BFDAC67L,
- 0xDE6C23C44B053D02L, 0x581C49FED002D64DL,
- 0xDD474D6338261571L, 0xAA4546C3E473D062L,
- 0x928FCE349455F860L, 0x48161BBACAAB94D9L,
- 0x63912430770E6F68L, 0x6EC8A5E602C6641CL,
- 0x87282515337DDD2BL, 0x2CDA6B42034B701BL,
- 0xB03D37C181CB096DL, 0xE108438266C71C6FL,
- 0x2B3180C7EB51B255L, 0xDF92B82F96C08BBCL,
- 0x5C68C8C0A632F3BAL, 0x5504CC861C3D0556L,
- 0xABBFA4E55FB26B8FL, 0x41848B0AB3BACEB4L,
- 0xB334A273AA445D32L, 0xBCA696F0A85AD881L,
- 0x24F6EC65B528D56CL, 0x0CE1512E90F4524AL,
- 0x4E9DD79D5506D35AL, 0x258905FAC6CE9779L,
- 0x2019295B3E109B33L, 0xF8A9478B73A054CCL,
- 0x2924F2F934417EB0L, 0x3993357D536D1BC4L,
- 0x38A81AC21DB6FF8BL, 0x47C4FBF17D6016BFL,
- 0x1E0FAADD7667E3F5L, 0x7ABCFF62938BEB96L,
- 0xA78DAD948FC179C9L, 0x8F1F98B72911E50DL,
- 0x61E48EAE27121A91L, 0x4D62F7AD31859808L,
- 0xECEBA345EF5CEAEBL, 0xF5CEB25EBC9684CEL,
- 0xF633E20CB7F76221L, 0xA32CDF06AB8293E4L,
- 0x985A202CA5EE2CA4L, 0xCF0B8447CC8A8FB1L,
- 0x9F765244979859A3L, 0xA8D516B1A1240017L,
- 0x0BD7BA3EBB5DC726L, 0xE54BCA55B86ADB39L,
- 0x1D7A3AFD6C478063L, 0x519EC608E7669EDDL,
- 0x0E5715A2D149AA23L, 0x177D4571848FF194L,
- 0xEEB55F3241014C22L, 0x0F5E5CA13A6E2EC2L,
- 0x8029927B75F5C361L, 0xAD139FABC3D6E436L,
- 0x0D5DF1A94CCF402FL, 0x3E8BD948BEA5DFC8L,
- 0xA5A0D357BD3FF77EL, 0xA2D12E251F74F645L,
- 0x66FD9E525E81A082L, 0x2E0C90CE7F687A49L,
- 0xC2E8BCBEBA973BC5L, 0x000001BCE509745FL,
- 0x423777BBE6DAB3D6L, 0xD1661C7EAEF06EB5L,
- 0xA1781F354DAACFD8L, 0x2D11284A2B16AFFCL,
- 0xF1FC4F67FA891D1FL, 0x73ECC25DCB920ADAL,
- 0xAE610C22C2A12651L, 0x96E0A810D356B78AL,
- 0x5A9A381F2FE7870FL, 0xD5AD62EDE94E5530L,
- 0xD225E5E8368D1427L, 0x65977B70C7AF4631L,
- 0x99F889B2DE39D74FL, 0x233F30BF54E1D143L,
- 0x9A9675D3D9A63C97L, 0x5470554FF334F9A8L,
- 0x166ACB744A4F5688L, 0x70C74CAAB2E4AEADL,
- 0xF0D091646F294D12L, 0x57B82A89684031D1L,
- 0xEFD95A5A61BE0B6BL, 0x2FBD12E969F2F29AL,
- 0x9BD37013FEFF9FE8L, 0x3F9B0404D6085A06L,
- 0x4940C1F3166CFE15L, 0x09542C4DCDF3DEFBL,
- 0xB4C5218385CD5CE3L, 0xC935B7DC4462A641L,
- 0x3417F8A68ED3B63FL, 0xB80959295B215B40L,
- 0xF99CDAEF3B8C8572L, 0x018C0614F8FCB95DL,
- 0x1B14ACCD1A3ACDF3L, 0x84D471F200BB732DL,
- 0xC1A3110E95E8DA16L, 0x430A7220BF1A82B8L,
- 0xB77E090D39DF210EL, 0x5EF4BD9F3CD05E9DL,
- 0x9D4FF6DA7E57A444L, 0xDA1D60E183D4A5F8L,
- 0xB287C38417998E47L, 0xFE3EDC121BB31886L,
- 0xC7FE3CCC980CCBEFL, 0xE46FB590189BFD03L,
- 0x3732FD469A4C57DCL, 0x7EF700A07CF1AD65L,
- 0x59C64468A31D8859L, 0x762FB0B4D45B61F6L,
- 0x155BAED099047718L, 0x68755E4C3D50BAA6L,
- 0xE9214E7F22D8B4DFL, 0x2ADDBF532EAC95F4L,
- 0x32AE3909B4BD0109L, 0x834DF537B08E3450L,
- 0xFA209DA84220728DL, 0x9E691D9B9EFE23F7L,
- 0x0446D288C4AE8D7FL, 0x7B4CC524E169785BL,
- 0x21D87F0135CA1385L, 0xCEBB400F137B8AA5L,
- 0x272E2B66580796BEL, 0x3612264125C2B0DEL,
- 0x057702BDAD1EFBB2L, 0xD4BABB8EACF84BE9L,
- 0x91583139641BC67BL, 0x8BDC2DE08036E024L,
- 0x603C8156F49F68EDL, 0xF7D236F7DBEF5111L,
- 0x9727C4598AD21E80L, 0xA08A0896670A5FD7L,
- 0xCB4A8F4309EBA9CBL, 0x81AF564B0F7036A1L,
- 0xC0B99AA778199ABDL, 0x959F1EC83FC8E952L,
- 0x8C505077794A81B9L, 0x3ACAAF8F056338F0L,
- 0x07B43F50627A6778L, 0x4A44AB49F5ECCC77L,
- 0x3BC3D6E4B679EE98L, 0x9CC0D4D1CF14108CL,
- 0x4406C00B206BC8A0L, 0x82A18854C8D72D89L,
- 0x67E366B35C3C432CL, 0xB923DD61102B37F2L,
- 0x56AB2779D884271DL, 0xBE83E1B0FF1525AFL,
- 0xFB7C65D4217E49A9L, 0x6BDBE0E76D48E7D4L,
- 0x08DF828745D9179EL, 0x22EA6A9ADD53BD34L,
- 0xE36E141C5622200AL, 0x7F805D1B8CB750EEL,
- 0xAFE5C7A59F58E837L, 0xE27F996A4FB1C23CL,
- 0xD3867DFB0775F0D0L, 0xD0E673DE6E88891AL,
- 0x123AEB9EAFB86C25L, 0x30F1D5D5C145B895L,
- 0xBB434A2DEE7269E7L, 0x78CB67ECF931FA38L,
- 0xF33B0372323BBF9CL, 0x52D66336FB279C74L,
- 0x505F33AC0AFB4EAAL, 0xE8A5CD99A2CCE187L,
- 0x534974801E2D30BBL, 0x8D2D5711D5876D90L,
- 0x1F1A412891BC038EL, 0xD6E2E71D82E56648L,
- 0x74036C3A497732B7L, 0x89B67ED96361F5ABL,
- 0xFFED95D8F1EA02A2L, 0xE72B3BD61464D43DL,
- 0xA6300F170BDC4820L, 0xEBC18760ED78A77AL };
+ private static final long[] T1 = {
+ 0x02AAB17CF7E90C5EL, 0xAC424B03E243A8ECL, 0x72CD5BE30DD5FCD3L,
+ 0x6D019B93F6F97F3AL, 0xCD9978FFD21F9193L, 0x7573A1C9708029E2L,
+ 0xB164326B922A83C3L, 0x46883EEE04915870L, 0xEAACE3057103ECE6L,
+ 0xC54169B808A3535CL, 0x4CE754918DDEC47CL, 0x0AA2F4DFDC0DF40CL,
+ 0x10B76F18A74DBEFAL, 0xC6CCB6235AD1AB6AL, 0x13726121572FE2FFL,
+ 0x1A488C6F199D921EL, 0x4BC9F9F4DA0007CAL, 0x26F5E6F6E85241C7L,
+ 0x859079DBEA5947B6L, 0x4F1885C5C99E8C92L, 0xD78E761EA96F864BL,
+ 0x8E36428C52B5C17DL, 0x69CF6827373063C1L, 0xB607C93D9BB4C56EL,
+ 0x7D820E760E76B5EAL, 0x645C9CC6F07FDC42L, 0xBF38A078243342E0L,
+ 0x5F6B343C9D2E7D04L, 0xF2C28AEB600B0EC6L, 0x6C0ED85F7254BCACL,
+ 0x71592281A4DB4FE5L, 0x1967FA69CE0FED9FL, 0xFD5293F8B96545DBL,
+ 0xC879E9D7F2A7600BL, 0x860248920193194EL, 0xA4F9533B2D9CC0B3L,
+ 0x9053836C15957613L, 0xDB6DCF8AFC357BF1L, 0x18BEEA7A7A370F57L,
+ 0x037117CA50B99066L, 0x6AB30A9774424A35L, 0xF4E92F02E325249BL,
+ 0x7739DB07061CCAE1L, 0xD8F3B49CECA42A05L, 0xBD56BE3F51382F73L,
+ 0x45FAED5843B0BB28L, 0x1C813D5C11BF1F83L, 0x8AF0E4B6D75FA169L,
+ 0x33EE18A487AD9999L, 0x3C26E8EAB1C94410L, 0xB510102BC0A822F9L,
+ 0x141EEF310CE6123BL, 0xFC65B90059DDB154L, 0xE0158640C5E0E607L,
+ 0x884E079826C3A3CFL, 0x930D0D9523C535FDL, 0x35638D754E9A2B00L,
+ 0x4085FCCF40469DD5L, 0xC4B17AD28BE23A4CL, 0xCAB2F0FC6A3E6A2EL,
+ 0x2860971A6B943FCDL, 0x3DDE6EE212E30446L, 0x6222F32AE01765AEL,
+ 0x5D550BB5478308FEL, 0xA9EFA98DA0EDA22AL, 0xC351A71686C40DA7L,
+ 0x1105586D9C867C84L, 0xDCFFEE85FDA22853L, 0xCCFBD0262C5EEF76L,
+ 0xBAF294CB8990D201L, 0xE69464F52AFAD975L, 0x94B013AFDF133E14L,
+ 0x06A7D1A32823C958L, 0x6F95FE5130F61119L, 0xD92AB34E462C06C0L,
+ 0xED7BDE33887C71D2L, 0x79746D6E6518393EL, 0x5BA419385D713329L,
+ 0x7C1BA6B948A97564L, 0x31987C197BFDAC67L, 0xDE6C23C44B053D02L,
+ 0x581C49FED002D64DL, 0xDD474D6338261571L, 0xAA4546C3E473D062L,
+ 0x928FCE349455F860L, 0x48161BBACAAB94D9L, 0x63912430770E6F68L,
+ 0x6EC8A5E602C6641CL, 0x87282515337DDD2BL, 0x2CDA6B42034B701BL,
+ 0xB03D37C181CB096DL, 0xE108438266C71C6FL, 0x2B3180C7EB51B255L,
+ 0xDF92B82F96C08BBCL, 0x5C68C8C0A632F3BAL, 0x5504CC861C3D0556L,
+ 0xABBFA4E55FB26B8FL, 0x41848B0AB3BACEB4L, 0xB334A273AA445D32L,
+ 0xBCA696F0A85AD881L, 0x24F6EC65B528D56CL, 0x0CE1512E90F4524AL,
+ 0x4E9DD79D5506D35AL, 0x258905FAC6CE9779L, 0x2019295B3E109B33L,
+ 0xF8A9478B73A054CCL, 0x2924F2F934417EB0L, 0x3993357D536D1BC4L,
+ 0x38A81AC21DB6FF8BL, 0x47C4FBF17D6016BFL, 0x1E0FAADD7667E3F5L,
+ 0x7ABCFF62938BEB96L, 0xA78DAD948FC179C9L, 0x8F1F98B72911E50DL,
+ 0x61E48EAE27121A91L, 0x4D62F7AD31859808L, 0xECEBA345EF5CEAEBL,
+ 0xF5CEB25EBC9684CEL, 0xF633E20CB7F76221L, 0xA32CDF06AB8293E4L,
+ 0x985A202CA5EE2CA4L, 0xCF0B8447CC8A8FB1L, 0x9F765244979859A3L,
+ 0xA8D516B1A1240017L, 0x0BD7BA3EBB5DC726L, 0xE54BCA55B86ADB39L,
+ 0x1D7A3AFD6C478063L, 0x519EC608E7669EDDL, 0x0E5715A2D149AA23L,
+ 0x177D4571848FF194L, 0xEEB55F3241014C22L, 0x0F5E5CA13A6E2EC2L,
+ 0x8029927B75F5C361L, 0xAD139FABC3D6E436L, 0x0D5DF1A94CCF402FL,
+ 0x3E8BD948BEA5DFC8L, 0xA5A0D357BD3FF77EL, 0xA2D12E251F74F645L,
+ 0x66FD9E525E81A082L, 0x2E0C90CE7F687A49L, 0xC2E8BCBEBA973BC5L,
+ 0x000001BCE509745FL, 0x423777BBE6DAB3D6L, 0xD1661C7EAEF06EB5L,
+ 0xA1781F354DAACFD8L, 0x2D11284A2B16AFFCL, 0xF1FC4F67FA891D1FL,
+ 0x73ECC25DCB920ADAL, 0xAE610C22C2A12651L, 0x96E0A810D356B78AL,
+ 0x5A9A381F2FE7870FL, 0xD5AD62EDE94E5530L, 0xD225E5E8368D1427L,
+ 0x65977B70C7AF4631L, 0x99F889B2DE39D74FL, 0x233F30BF54E1D143L,
+ 0x9A9675D3D9A63C97L, 0x5470554FF334F9A8L, 0x166ACB744A4F5688L,
+ 0x70C74CAAB2E4AEADL, 0xF0D091646F294D12L, 0x57B82A89684031D1L,
+ 0xEFD95A5A61BE0B6BL, 0x2FBD12E969F2F29AL, 0x9BD37013FEFF9FE8L,
+ 0x3F9B0404D6085A06L, 0x4940C1F3166CFE15L, 0x09542C4DCDF3DEFBL,
+ 0xB4C5218385CD5CE3L, 0xC935B7DC4462A641L, 0x3417F8A68ED3B63FL,
+ 0xB80959295B215B40L, 0xF99CDAEF3B8C8572L, 0x018C0614F8FCB95DL,
+ 0x1B14ACCD1A3ACDF3L, 0x84D471F200BB732DL, 0xC1A3110E95E8DA16L,
+ 0x430A7220BF1A82B8L, 0xB77E090D39DF210EL, 0x5EF4BD9F3CD05E9DL,
+ 0x9D4FF6DA7E57A444L, 0xDA1D60E183D4A5F8L, 0xB287C38417998E47L,
+ 0xFE3EDC121BB31886L, 0xC7FE3CCC980CCBEFL, 0xE46FB590189BFD03L,
+ 0x3732FD469A4C57DCL, 0x7EF700A07CF1AD65L, 0x59C64468A31D8859L,
+ 0x762FB0B4D45B61F6L, 0x155BAED099047718L, 0x68755E4C3D50BAA6L,
+ 0xE9214E7F22D8B4DFL, 0x2ADDBF532EAC95F4L, 0x32AE3909B4BD0109L,
+ 0x834DF537B08E3450L, 0xFA209DA84220728DL, 0x9E691D9B9EFE23F7L,
+ 0x0446D288C4AE8D7FL, 0x7B4CC524E169785BL, 0x21D87F0135CA1385L,
+ 0xCEBB400F137B8AA5L, 0x272E2B66580796BEL, 0x3612264125C2B0DEL,
+ 0x057702BDAD1EFBB2L, 0xD4BABB8EACF84BE9L, 0x91583139641BC67BL,
+ 0x8BDC2DE08036E024L, 0x603C8156F49F68EDL, 0xF7D236F7DBEF5111L,
+ 0x9727C4598AD21E80L, 0xA08A0896670A5FD7L, 0xCB4A8F4309EBA9CBL,
+ 0x81AF564B0F7036A1L, 0xC0B99AA778199ABDL, 0x959F1EC83FC8E952L,
+ 0x8C505077794A81B9L, 0x3ACAAF8F056338F0L, 0x07B43F50627A6778L,
+ 0x4A44AB49F5ECCC77L, 0x3BC3D6E4B679EE98L, 0x9CC0D4D1CF14108CL,
+ 0x4406C00B206BC8A0L, 0x82A18854C8D72D89L, 0x67E366B35C3C432CL,
+ 0xB923DD61102B37F2L, 0x56AB2779D884271DL, 0xBE83E1B0FF1525AFL,
+ 0xFB7C65D4217E49A9L, 0x6BDBE0E76D48E7D4L, 0x08DF828745D9179EL,
+ 0x22EA6A9ADD53BD34L, 0xE36E141C5622200AL, 0x7F805D1B8CB750EEL,
+ 0xAFE5C7A59F58E837L, 0xE27F996A4FB1C23CL, 0xD3867DFB0775F0D0L,
+ 0xD0E673DE6E88891AL, 0x123AEB9EAFB86C25L, 0x30F1D5D5C145B895L,
+ 0xBB434A2DEE7269E7L, 0x78CB67ECF931FA38L, 0xF33B0372323BBF9CL,
+ 0x52D66336FB279C74L, 0x505F33AC0AFB4EAAL, 0xE8A5CD99A2CCE187L,
+ 0x534974801E2D30BBL, 0x8D2D5711D5876D90L, 0x1F1A412891BC038EL,
+ 0xD6E2E71D82E56648L, 0x74036C3A497732B7L, 0x89B67ED96361F5ABL,
+ 0xFFED95D8F1EA02A2L, 0xE72B3BD61464D43DL, 0xA6300F170BDC4820L,
+ 0xEBC18760ED78A77AL };
/** S-Box T2. */
- private static final long[] T2 = { 0xE6A6BE5A05A12138L, 0xB5A122A5B4F87C98L,
- 0x563C6089140B6990L, 0x4C46CB2E391F5DD5L,
- 0xD932ADDBC9B79434L, 0x08EA70E42015AFF5L,
- 0xD765A6673E478CF1L, 0xC4FB757EAB278D99L,
- 0xDF11C6862D6E0692L, 0xDDEB84F10D7F3B16L,
- 0x6F2EF604A665EA04L, 0x4A8E0F0FF0E0DFB3L,
- 0xA5EDEEF83DBCBA51L, 0xFC4F0A2A0EA4371EL,
- 0xE83E1DA85CB38429L, 0xDC8FF882BA1B1CE2L,
- 0xCD45505E8353E80DL, 0x18D19A00D4DB0717L,
- 0x34A0CFEDA5F38101L, 0x0BE77E518887CAF2L,
- 0x1E341438B3C45136L, 0xE05797F49089CCF9L,
- 0xFFD23F9DF2591D14L, 0x543DDA228595C5CDL,
- 0x661F81FD99052A33L, 0x8736E641DB0F7B76L,
- 0x15227725418E5307L, 0xE25F7F46162EB2FAL,
- 0x48A8B2126C13D9FEL, 0xAFDC541792E76EEAL,
- 0x03D912BFC6D1898FL, 0x31B1AAFA1B83F51BL,
- 0xF1AC2796E42AB7D9L, 0x40A3A7D7FCD2EBACL,
- 0x1056136D0AFBBCC5L, 0x7889E1DD9A6D0C85L,
- 0xD33525782A7974AAL, 0xA7E25D09078AC09BL,
- 0xBD4138B3EAC6EDD0L, 0x920ABFBE71EB9E70L,
- 0xA2A5D0F54FC2625CL, 0xC054E36B0B1290A3L,
- 0xF6DD59FF62FE932BL, 0x3537354511A8AC7DL,
- 0xCA845E9172FADCD4L, 0x84F82B60329D20DCL,
- 0x79C62CE1CD672F18L, 0x8B09A2ADD124642CL,
- 0xD0C1E96A19D9E726L, 0x5A786A9B4BA9500CL,
- 0x0E020336634C43F3L, 0xC17B474AEB66D822L,
- 0x6A731AE3EC9BAAC2L, 0x8226667AE0840258L,
- 0x67D4567691CAECA5L, 0x1D94155C4875ADB5L,
- 0x6D00FD985B813FDFL, 0x51286EFCB774CD06L,
- 0x5E8834471FA744AFL, 0xF72CA0AEE761AE2EL,
- 0xBE40E4CDAEE8E09AL, 0xE9970BBB5118F665L,
- 0x726E4BEB33DF1964L, 0x703B000729199762L,
- 0x4631D816F5EF30A7L, 0xB880B5B51504A6BEL,
- 0x641793C37ED84B6CL, 0x7B21ED77F6E97D96L,
- 0x776306312EF96B73L, 0xAE528948E86FF3F4L,
- 0x53DBD7F286A3F8F8L, 0x16CADCE74CFC1063L,
- 0x005C19BDFA52C6DDL, 0x68868F5D64D46AD3L,
- 0x3A9D512CCF1E186AL, 0x367E62C2385660AEL,
- 0xE359E7EA77DCB1D7L, 0x526C0773749ABE6EL,
- 0x735AE5F9D09F734BL, 0x493FC7CC8A558BA8L,
- 0xB0B9C1533041AB45L, 0x321958BA470A59BDL,
- 0x852DB00B5F46C393L, 0x91209B2BD336B0E5L,
- 0x6E604F7D659EF19FL, 0xB99A8AE2782CCB24L,
- 0xCCF52AB6C814C4C7L, 0x4727D9AFBE11727BL,
- 0x7E950D0C0121B34DL, 0x756F435670AD471FL,
- 0xF5ADD442615A6849L, 0x4E87E09980B9957AL,
- 0x2ACFA1DF50AEE355L, 0xD898263AFD2FD556L,
- 0xC8F4924DD80C8FD6L, 0xCF99CA3D754A173AL,
- 0xFE477BACAF91BF3CL, 0xED5371F6D690C12DL,
- 0x831A5C285E687094L, 0xC5D3C90A3708A0A4L,
- 0x0F7F903717D06580L, 0x19F9BB13B8FDF27FL,
- 0xB1BD6F1B4D502843L, 0x1C761BA38FFF4012L,
- 0x0D1530C4E2E21F3BL, 0x8943CE69A7372C8AL,
- 0xE5184E11FEB5CE66L, 0x618BDB80BD736621L,
- 0x7D29BAD68B574D0BL, 0x81BB613E25E6FE5BL,
- 0x071C9C10BC07913FL, 0xC7BEEB7909AC2D97L,
- 0xC3E58D353BC5D757L, 0xEB017892F38F61E8L,
- 0xD4EFFB9C9B1CC21AL, 0x99727D26F494F7ABL,
- 0xA3E063A2956B3E03L, 0x9D4A8B9A4AA09C30L,
- 0x3F6AB7D500090FB4L, 0x9CC0F2A057268AC0L,
- 0x3DEE9D2DEDBF42D1L, 0x330F49C87960A972L,
- 0xC6B2720287421B41L, 0x0AC59EC07C00369CL,
- 0xEF4EAC49CB353425L, 0xF450244EEF0129D8L,
- 0x8ACC46E5CAF4DEB6L, 0x2FFEAB63989263F7L,
- 0x8F7CB9FE5D7A4578L, 0x5BD8F7644E634635L,
- 0x427A7315BF2DC900L, 0x17D0C4AA2125261CL,
- 0x3992486C93518E50L, 0xB4CBFEE0A2D7D4C3L,
- 0x7C75D6202C5DDD8DL, 0xDBC295D8E35B6C61L,
- 0x60B369D302032B19L, 0xCE42685FDCE44132L,
- 0x06F3DDB9DDF65610L, 0x8EA4D21DB5E148F0L,
- 0x20B0FCE62FCD496FL, 0x2C1B912358B0EE31L,
- 0xB28317B818F5A308L, 0xA89C1E189CA6D2CFL,
- 0x0C6B18576AAADBC8L, 0xB65DEAA91299FAE3L,
- 0xFB2B794B7F1027E7L, 0x04E4317F443B5BEBL,
- 0x4B852D325939D0A6L, 0xD5AE6BEEFB207FFCL,
- 0x309682B281C7D374L, 0xBAE309A194C3B475L,
- 0x8CC3F97B13B49F05L, 0x98A9422FF8293967L,
- 0x244B16B01076FF7CL, 0xF8BF571C663D67EEL,
- 0x1F0D6758EEE30DA1L, 0xC9B611D97ADEB9B7L,
- 0xB7AFD5887B6C57A2L, 0x6290AE846B984FE1L,
- 0x94DF4CDEACC1A5FDL, 0x058A5BD1C5483AFFL,
- 0x63166CC142BA3C37L, 0x8DB8526EB2F76F40L,
- 0xE10880036F0D6D4EL, 0x9E0523C9971D311DL,
- 0x45EC2824CC7CD691L, 0x575B8359E62382C9L,
- 0xFA9E400DC4889995L, 0xD1823ECB45721568L,
- 0xDAFD983B8206082FL, 0xAA7D29082386A8CBL,
- 0x269FCD4403B87588L, 0x1B91F5F728BDD1E0L,
- 0xE4669F39040201F6L, 0x7A1D7C218CF04ADEL,
- 0x65623C29D79CE5CEL, 0x2368449096C00BB1L,
- 0xAB9BF1879DA503BAL, 0xBC23ECB1A458058EL,
- 0x9A58DF01BB401ECCL, 0xA070E868A85F143DL,
- 0x4FF188307DF2239EL, 0x14D565B41A641183L,
- 0xEE13337452701602L, 0x950E3DCF3F285E09L,
- 0x59930254B9C80953L, 0x3BF299408930DA6DL,
- 0xA955943F53691387L, 0xA15EDECAA9CB8784L,
- 0x29142127352BE9A0L, 0x76F0371FFF4E7AFBL,
- 0x0239F450274F2228L, 0xBB073AF01D5E868BL,
- 0xBFC80571C10E96C1L, 0xD267088568222E23L,
- 0x9671A3D48E80B5B0L, 0x55B5D38AE193BB81L,
- 0x693AE2D0A18B04B8L, 0x5C48B4ECADD5335FL,
- 0xFD743B194916A1CAL, 0x2577018134BE98C4L,
- 0xE77987E83C54A4ADL, 0x28E11014DA33E1B9L,
- 0x270CC59E226AA213L, 0x71495F756D1A5F60L,
- 0x9BE853FB60AFEF77L, 0xADC786A7F7443DBFL,
- 0x0904456173B29A82L, 0x58BC7A66C232BD5EL,
- 0xF306558C673AC8B2L, 0x41F639C6B6C9772AL,
- 0x216DEFE99FDA35DAL, 0x11640CC71C7BE615L,
- 0x93C43694565C5527L, 0xEA038E6246777839L,
- 0xF9ABF3CE5A3E2469L, 0x741E768D0FD312D2L,
- 0x0144B883CED652C6L, 0xC20B5A5BA33F8552L,
- 0x1AE69633C3435A9DL, 0x97A28CA4088CFDECL,
- 0x8824A43C1E96F420L, 0x37612FA66EEEA746L,
- 0x6B4CB165F9CF0E5AL, 0x43AA1C06A0ABFB4AL,
- 0x7F4DC26FF162796BL, 0x6CBACC8E54ED9B0FL,
- 0xA6B7FFEFD2BB253EL, 0x2E25BC95B0A29D4FL,
- 0x86D6A58BDEF1388CL, 0xDED74AC576B6F054L,
- 0x8030BDBC2B45805DL, 0x3C81AF70E94D9289L,
- 0x3EFF6DDA9E3100DBL, 0xB38DC39FDFCC8847L,
- 0x123885528D17B87EL, 0xF2DA0ED240B1B642L,
- 0x44CEFADCD54BF9A9L, 0x1312200E433C7EE6L,
- 0x9FFCC84F3A78C748L, 0xF0CD1F72248576BBL,
- 0xEC6974053638CFE4L, 0x2BA7B67C0CEC4E4CL,
- 0xAC2F4DF3E5CE32EDL, 0xCB33D14326EA4C11L,
- 0xA4E9044CC77E58BCL, 0x5F513293D934FCEFL,
- 0x5DC9645506E55444L, 0x50DE418F317DE40AL,
- 0x388CB31A69DDE259L, 0x2DB4A83455820A86L,
- 0x9010A91E84711AE9L, 0x4DF7F0B7B1498371L,
- 0xD62A2EABC0977179L, 0x22FAC097AA8D5C0EL };
+ private static final long[] T2 = {
+ 0xE6A6BE5A05A12138L, 0xB5A122A5B4F87C98L, 0x563C6089140B6990L,
+ 0x4C46CB2E391F5DD5L, 0xD932ADDBC9B79434L, 0x08EA70E42015AFF5L,
+ 0xD765A6673E478CF1L, 0xC4FB757EAB278D99L, 0xDF11C6862D6E0692L,
+ 0xDDEB84F10D7F3B16L, 0x6F2EF604A665EA04L, 0x4A8E0F0FF0E0DFB3L,
+ 0xA5EDEEF83DBCBA51L, 0xFC4F0A2A0EA4371EL, 0xE83E1DA85CB38429L,
+ 0xDC8FF882BA1B1CE2L, 0xCD45505E8353E80DL, 0x18D19A00D4DB0717L,
+ 0x34A0CFEDA5F38101L, 0x0BE77E518887CAF2L, 0x1E341438B3C45136L,
+ 0xE05797F49089CCF9L, 0xFFD23F9DF2591D14L, 0x543DDA228595C5CDL,
+ 0x661F81FD99052A33L, 0x8736E641DB0F7B76L, 0x15227725418E5307L,
+ 0xE25F7F46162EB2FAL, 0x48A8B2126C13D9FEL, 0xAFDC541792E76EEAL,
+ 0x03D912BFC6D1898FL, 0x31B1AAFA1B83F51BL, 0xF1AC2796E42AB7D9L,
+ 0x40A3A7D7FCD2EBACL, 0x1056136D0AFBBCC5L, 0x7889E1DD9A6D0C85L,
+ 0xD33525782A7974AAL, 0xA7E25D09078AC09BL, 0xBD4138B3EAC6EDD0L,
+ 0x920ABFBE71EB9E70L, 0xA2A5D0F54FC2625CL, 0xC054E36B0B1290A3L,
+ 0xF6DD59FF62FE932BL, 0x3537354511A8AC7DL, 0xCA845E9172FADCD4L,
+ 0x84F82B60329D20DCL, 0x79C62CE1CD672F18L, 0x8B09A2ADD124642CL,
+ 0xD0C1E96A19D9E726L, 0x5A786A9B4BA9500CL, 0x0E020336634C43F3L,
+ 0xC17B474AEB66D822L, 0x6A731AE3EC9BAAC2L, 0x8226667AE0840258L,
+ 0x67D4567691CAECA5L, 0x1D94155C4875ADB5L, 0x6D00FD985B813FDFL,
+ 0x51286EFCB774CD06L, 0x5E8834471FA744AFL, 0xF72CA0AEE761AE2EL,
+ 0xBE40E4CDAEE8E09AL, 0xE9970BBB5118F665L, 0x726E4BEB33DF1964L,
+ 0x703B000729199762L, 0x4631D816F5EF30A7L, 0xB880B5B51504A6BEL,
+ 0x641793C37ED84B6CL, 0x7B21ED77F6E97D96L, 0x776306312EF96B73L,
+ 0xAE528948E86FF3F4L, 0x53DBD7F286A3F8F8L, 0x16CADCE74CFC1063L,
+ 0x005C19BDFA52C6DDL, 0x68868F5D64D46AD3L, 0x3A9D512CCF1E186AL,
+ 0x367E62C2385660AEL, 0xE359E7EA77DCB1D7L, 0x526C0773749ABE6EL,
+ 0x735AE5F9D09F734BL, 0x493FC7CC8A558BA8L, 0xB0B9C1533041AB45L,
+ 0x321958BA470A59BDL, 0x852DB00B5F46C393L, 0x91209B2BD336B0E5L,
+ 0x6E604F7D659EF19FL, 0xB99A8AE2782CCB24L, 0xCCF52AB6C814C4C7L,
+ 0x4727D9AFBE11727BL, 0x7E950D0C0121B34DL, 0x756F435670AD471FL,
+ 0xF5ADD442615A6849L, 0x4E87E09980B9957AL, 0x2ACFA1DF50AEE355L,
+ 0xD898263AFD2FD556L, 0xC8F4924DD80C8FD6L, 0xCF99CA3D754A173AL,
+ 0xFE477BACAF91BF3CL, 0xED5371F6D690C12DL, 0x831A5C285E687094L,
+ 0xC5D3C90A3708A0A4L, 0x0F7F903717D06580L, 0x19F9BB13B8FDF27FL,
+ 0xB1BD6F1B4D502843L, 0x1C761BA38FFF4012L, 0x0D1530C4E2E21F3BL,
+ 0x8943CE69A7372C8AL, 0xE5184E11FEB5CE66L, 0x618BDB80BD736621L,
+ 0x7D29BAD68B574D0BL, 0x81BB613E25E6FE5BL, 0x071C9C10BC07913FL,
+ 0xC7BEEB7909AC2D97L, 0xC3E58D353BC5D757L, 0xEB017892F38F61E8L,
+ 0xD4EFFB9C9B1CC21AL, 0x99727D26F494F7ABL, 0xA3E063A2956B3E03L,
+ 0x9D4A8B9A4AA09C30L, 0x3F6AB7D500090FB4L, 0x9CC0F2A057268AC0L,
+ 0x3DEE9D2DEDBF42D1L, 0x330F49C87960A972L, 0xC6B2720287421B41L,
+ 0x0AC59EC07C00369CL, 0xEF4EAC49CB353425L, 0xF450244EEF0129D8L,
+ 0x8ACC46E5CAF4DEB6L, 0x2FFEAB63989263F7L, 0x8F7CB9FE5D7A4578L,
+ 0x5BD8F7644E634635L, 0x427A7315BF2DC900L, 0x17D0C4AA2125261CL,
+ 0x3992486C93518E50L, 0xB4CBFEE0A2D7D4C3L, 0x7C75D6202C5DDD8DL,
+ 0xDBC295D8E35B6C61L, 0x60B369D302032B19L, 0xCE42685FDCE44132L,
+ 0x06F3DDB9DDF65610L, 0x8EA4D21DB5E148F0L, 0x20B0FCE62FCD496FL,
+ 0x2C1B912358B0EE31L, 0xB28317B818F5A308L, 0xA89C1E189CA6D2CFL,
+ 0x0C6B18576AAADBC8L, 0xB65DEAA91299FAE3L, 0xFB2B794B7F1027E7L,
+ 0x04E4317F443B5BEBL, 0x4B852D325939D0A6L, 0xD5AE6BEEFB207FFCL,
+ 0x309682B281C7D374L, 0xBAE309A194C3B475L, 0x8CC3F97B13B49F05L,
+ 0x98A9422FF8293967L, 0x244B16B01076FF7CL, 0xF8BF571C663D67EEL,
+ 0x1F0D6758EEE30DA1L, 0xC9B611D97ADEB9B7L, 0xB7AFD5887B6C57A2L,
+ 0x6290AE846B984FE1L, 0x94DF4CDEACC1A5FDL, 0x058A5BD1C5483AFFL,
+ 0x63166CC142BA3C37L, 0x8DB8526EB2F76F40L, 0xE10880036F0D6D4EL,
+ 0x9E0523C9971D311DL, 0x45EC2824CC7CD691L, 0x575B8359E62382C9L,
+ 0xFA9E400DC4889995L, 0xD1823ECB45721568L, 0xDAFD983B8206082FL,
+ 0xAA7D29082386A8CBL, 0x269FCD4403B87588L, 0x1B91F5F728BDD1E0L,
+ 0xE4669F39040201F6L, 0x7A1D7C218CF04ADEL, 0x65623C29D79CE5CEL,
+ 0x2368449096C00BB1L, 0xAB9BF1879DA503BAL, 0xBC23ECB1A458058EL,
+ 0x9A58DF01BB401ECCL, 0xA070E868A85F143DL, 0x4FF188307DF2239EL,
+ 0x14D565B41A641183L, 0xEE13337452701602L, 0x950E3DCF3F285E09L,
+ 0x59930254B9C80953L, 0x3BF299408930DA6DL, 0xA955943F53691387L,
+ 0xA15EDECAA9CB8784L, 0x29142127352BE9A0L, 0x76F0371FFF4E7AFBL,
+ 0x0239F450274F2228L, 0xBB073AF01D5E868BL, 0xBFC80571C10E96C1L,
+ 0xD267088568222E23L, 0x9671A3D48E80B5B0L, 0x55B5D38AE193BB81L,
+ 0x693AE2D0A18B04B8L, 0x5C48B4ECADD5335FL, 0xFD743B194916A1CAL,
+ 0x2577018134BE98C4L, 0xE77987E83C54A4ADL, 0x28E11014DA33E1B9L,
+ 0x270CC59E226AA213L, 0x71495F756D1A5F60L, 0x9BE853FB60AFEF77L,
+ 0xADC786A7F7443DBFL, 0x0904456173B29A82L, 0x58BC7A66C232BD5EL,
+ 0xF306558C673AC8B2L, 0x41F639C6B6C9772AL, 0x216DEFE99FDA35DAL,
+ 0x11640CC71C7BE615L, 0x93C43694565C5527L, 0xEA038E6246777839L,
+ 0xF9ABF3CE5A3E2469L, 0x741E768D0FD312D2L, 0x0144B883CED652C6L,
+ 0xC20B5A5BA33F8552L, 0x1AE69633C3435A9DL, 0x97A28CA4088CFDECL,
+ 0x8824A43C1E96F420L, 0x37612FA66EEEA746L, 0x6B4CB165F9CF0E5AL,
+ 0x43AA1C06A0ABFB4AL, 0x7F4DC26FF162796BL, 0x6CBACC8E54ED9B0FL,
+ 0xA6B7FFEFD2BB253EL, 0x2E25BC95B0A29D4FL, 0x86D6A58BDEF1388CL,
+ 0xDED74AC576B6F054L, 0x8030BDBC2B45805DL, 0x3C81AF70E94D9289L,
+ 0x3EFF6DDA9E3100DBL, 0xB38DC39FDFCC8847L, 0x123885528D17B87EL,
+ 0xF2DA0ED240B1B642L, 0x44CEFADCD54BF9A9L, 0x1312200E433C7EE6L,
+ 0x9FFCC84F3A78C748L, 0xF0CD1F72248576BBL, 0xEC6974053638CFE4L,
+ 0x2BA7B67C0CEC4E4CL, 0xAC2F4DF3E5CE32EDL, 0xCB33D14326EA4C11L,
+ 0xA4E9044CC77E58BCL, 0x5F513293D934FCEFL, 0x5DC9645506E55444L,
+ 0x50DE418F317DE40AL, 0x388CB31A69DDE259L, 0x2DB4A83455820A86L,
+ 0x9010A91E84711AE9L, 0x4DF7F0B7B1498371L, 0xD62A2EABC0977179L,
+ 0x22FAC097AA8D5C0EL };
/** S-Box T3. */
- private static final long[] T3 = { 0xF49FCC2FF1DAF39BL, 0x487FD5C66FF29281L,
- 0xE8A30667FCDCA83FL, 0x2C9B4BE3D2FCCE63L,
- 0xDA3FF74B93FBBBC2L, 0x2FA165D2FE70BA66L,
- 0xA103E279970E93D4L, 0xBECDEC77B0E45E71L,
- 0xCFB41E723985E497L, 0xB70AAA025EF75017L,
- 0xD42309F03840B8E0L, 0x8EFC1AD035898579L,
- 0x96C6920BE2B2ABC5L, 0x66AF4163375A9172L,
- 0x2174ABDCCA7127FBL, 0xB33CCEA64A72FF41L,
- 0xF04A4933083066A5L, 0x8D970ACDD7289AF5L,
- 0x8F96E8E031C8C25EL, 0xF3FEC02276875D47L,
- 0xEC7BF310056190DDL, 0xF5ADB0AEBB0F1491L,
- 0x9B50F8850FD58892L, 0x4975488358B74DE8L,
- 0xA3354FF691531C61L, 0x0702BBE481D2C6EEL,
- 0x89FB24057DEDED98L, 0xAC3075138596E902L,
- 0x1D2D3580172772EDL, 0xEB738FC28E6BC30DL,
- 0x5854EF8F63044326L, 0x9E5C52325ADD3BBEL,
- 0x90AA53CF325C4623L, 0xC1D24D51349DD067L,
- 0x2051CFEEA69EA624L, 0x13220F0A862E7E4FL,
- 0xCE39399404E04864L, 0xD9C42CA47086FCB7L,
- 0x685AD2238A03E7CCL, 0x066484B2AB2FF1DBL,
- 0xFE9D5D70EFBF79ECL, 0x5B13B9DD9C481854L,
- 0x15F0D475ED1509ADL, 0x0BEBCD060EC79851L,
- 0xD58C6791183AB7F8L, 0xD1187C5052F3EEE4L,
- 0xC95D1192E54E82FFL, 0x86EEA14CB9AC6CA2L,
- 0x3485BEB153677D5DL, 0xDD191D781F8C492AL,
- 0xF60866BAA784EBF9L, 0x518F643BA2D08C74L,
- 0x8852E956E1087C22L, 0xA768CB8DC410AE8DL,
- 0x38047726BFEC8E1AL, 0xA67738B4CD3B45AAL,
- 0xAD16691CEC0DDE19L, 0xC6D4319380462E07L,
- 0xC5A5876D0BA61938L, 0x16B9FA1FA58FD840L,
- 0x188AB1173CA74F18L, 0xABDA2F98C99C021FL,
- 0x3E0580AB134AE816L, 0x5F3B05B773645ABBL,
- 0x2501A2BE5575F2F6L, 0x1B2F74004E7E8BA9L,
- 0x1CD7580371E8D953L, 0x7F6ED89562764E30L,
- 0xB15926FF596F003DL, 0x9F65293DA8C5D6B9L,
- 0x6ECEF04DD690F84CL, 0x4782275FFF33AF88L,
- 0xE41433083F820801L, 0xFD0DFE409A1AF9B5L,
- 0x4325A3342CDB396BL, 0x8AE77E62B301B252L,
- 0xC36F9E9F6655615AL, 0x85455A2D92D32C09L,
- 0xF2C7DEA949477485L, 0x63CFB4C133A39EBAL,
- 0x83B040CC6EBC5462L, 0x3B9454C8FDB326B0L,
- 0x56F56A9E87FFD78CL, 0x2DC2940D99F42BC6L,
- 0x98F7DF096B096E2DL, 0x19A6E01E3AD852BFL,
- 0x42A99CCBDBD4B40BL, 0xA59998AF45E9C559L,
- 0x366295E807D93186L, 0x6B48181BFAA1F773L,
- 0x1FEC57E2157A0A1DL, 0x4667446AF6201AD5L,
- 0xE615EBCACFB0F075L, 0xB8F31F4F68290778L,
- 0x22713ED6CE22D11EL, 0x3057C1A72EC3C93BL,
- 0xCB46ACC37C3F1F2FL, 0xDBB893FD02AAF50EL,
- 0x331FD92E600B9FCFL, 0xA498F96148EA3AD6L,
- 0xA8D8426E8B6A83EAL, 0xA089B274B7735CDCL,
- 0x87F6B3731E524A11L, 0x118808E5CBC96749L,
- 0x9906E4C7B19BD394L, 0xAFED7F7E9B24A20CL,
- 0x6509EADEEB3644A7L, 0x6C1EF1D3E8EF0EDEL,
- 0xB9C97D43E9798FB4L, 0xA2F2D784740C28A3L,
- 0x7B8496476197566FL, 0x7A5BE3E6B65F069DL,
- 0xF96330ED78BE6F10L, 0xEEE60DE77A076A15L,
- 0x2B4BEE4AA08B9BD0L, 0x6A56A63EC7B8894EL,
- 0x02121359BA34FEF4L, 0x4CBF99F8283703FCL,
- 0x398071350CAF30C8L, 0xD0A77A89F017687AL,
- 0xF1C1A9EB9E423569L, 0x8C7976282DEE8199L,
- 0x5D1737A5DD1F7ABDL, 0x4F53433C09A9FA80L,
- 0xFA8B0C53DF7CA1D9L, 0x3FD9DCBC886CCB77L,
- 0xC040917CA91B4720L, 0x7DD00142F9D1DCDFL,
- 0x8476FC1D4F387B58L, 0x23F8E7C5F3316503L,
- 0x032A2244E7E37339L, 0x5C87A5D750F5A74BL,
- 0x082B4CC43698992EL, 0xDF917BECB858F63CL,
- 0x3270B8FC5BF86DDAL, 0x10AE72BB29B5DD76L,
- 0x576AC94E7700362BL, 0x1AD112DAC61EFB8FL,
- 0x691BC30EC5FAA427L, 0xFF246311CC327143L,
- 0x3142368E30E53206L, 0x71380E31E02CA396L,
- 0x958D5C960AAD76F1L, 0xF8D6F430C16DA536L,
- 0xC8FFD13F1BE7E1D2L, 0x7578AE66004DDBE1L,
- 0x05833F01067BE646L, 0xBB34B5AD3BFE586DL,
- 0x095F34C9A12B97F0L, 0x247AB64525D60CA8L,
- 0xDCDBC6F3017477D1L, 0x4A2E14D4DECAD24DL,
- 0xBDB5E6D9BE0A1EEBL, 0x2A7E70F7794301ABL,
- 0xDEF42D8A270540FDL, 0x01078EC0A34C22C1L,
- 0xE5DE511AF4C16387L, 0x7EBB3A52BD9A330AL,
- 0x77697857AA7D6435L, 0x004E831603AE4C32L,
- 0xE7A21020AD78E312L, 0x9D41A70C6AB420F2L,
- 0x28E06C18EA1141E6L, 0xD2B28CBD984F6B28L,
- 0x26B75F6C446E9D83L, 0xBA47568C4D418D7FL,
- 0xD80BADBFE6183D8EL, 0x0E206D7F5F166044L,
- 0xE258A43911CBCA3EL, 0x723A1746B21DC0BCL,
- 0xC7CAA854F5D7CDD3L, 0x7CAC32883D261D9CL,
- 0x7690C26423BA942CL, 0x17E55524478042B8L,
- 0xE0BE477656A2389FL, 0x4D289B5E67AB2DA0L,
- 0x44862B9C8FBBFD31L, 0xB47CC8049D141365L,
- 0x822C1B362B91C793L, 0x4EB14655FB13DFD8L,
- 0x1ECBBA0714E2A97BL, 0x6143459D5CDE5F14L,
- 0x53A8FBF1D5F0AC89L, 0x97EA04D81C5E5B00L,
- 0x622181A8D4FDB3F3L, 0xE9BCD341572A1208L,
- 0x1411258643CCE58AL, 0x9144C5FEA4C6E0A4L,
- 0x0D33D06565CF620FL, 0x54A48D489F219CA1L,
- 0xC43E5EAC6D63C821L, 0xA9728B3A72770DAFL,
- 0xD7934E7B20DF87EFL, 0xE35503B61A3E86E5L,
- 0xCAE321FBC819D504L, 0x129A50B3AC60BFA6L,
- 0xCD5E68EA7E9FB6C3L, 0xB01C90199483B1C7L,
- 0x3DE93CD5C295376CL, 0xAED52EDF2AB9AD13L,
- 0x2E60F512C0A07884L, 0xBC3D86A3E36210C9L,
- 0x35269D9B163951CEL, 0x0C7D6E2AD0CDB5FAL,
- 0x59E86297D87F5733L, 0x298EF221898DB0E7L,
- 0x55000029D1A5AA7EL, 0x8BC08AE1B5061B45L,
- 0xC2C31C2B6C92703AL, 0x94CC596BAF25EF42L,
- 0x0A1D73DB22540456L, 0x04B6A0F9D9C4179AL,
- 0xEFFDAFA2AE3D3C60L, 0xF7C8075BB49496C4L,
- 0x9CC5C7141D1CD4E3L, 0x78BD1638218E5534L,
- 0xB2F11568F850246AL, 0xEDFABCFA9502BC29L,
- 0x796CE5F2DA23051BL, 0xAAE128B0DC93537CL,
- 0x3A493DA0EE4B29AEL, 0xB5DF6B2C416895D7L,
- 0xFCABBD25122D7F37L, 0x70810B58105DC4B1L,
- 0xE10FDD37F7882A90L, 0x524DCAB5518A3F5CL,
- 0x3C9E85878451255BL, 0x4029828119BD34E2L,
- 0x74A05B6F5D3CECCBL, 0xB610021542E13ECAL,
- 0x0FF979D12F59E2ACL, 0x6037DA27E4F9CC50L,
- 0x5E92975A0DF1847DL, 0xD66DE190D3E623FEL,
- 0x5032D6B87B568048L, 0x9A36B7CE8235216EL,
- 0x80272A7A24F64B4AL, 0x93EFED8B8C6916F7L,
- 0x37DDBFF44CCE1555L, 0x4B95DB5D4B99BD25L,
- 0x92D3FDA169812FC0L, 0xFB1A4A9A90660BB6L,
- 0x730C196946A4B9B2L, 0x81E289AA7F49DA68L,
- 0x64669A0F83B1A05FL, 0x27B3FF7D9644F48BL,
- 0xCC6B615C8DB675B3L, 0x674F20B9BCEBBE95L,
- 0x6F31238275655982L, 0x5AE488713E45CF05L,
- 0xBF619F9954C21157L, 0xEABAC46040A8EAE9L,
- 0x454C6FE9F2C0C1CDL, 0x419CF6496412691CL,
- 0xD3DC3BEF265B0F70L, 0x6D0E60F5C3578A9EL };
+ private static final long[] T3 = {
+ 0xF49FCC2FF1DAF39BL, 0x487FD5C66FF29281L, 0xE8A30667FCDCA83FL,
+ 0x2C9B4BE3D2FCCE63L, 0xDA3FF74B93FBBBC2L, 0x2FA165D2FE70BA66L,
+ 0xA103E279970E93D4L, 0xBECDEC77B0E45E71L, 0xCFB41E723985E497L,
+ 0xB70AAA025EF75017L, 0xD42309F03840B8E0L, 0x8EFC1AD035898579L,
+ 0x96C6920BE2B2ABC5L, 0x66AF4163375A9172L, 0x2174ABDCCA7127FBL,
+ 0xB33CCEA64A72FF41L, 0xF04A4933083066A5L, 0x8D970ACDD7289AF5L,
+ 0x8F96E8E031C8C25EL, 0xF3FEC02276875D47L, 0xEC7BF310056190DDL,
+ 0xF5ADB0AEBB0F1491L, 0x9B50F8850FD58892L, 0x4975488358B74DE8L,
+ 0xA3354FF691531C61L, 0x0702BBE481D2C6EEL, 0x89FB24057DEDED98L,
+ 0xAC3075138596E902L, 0x1D2D3580172772EDL, 0xEB738FC28E6BC30DL,
+ 0x5854EF8F63044326L, 0x9E5C52325ADD3BBEL, 0x90AA53CF325C4623L,
+ 0xC1D24D51349DD067L, 0x2051CFEEA69EA624L, 0x13220F0A862E7E4FL,
+ 0xCE39399404E04864L, 0xD9C42CA47086FCB7L, 0x685AD2238A03E7CCL,
+ 0x066484B2AB2FF1DBL, 0xFE9D5D70EFBF79ECL, 0x5B13B9DD9C481854L,
+ 0x15F0D475ED1509ADL, 0x0BEBCD060EC79851L, 0xD58C6791183AB7F8L,
+ 0xD1187C5052F3EEE4L, 0xC95D1192E54E82FFL, 0x86EEA14CB9AC6CA2L,
+ 0x3485BEB153677D5DL, 0xDD191D781F8C492AL, 0xF60866BAA784EBF9L,
+ 0x518F643BA2D08C74L, 0x8852E956E1087C22L, 0xA768CB8DC410AE8DL,
+ 0x38047726BFEC8E1AL, 0xA67738B4CD3B45AAL, 0xAD16691CEC0DDE19L,
+ 0xC6D4319380462E07L, 0xC5A5876D0BA61938L, 0x16B9FA1FA58FD840L,
+ 0x188AB1173CA74F18L, 0xABDA2F98C99C021FL, 0x3E0580AB134AE816L,
+ 0x5F3B05B773645ABBL, 0x2501A2BE5575F2F6L, 0x1B2F74004E7E8BA9L,
+ 0x1CD7580371E8D953L, 0x7F6ED89562764E30L, 0xB15926FF596F003DL,
+ 0x9F65293DA8C5D6B9L, 0x6ECEF04DD690F84CL, 0x4782275FFF33AF88L,
+ 0xE41433083F820801L, 0xFD0DFE409A1AF9B5L, 0x4325A3342CDB396BL,
+ 0x8AE77E62B301B252L, 0xC36F9E9F6655615AL, 0x85455A2D92D32C09L,
+ 0xF2C7DEA949477485L, 0x63CFB4C133A39EBAL, 0x83B040CC6EBC5462L,
+ 0x3B9454C8FDB326B0L, 0x56F56A9E87FFD78CL, 0x2DC2940D99F42BC6L,
+ 0x98F7DF096B096E2DL, 0x19A6E01E3AD852BFL, 0x42A99CCBDBD4B40BL,
+ 0xA59998AF45E9C559L, 0x366295E807D93186L, 0x6B48181BFAA1F773L,
+ 0x1FEC57E2157A0A1DL, 0x4667446AF6201AD5L, 0xE615EBCACFB0F075L,
+ 0xB8F31F4F68290778L, 0x22713ED6CE22D11EL, 0x3057C1A72EC3C93BL,
+ 0xCB46ACC37C3F1F2FL, 0xDBB893FD02AAF50EL, 0x331FD92E600B9FCFL,
+ 0xA498F96148EA3AD6L, 0xA8D8426E8B6A83EAL, 0xA089B274B7735CDCL,
+ 0x87F6B3731E524A11L, 0x118808E5CBC96749L, 0x9906E4C7B19BD394L,
+ 0xAFED7F7E9B24A20CL, 0x6509EADEEB3644A7L, 0x6C1EF1D3E8EF0EDEL,
+ 0xB9C97D43E9798FB4L, 0xA2F2D784740C28A3L, 0x7B8496476197566FL,
+ 0x7A5BE3E6B65F069DL, 0xF96330ED78BE6F10L, 0xEEE60DE77A076A15L,
+ 0x2B4BEE4AA08B9BD0L, 0x6A56A63EC7B8894EL, 0x02121359BA34FEF4L,
+ 0x4CBF99F8283703FCL, 0x398071350CAF30C8L, 0xD0A77A89F017687AL,
+ 0xF1C1A9EB9E423569L, 0x8C7976282DEE8199L, 0x5D1737A5DD1F7ABDL,
+ 0x4F53433C09A9FA80L, 0xFA8B0C53DF7CA1D9L, 0x3FD9DCBC886CCB77L,
+ 0xC040917CA91B4720L, 0x7DD00142F9D1DCDFL, 0x8476FC1D4F387B58L,
+ 0x23F8E7C5F3316503L, 0x032A2244E7E37339L, 0x5C87A5D750F5A74BL,
+ 0x082B4CC43698992EL, 0xDF917BECB858F63CL, 0x3270B8FC5BF86DDAL,
+ 0x10AE72BB29B5DD76L, 0x576AC94E7700362BL, 0x1AD112DAC61EFB8FL,
+ 0x691BC30EC5FAA427L, 0xFF246311CC327143L, 0x3142368E30E53206L,
+ 0x71380E31E02CA396L, 0x958D5C960AAD76F1L, 0xF8D6F430C16DA536L,
+ 0xC8FFD13F1BE7E1D2L, 0x7578AE66004DDBE1L, 0x05833F01067BE646L,
+ 0xBB34B5AD3BFE586DL, 0x095F34C9A12B97F0L, 0x247AB64525D60CA8L,
+ 0xDCDBC6F3017477D1L, 0x4A2E14D4DECAD24DL, 0xBDB5E6D9BE0A1EEBL,
+ 0x2A7E70F7794301ABL, 0xDEF42D8A270540FDL, 0x01078EC0A34C22C1L,
+ 0xE5DE511AF4C16387L, 0x7EBB3A52BD9A330AL, 0x77697857AA7D6435L,
+ 0x004E831603AE4C32L, 0xE7A21020AD78E312L, 0x9D41A70C6AB420F2L,
+ 0x28E06C18EA1141E6L, 0xD2B28CBD984F6B28L, 0x26B75F6C446E9D83L,
+ 0xBA47568C4D418D7FL, 0xD80BADBFE6183D8EL, 0x0E206D7F5F166044L,
+ 0xE258A43911CBCA3EL, 0x723A1746B21DC0BCL, 0xC7CAA854F5D7CDD3L,
+ 0x7CAC32883D261D9CL, 0x7690C26423BA942CL, 0x17E55524478042B8L,
+ 0xE0BE477656A2389FL, 0x4D289B5E67AB2DA0L, 0x44862B9C8FBBFD31L,
+ 0xB47CC8049D141365L, 0x822C1B362B91C793L, 0x4EB14655FB13DFD8L,
+ 0x1ECBBA0714E2A97BL, 0x6143459D5CDE5F14L, 0x53A8FBF1D5F0AC89L,
+ 0x97EA04D81C5E5B00L, 0x622181A8D4FDB3F3L, 0xE9BCD341572A1208L,
+ 0x1411258643CCE58AL, 0x9144C5FEA4C6E0A4L, 0x0D33D06565CF620FL,
+ 0x54A48D489F219CA1L, 0xC43E5EAC6D63C821L, 0xA9728B3A72770DAFL,
+ 0xD7934E7B20DF87EFL, 0xE35503B61A3E86E5L, 0xCAE321FBC819D504L,
+ 0x129A50B3AC60BFA6L, 0xCD5E68EA7E9FB6C3L, 0xB01C90199483B1C7L,
+ 0x3DE93CD5C295376CL, 0xAED52EDF2AB9AD13L, 0x2E60F512C0A07884L,
+ 0xBC3D86A3E36210C9L, 0x35269D9B163951CEL, 0x0C7D6E2AD0CDB5FAL,
+ 0x59E86297D87F5733L, 0x298EF221898DB0E7L, 0x55000029D1A5AA7EL,
+ 0x8BC08AE1B5061B45L, 0xC2C31C2B6C92703AL, 0x94CC596BAF25EF42L,
+ 0x0A1D73DB22540456L, 0x04B6A0F9D9C4179AL, 0xEFFDAFA2AE3D3C60L,
+ 0xF7C8075BB49496C4L, 0x9CC5C7141D1CD4E3L, 0x78BD1638218E5534L,
+ 0xB2F11568F850246AL, 0xEDFABCFA9502BC29L, 0x796CE5F2DA23051BL,
+ 0xAAE128B0DC93537CL, 0x3A493DA0EE4B29AEL, 0xB5DF6B2C416895D7L,
+ 0xFCABBD25122D7F37L, 0x70810B58105DC4B1L, 0xE10FDD37F7882A90L,
+ 0x524DCAB5518A3F5CL, 0x3C9E85878451255BL, 0x4029828119BD34E2L,
+ 0x74A05B6F5D3CECCBL, 0xB610021542E13ECAL, 0x0FF979D12F59E2ACL,
+ 0x6037DA27E4F9CC50L, 0x5E92975A0DF1847DL, 0xD66DE190D3E623FEL,
+ 0x5032D6B87B568048L, 0x9A36B7CE8235216EL, 0x80272A7A24F64B4AL,
+ 0x93EFED8B8C6916F7L, 0x37DDBFF44CCE1555L, 0x4B95DB5D4B99BD25L,
+ 0x92D3FDA169812FC0L, 0xFB1A4A9A90660BB6L, 0x730C196946A4B9B2L,
+ 0x81E289AA7F49DA68L, 0x64669A0F83B1A05FL, 0x27B3FF7D9644F48BL,
+ 0xCC6B615C8DB675B3L, 0x674F20B9BCEBBE95L, 0x6F31238275655982L,
+ 0x5AE488713E45CF05L, 0xBF619F9954C21157L, 0xEABAC46040A8EAE9L,
+ 0x454C6FE9F2C0C1CDL, 0x419CF6496412691CL, 0xD3DC3BEF265B0F70L,
+ 0x6D0E60F5C3578A9EL };
/** S-Box T4. */
- private static final long[] T4 = { 0x5B0E608526323C55L, 0x1A46C1A9FA1B59F5L,
- 0xA9E245A17C4C8FFAL, 0x65CA5159DB2955D7L,
- 0x05DB0A76CE35AFC2L, 0x81EAC77EA9113D45L,
- 0x528EF88AB6AC0A0DL, 0xA09EA253597BE3FFL,
- 0x430DDFB3AC48CD56L, 0xC4B3A67AF45CE46FL,
- 0x4ECECFD8FBE2D05EL, 0x3EF56F10B39935F0L,
- 0x0B22D6829CD619C6L, 0x17FD460A74DF2069L,
- 0x6CF8CC8E8510ED40L, 0xD6C824BF3A6ECAA7L,
- 0x61243D581A817049L, 0x048BACB6BBC163A2L,
- 0xD9A38AC27D44CC32L, 0x7FDDFF5BAAF410ABL,
- 0xAD6D495AA804824BL, 0xE1A6A74F2D8C9F94L,
- 0xD4F7851235DEE8E3L, 0xFD4B7F886540D893L,
- 0x247C20042AA4BFDAL, 0x096EA1C517D1327CL,
- 0xD56966B4361A6685L, 0x277DA5C31221057DL,
- 0x94D59893A43ACFF7L, 0x64F0C51CCDC02281L,
- 0x3D33BCC4FF6189DBL, 0xE005CB184CE66AF1L,
- 0xFF5CCD1D1DB99BEAL, 0xB0B854A7FE42980FL,
- 0x7BD46A6A718D4B9FL, 0xD10FA8CC22A5FD8CL,
- 0xD31484952BE4BD31L, 0xC7FA975FCB243847L,
- 0x4886ED1E5846C407L, 0x28CDDB791EB70B04L,
- 0xC2B00BE2F573417FL, 0x5C9590452180F877L,
- 0x7A6BDDFFF370EB00L, 0xCE509E38D6D9D6A4L,
- 0xEBEB0F00647FA702L, 0x1DCC06CF76606F06L,
- 0xE4D9F28BA286FF0AL, 0xD85A305DC918C262L,
- 0x475B1D8732225F54L, 0x2D4FB51668CCB5FEL,
- 0xA679B9D9D72BBA20L, 0x53841C0D912D43A5L,
- 0x3B7EAA48BF12A4E8L, 0x781E0E47F22F1DDFL,
- 0xEFF20CE60AB50973L, 0x20D261D19DFFB742L,
- 0x16A12B03062A2E39L, 0x1960EB2239650495L,
- 0x251C16FED50EB8B8L, 0x9AC0C330F826016EL,
- 0xED152665953E7671L, 0x02D63194A6369570L,
- 0x5074F08394B1C987L, 0x70BA598C90B25CE1L,
- 0x794A15810B9742F6L, 0x0D5925E9FCAF8C6CL,
- 0x3067716CD868744EL, 0x910AB077E8D7731BL,
- 0x6A61BBDB5AC42F61L, 0x93513EFBF0851567L,
- 0xF494724B9E83E9D5L, 0xE887E1985C09648DL,
- 0x34B1D3C675370CFDL, 0xDC35E433BC0D255DL,
- 0xD0AAB84234131BE0L, 0x08042A50B48B7EAFL,
- 0x9997C4EE44A3AB35L, 0x829A7B49201799D0L,
- 0x263B8307B7C54441L, 0x752F95F4FD6A6CA6L,
- 0x927217402C08C6E5L, 0x2A8AB754A795D9EEL,
- 0xA442F7552F72943DL, 0x2C31334E19781208L,
- 0x4FA98D7CEAEE6291L, 0x55C3862F665DB309L,
- 0xBD0610175D53B1F3L, 0x46FE6CB840413F27L,
- 0x3FE03792DF0CFA59L, 0xCFE700372EB85E8FL,
- 0xA7BE29E7ADBCE118L, 0xE544EE5CDE8431DDL,
- 0x8A781B1B41F1873EL, 0xA5C94C78A0D2F0E7L,
- 0x39412E2877B60728L, 0xA1265EF3AFC9A62CL,
- 0xBCC2770C6A2506C5L, 0x3AB66DD5DCE1CE12L,
- 0xE65499D04A675B37L, 0x7D8F523481BFD216L,
- 0x0F6F64FCEC15F389L, 0x74EFBE618B5B13C8L,
- 0xACDC82B714273E1DL, 0xDD40BFE003199D17L,
- 0x37E99257E7E061F8L, 0xFA52626904775AAAL,
- 0x8BBBF63A463D56F9L, 0xF0013F1543A26E64L,
- 0xA8307E9F879EC898L, 0xCC4C27A4150177CCL,
- 0x1B432F2CCA1D3348L, 0xDE1D1F8F9F6FA013L,
- 0x606602A047A7DDD6L, 0xD237AB64CC1CB2C7L,
- 0x9B938E7225FCD1D3L, 0xEC4E03708E0FF476L,
- 0xFEB2FBDA3D03C12DL, 0xAE0BCED2EE43889AL,
- 0x22CB8923EBFB4F43L, 0x69360D013CF7396DL,
- 0x855E3602D2D4E022L, 0x073805BAD01F784CL,
- 0x33E17A133852F546L, 0xDF4874058AC7B638L,
- 0xBA92B29C678AA14AL, 0x0CE89FC76CFAADCDL,
- 0x5F9D4E0908339E34L, 0xF1AFE9291F5923B9L,
- 0x6E3480F60F4A265FL, 0xEEBF3A2AB29B841CL,
- 0xE21938A88F91B4ADL, 0x57DFEFF845C6D3C3L,
- 0x2F006B0BF62CAAF2L, 0x62F479EF6F75EE78L,
- 0x11A55AD41C8916A9L, 0xF229D29084FED453L,
- 0x42F1C27B16B000E6L, 0x2B1F76749823C074L,
- 0x4B76ECA3C2745360L, 0x8C98F463B91691BDL,
- 0x14BCC93CF1ADE66AL, 0x8885213E6D458397L,
- 0x8E177DF0274D4711L, 0xB49B73B5503F2951L,
- 0x10168168C3F96B6BL, 0x0E3D963B63CAB0AEL,
- 0x8DFC4B5655A1DB14L, 0xF789F1356E14DE5CL,
- 0x683E68AF4E51DAC1L, 0xC9A84F9D8D4B0FD9L,
- 0x3691E03F52A0F9D1L, 0x5ED86E46E1878E80L,
- 0x3C711A0E99D07150L, 0x5A0865B20C4E9310L,
- 0x56FBFC1FE4F0682EL, 0xEA8D5DE3105EDF9BL,
- 0x71ABFDB12379187AL, 0x2EB99DE1BEE77B9CL,
- 0x21ECC0EA33CF4523L, 0x59A4D7521805C7A1L,
- 0x3896F5EB56AE7C72L, 0xAA638F3DB18F75DCL,
- 0x9F39358DABE9808EL, 0xB7DEFA91C00B72ACL,
- 0x6B5541FD62492D92L, 0x6DC6DEE8F92E4D5BL,
- 0x353F57ABC4BEEA7EL, 0x735769D6DA5690CEL,
- 0x0A234AA642391484L, 0xF6F9508028F80D9DL,
- 0xB8E319A27AB3F215L, 0x31AD9C1151341A4DL,
- 0x773C22A57BEF5805L, 0x45C7561A07968633L,
- 0xF913DA9E249DBE36L, 0xDA652D9B78A64C68L,
- 0x4C27A97F3BC334EFL, 0x76621220E66B17F4L,
- 0x967743899ACD7D0BL, 0xF3EE5BCAE0ED6782L,
- 0x409F753600C879FCL, 0x06D09A39B5926DB6L,
- 0x6F83AEB0317AC588L, 0x01E6CA4A86381F21L,
- 0x66FF3462D19F3025L, 0x72207C24DDFD3BFBL,
- 0x4AF6B6D3E2ECE2EBL, 0x9C994DBEC7EA08DEL,
- 0x49ACE597B09A8BC4L, 0xB38C4766CF0797BAL,
- 0x131B9373C57C2A75L, 0xB1822CCE61931E58L,
- 0x9D7555B909BA1C0CL, 0x127FAFDD937D11D2L,
- 0x29DA3BADC66D92E4L, 0xA2C1D57154C2ECBCL,
- 0x58C5134D82F6FE24L, 0x1C3AE3515B62274FL,
- 0xE907C82E01CB8126L, 0xF8ED091913E37FCBL,
- 0x3249D8F9C80046C9L, 0x80CF9BEDE388FB63L,
- 0x1881539A116CF19EL, 0x5103F3F76BD52457L,
- 0x15B7E6F5AE47F7A8L, 0xDBD7C6DED47E9CCFL,
- 0x44E55C410228BB1AL, 0xB647D4255EDB4E99L,
- 0x5D11882BB8AAFC30L, 0xF5098BBB29D3212AL,
- 0x8FB5EA14E90296B3L, 0x677B942157DD025AL,
- 0xFB58E7C0A390ACB5L, 0x89D3674C83BD4A01L,
- 0x9E2DA4DF4BF3B93BL, 0xFCC41E328CAB4829L,
- 0x03F38C96BA582C52L, 0xCAD1BDBD7FD85DB2L,
- 0xBBB442C16082AE83L, 0xB95FE86BA5DA9AB0L,
- 0xB22E04673771A93FL, 0x845358C9493152D8L,
- 0xBE2A488697B4541EL, 0x95A2DC2DD38E6966L,
- 0xC02C11AC923C852BL, 0x2388B1990DF2A87BL,
- 0x7C8008FA1B4F37BEL, 0x1F70D0C84D54E503L,
- 0x5490ADEC7ECE57D4L, 0x002B3C27D9063A3AL,
- 0x7EAEA3848030A2BFL, 0xC602326DED2003C0L,
- 0x83A7287D69A94086L, 0xC57A5FCB30F57A8AL,
- 0xB56844E479EBE779L, 0xA373B40F05DCBCE9L,
- 0xD71A786E88570EE2L, 0x879CBACDBDE8F6A0L,
- 0x976AD1BCC164A32FL, 0xAB21E25E9666D78BL,
- 0x901063AAE5E5C33CL, 0x9818B34448698D90L,
- 0xE36487AE3E1E8ABBL, 0xAFBDF931893BDCB4L,
- 0x6345A0DC5FBBD519L, 0x8628FE269B9465CAL,
- 0x1E5D01603F9C51ECL, 0x4DE44006A15049B7L,
- 0xBF6C70E5F776CBB1L, 0x411218F2EF552BEDL,
- 0xCB0C0708705A36A3L, 0xE74D14754F986044L,
- 0xCD56D9430EA8280EL, 0xC12591D7535F5065L,
- 0xC83223F1720AEF96L, 0xC3A0396F7363A51FL };
+ private static final long[] T4 = {
+ 0x5B0E608526323C55L, 0x1A46C1A9FA1B59F5L, 0xA9E245A17C4C8FFAL,
+ 0x65CA5159DB2955D7L, 0x05DB0A76CE35AFC2L, 0x81EAC77EA9113D45L,
+ 0x528EF88AB6AC0A0DL, 0xA09EA253597BE3FFL, 0x430DDFB3AC48CD56L,
+ 0xC4B3A67AF45CE46FL, 0x4ECECFD8FBE2D05EL, 0x3EF56F10B39935F0L,
+ 0x0B22D6829CD619C6L, 0x17FD460A74DF2069L, 0x6CF8CC8E8510ED40L,
+ 0xD6C824BF3A6ECAA7L, 0x61243D581A817049L, 0x048BACB6BBC163A2L,
+ 0xD9A38AC27D44CC32L, 0x7FDDFF5BAAF410ABL, 0xAD6D495AA804824BL,
+ 0xE1A6A74F2D8C9F94L, 0xD4F7851235DEE8E3L, 0xFD4B7F886540D893L,
+ 0x247C20042AA4BFDAL, 0x096EA1C517D1327CL, 0xD56966B4361A6685L,
+ 0x277DA5C31221057DL, 0x94D59893A43ACFF7L, 0x64F0C51CCDC02281L,
+ 0x3D33BCC4FF6189DBL, 0xE005CB184CE66AF1L, 0xFF5CCD1D1DB99BEAL,
+ 0xB0B854A7FE42980FL, 0x7BD46A6A718D4B9FL, 0xD10FA8CC22A5FD8CL,
+ 0xD31484952BE4BD31L, 0xC7FA975FCB243847L, 0x4886ED1E5846C407L,
+ 0x28CDDB791EB70B04L, 0xC2B00BE2F573417FL, 0x5C9590452180F877L,
+ 0x7A6BDDFFF370EB00L, 0xCE509E38D6D9D6A4L, 0xEBEB0F00647FA702L,
+ 0x1DCC06CF76606F06L, 0xE4D9F28BA286FF0AL, 0xD85A305DC918C262L,
+ 0x475B1D8732225F54L, 0x2D4FB51668CCB5FEL, 0xA679B9D9D72BBA20L,
+ 0x53841C0D912D43A5L, 0x3B7EAA48BF12A4E8L, 0x781E0E47F22F1DDFL,
+ 0xEFF20CE60AB50973L, 0x20D261D19DFFB742L, 0x16A12B03062A2E39L,
+ 0x1960EB2239650495L, 0x251C16FED50EB8B8L, 0x9AC0C330F826016EL,
+ 0xED152665953E7671L, 0x02D63194A6369570L, 0x5074F08394B1C987L,
+ 0x70BA598C90B25CE1L, 0x794A15810B9742F6L, 0x0D5925E9FCAF8C6CL,
+ 0x3067716CD868744EL, 0x910AB077E8D7731BL, 0x6A61BBDB5AC42F61L,
+ 0x93513EFBF0851567L, 0xF494724B9E83E9D5L, 0xE887E1985C09648DL,
+ 0x34B1D3C675370CFDL, 0xDC35E433BC0D255DL, 0xD0AAB84234131BE0L,
+ 0x08042A50B48B7EAFL, 0x9997C4EE44A3AB35L, 0x829A7B49201799D0L,
+ 0x263B8307B7C54441L, 0x752F95F4FD6A6CA6L, 0x927217402C08C6E5L,
+ 0x2A8AB754A795D9EEL, 0xA442F7552F72943DL, 0x2C31334E19781208L,
+ 0x4FA98D7CEAEE6291L, 0x55C3862F665DB309L, 0xBD0610175D53B1F3L,
+ 0x46FE6CB840413F27L, 0x3FE03792DF0CFA59L, 0xCFE700372EB85E8FL,
+ 0xA7BE29E7ADBCE118L, 0xE544EE5CDE8431DDL, 0x8A781B1B41F1873EL,
+ 0xA5C94C78A0D2F0E7L, 0x39412E2877B60728L, 0xA1265EF3AFC9A62CL,
+ 0xBCC2770C6A2506C5L, 0x3AB66DD5DCE1CE12L, 0xE65499D04A675B37L,
+ 0x7D8F523481BFD216L, 0x0F6F64FCEC15F389L, 0x74EFBE618B5B13C8L,
+ 0xACDC82B714273E1DL, 0xDD40BFE003199D17L, 0x37E99257E7E061F8L,
+ 0xFA52626904775AAAL, 0x8BBBF63A463D56F9L, 0xF0013F1543A26E64L,
+ 0xA8307E9F879EC898L, 0xCC4C27A4150177CCL, 0x1B432F2CCA1D3348L,
+ 0xDE1D1F8F9F6FA013L, 0x606602A047A7DDD6L, 0xD237AB64CC1CB2C7L,
+ 0x9B938E7225FCD1D3L, 0xEC4E03708E0FF476L, 0xFEB2FBDA3D03C12DL,
+ 0xAE0BCED2EE43889AL, 0x22CB8923EBFB4F43L, 0x69360D013CF7396DL,
+ 0x855E3602D2D4E022L, 0x073805BAD01F784CL, 0x33E17A133852F546L,
+ 0xDF4874058AC7B638L, 0xBA92B29C678AA14AL, 0x0CE89FC76CFAADCDL,
+ 0x5F9D4E0908339E34L, 0xF1AFE9291F5923B9L, 0x6E3480F60F4A265FL,
+ 0xEEBF3A2AB29B841CL, 0xE21938A88F91B4ADL, 0x57DFEFF845C6D3C3L,
+ 0x2F006B0BF62CAAF2L, 0x62F479EF6F75EE78L, 0x11A55AD41C8916A9L,
+ 0xF229D29084FED453L, 0x42F1C27B16B000E6L, 0x2B1F76749823C074L,
+ 0x4B76ECA3C2745360L, 0x8C98F463B91691BDL, 0x14BCC93CF1ADE66AL,
+ 0x8885213E6D458397L, 0x8E177DF0274D4711L, 0xB49B73B5503F2951L,
+ 0x10168168C3F96B6BL, 0x0E3D963B63CAB0AEL, 0x8DFC4B5655A1DB14L,
+ 0xF789F1356E14DE5CL, 0x683E68AF4E51DAC1L, 0xC9A84F9D8D4B0FD9L,
+ 0x3691E03F52A0F9D1L, 0x5ED86E46E1878E80L, 0x3C711A0E99D07150L,
+ 0x5A0865B20C4E9310L, 0x56FBFC1FE4F0682EL, 0xEA8D5DE3105EDF9BL,
+ 0x71ABFDB12379187AL, 0x2EB99DE1BEE77B9CL, 0x21ECC0EA33CF4523L,
+ 0x59A4D7521805C7A1L, 0x3896F5EB56AE7C72L, 0xAA638F3DB18F75DCL,
+ 0x9F39358DABE9808EL, 0xB7DEFA91C00B72ACL, 0x6B5541FD62492D92L,
+ 0x6DC6DEE8F92E4D5BL, 0x353F57ABC4BEEA7EL, 0x735769D6DA5690CEL,
+ 0x0A234AA642391484L, 0xF6F9508028F80D9DL, 0xB8E319A27AB3F215L,
+ 0x31AD9C1151341A4DL, 0x773C22A57BEF5805L, 0x45C7561A07968633L,
+ 0xF913DA9E249DBE36L, 0xDA652D9B78A64C68L, 0x4C27A97F3BC334EFL,
+ 0x76621220E66B17F4L, 0x967743899ACD7D0BL, 0xF3EE5BCAE0ED6782L,
+ 0x409F753600C879FCL, 0x06D09A39B5926DB6L, 0x6F83AEB0317AC588L,
+ 0x01E6CA4A86381F21L, 0x66FF3462D19F3025L, 0x72207C24DDFD3BFBL,
+ 0x4AF6B6D3E2ECE2EBL, 0x9C994DBEC7EA08DEL, 0x49ACE597B09A8BC4L,
+ 0xB38C4766CF0797BAL, 0x131B9373C57C2A75L, 0xB1822CCE61931E58L,
+ 0x9D7555B909BA1C0CL, 0x127FAFDD937D11D2L, 0x29DA3BADC66D92E4L,
+ 0xA2C1D57154C2ECBCL, 0x58C5134D82F6FE24L, 0x1C3AE3515B62274FL,
+ 0xE907C82E01CB8126L, 0xF8ED091913E37FCBL, 0x3249D8F9C80046C9L,
+ 0x80CF9BEDE388FB63L, 0x1881539A116CF19EL, 0x5103F3F76BD52457L,
+ 0x15B7E6F5AE47F7A8L, 0xDBD7C6DED47E9CCFL, 0x44E55C410228BB1AL,
+ 0xB647D4255EDB4E99L, 0x5D11882BB8AAFC30L, 0xF5098BBB29D3212AL,
+ 0x8FB5EA14E90296B3L, 0x677B942157DD025AL, 0xFB58E7C0A390ACB5L,
+ 0x89D3674C83BD4A01L, 0x9E2DA4DF4BF3B93BL, 0xFCC41E328CAB4829L,
+ 0x03F38C96BA582C52L, 0xCAD1BDBD7FD85DB2L, 0xBBB442C16082AE83L,
+ 0xB95FE86BA5DA9AB0L, 0xB22E04673771A93FL, 0x845358C9493152D8L,
+ 0xBE2A488697B4541EL, 0x95A2DC2DD38E6966L, 0xC02C11AC923C852BL,
+ 0x2388B1990DF2A87BL, 0x7C8008FA1B4F37BEL, 0x1F70D0C84D54E503L,
+ 0x5490ADEC7ECE57D4L, 0x002B3C27D9063A3AL, 0x7EAEA3848030A2BFL,
+ 0xC602326DED2003C0L, 0x83A7287D69A94086L, 0xC57A5FCB30F57A8AL,
+ 0xB56844E479EBE779L, 0xA373B40F05DCBCE9L, 0xD71A786E88570EE2L,
+ 0x879CBACDBDE8F6A0L, 0x976AD1BCC164A32FL, 0xAB21E25E9666D78BL,
+ 0x901063AAE5E5C33CL, 0x9818B34448698D90L, 0xE36487AE3E1E8ABBL,
+ 0xAFBDF931893BDCB4L, 0x6345A0DC5FBBD519L, 0x8628FE269B9465CAL,
+ 0x1E5D01603F9C51ECL, 0x4DE44006A15049B7L, 0xBF6C70E5F776CBB1L,
+ 0x411218F2EF552BEDL, 0xCB0C0708705A36A3L, 0xE74D14754F986044L,
+ 0xCD56D9430EA8280EL, 0xC12591D7535F5065L, 0xC83223F1720AEF96L,
+ 0xC3A0396F7363A51FL };
// The cached self-test result.
private static Boolean valid;
@@ -602,9 +436,6 @@ public class Tiger extends BaseHash
// The context.
private long a, b, c;
- // Constructors.
- // -----------------------------------------------------------------------
-
/**
* Trivial 0-arguments constructor.
*/
@@ -628,9 +459,6 @@ public class Tiger extends BaseHash
this.buffer = (that.buffer != null) ? (byte[]) that.buffer.clone() : null;
}
- // Instance methods implementing BaseHash.
- // -----------------------------------------------------------------------
-
public Object clone()
{
return new Tiger(this);
@@ -640,42 +468,39 @@ public class Tiger extends BaseHash
{
if (valid == null)
{
- valid = Boolean.valueOf(DIGEST0.equals(Util.toString(new Tiger().digest())));
+ String d = Util.toString(new Tiger().digest());
+ valid = Boolean.valueOf(DIGEST0.equals(d));
}
return valid.booleanValue();
}
protected byte[] padBuffer()
{
- int n = (int) (count % BLOCK_SIZE);
+ int n = (int)(count % BLOCK_SIZE);
int padding = (n < 56) ? (56 - n) : (120 - n);
byte[] pad = new byte[padding + 8];
-
pad[0] = 1;
long bits = count << 3;
-
pad[padding++] = (byte) bits;
- pad[padding++] = (byte) (bits >>> 8);
- pad[padding++] = (byte) (bits >>> 16);
- pad[padding++] = (byte) (bits >>> 24);
- pad[padding++] = (byte) (bits >>> 32);
- pad[padding++] = (byte) (bits >>> 40);
- pad[padding++] = (byte) (bits >>> 48);
- pad[padding] = (byte) (bits >>> 56);
-
+ pad[padding++] = (byte)(bits >>> 8);
+ pad[padding++] = (byte)(bits >>> 16);
+ pad[padding++] = (byte)(bits >>> 24);
+ pad[padding++] = (byte)(bits >>> 32);
+ pad[padding++] = (byte)(bits >>> 40);
+ pad[padding++] = (byte)(bits >>> 48);
+ pad[padding ] = (byte)(bits >>> 56);
return pad;
}
protected byte[] getResult()
{
- return new byte[] { (byte) a, (byte) (a >>> 8), (byte) (a >>> 16),
- (byte) (a >>> 24), (byte) (a >>> 32), (byte) (a >>> 40),
- (byte) (a >>> 48), (byte) (a >>> 56), (byte) b,
- (byte) (b >>> 8), (byte) (b >>> 16), (byte) (b >>> 24),
- (byte) (b >>> 32), (byte) (b >>> 40), (byte) (b >>> 48),
- (byte) (b >>> 56), (byte) c, (byte) (c >>> 8),
- (byte) (c >>> 16), (byte) (c >>> 24), (byte) (c >>> 32),
- (byte) (c >>> 40), (byte) (c >>> 48), (byte) (c >>> 56) };
+ return new byte[] {
+ (byte) a, (byte)(a >>> 8), (byte)(a >>> 16), (byte)(a >>> 24),
+ (byte)(a >>> 32), (byte)(a >>> 40), (byte)(a >>> 48), (byte)(a >>> 56),
+ (byte) b, (byte)(b >>> 8), (byte)(b >>> 16), (byte)(b >>> 24),
+ (byte)(b >>> 32), (byte)(b >>> 40), (byte)(b >>> 48), (byte)(b >>> 56),
+ (byte) c, (byte)(c >>> 8), (byte)(c >>> 16), (byte)(c >>> 24),
+ (byte)(c >>> 32), (byte)(c >>> 40), (byte)(c >>> 48), (byte)(c >>> 56) };
}
protected void resetContext()
@@ -688,117 +513,153 @@ public class Tiger extends BaseHash
protected void transform(byte[] in, int offset)
{
long x0, x1, x2, x3, x4, x5, x6, x7;
-
- x0 = ((long) in[offset++] & 0xFF) | ((long) (in[offset++] & 0xFF) << 8)
- | ((long) (in[offset++] & 0xFF) << 16)
- | ((long) (in[offset++] & 0xFF) << 24)
- | ((long) (in[offset++] & 0xFF) << 32)
- | ((long) (in[offset++] & 0xFF) << 40)
- | ((long) (in[offset++] & 0xFF) << 48)
- | ((long) (in[offset++] & 0xFF) << 56);
- x1 = ((long) in[offset++] & 0xFF) | ((long) (in[offset++] & 0xFF) << 8)
- | ((long) (in[offset++] & 0xFF) << 16)
- | ((long) (in[offset++] & 0xFF) << 24)
- | ((long) (in[offset++] & 0xFF) << 32)
- | ((long) (in[offset++] & 0xFF) << 40)
- | ((long) (in[offset++] & 0xFF) << 48)
- | ((long) (in[offset++] & 0xFF) << 56);
- x2 = ((long) in[offset++] & 0xFF) | ((long) (in[offset++] & 0xFF) << 8)
- | ((long) (in[offset++] & 0xFF) << 16)
- | ((long) (in[offset++] & 0xFF) << 24)
- | ((long) (in[offset++] & 0xFF) << 32)
- | ((long) (in[offset++] & 0xFF) << 40)
- | ((long) (in[offset++] & 0xFF) << 48)
- | ((long) (in[offset++] & 0xFF) << 56);
- x3 = ((long) in[offset++] & 0xFF) | ((long) (in[offset++] & 0xFF) << 8)
- | ((long) (in[offset++] & 0xFF) << 16)
- | ((long) (in[offset++] & 0xFF) << 24)
- | ((long) (in[offset++] & 0xFF) << 32)
- | ((long) (in[offset++] & 0xFF) << 40)
- | ((long) (in[offset++] & 0xFF) << 48)
- | ((long) (in[offset++] & 0xFF) << 56);
- x4 = ((long) in[offset++] & 0xFF) | ((long) (in[offset++] & 0xFF) << 8)
- | ((long) (in[offset++] & 0xFF) << 16)
- | ((long) (in[offset++] & 0xFF) << 24)
- | ((long) (in[offset++] & 0xFF) << 32)
- | ((long) (in[offset++] & 0xFF) << 40)
- | ((long) (in[offset++] & 0xFF) << 48)
- | ((long) (in[offset++] & 0xFF) << 56);
- x5 = ((long) in[offset++] & 0xFF) | ((long) (in[offset++] & 0xFF) << 8)
- | ((long) (in[offset++] & 0xFF) << 16)
- | ((long) (in[offset++] & 0xFF) << 24)
- | ((long) (in[offset++] & 0xFF) << 32)
- | ((long) (in[offset++] & 0xFF) << 40)
- | ((long) (in[offset++] & 0xFF) << 48)
- | ((long) (in[offset++] & 0xFF) << 56);
- x6 = ((long) in[offset++] & 0xFF) | ((long) (in[offset++] & 0xFF) << 8)
- | ((long) (in[offset++] & 0xFF) << 16)
- | ((long) (in[offset++] & 0xFF) << 24)
- | ((long) (in[offset++] & 0xFF) << 32)
- | ((long) (in[offset++] & 0xFF) << 40)
- | ((long) (in[offset++] & 0xFF) << 48)
- | ((long) (in[offset++] & 0xFF) << 56);
- x7 = ((long) in[offset++] & 0xFF) | ((long) (in[offset++] & 0xFF) << 8)
- | ((long) (in[offset++] & 0xFF) << 16)
- | ((long) (in[offset++] & 0xFF) << 24)
- | ((long) (in[offset++] & 0xFF) << 32)
- | ((long) (in[offset++] & 0xFF) << 40)
- | ((long) (in[offset++] & 0xFF) << 48)
- | ((long) (in[offset] & 0xFF) << 56);
-
+ x0 = ((long) in[offset++] & 0xFF)
+ | ((long) (in[offset++] & 0xFF) << 8)
+ | ((long) (in[offset++] & 0xFF) << 16)
+ | ((long) (in[offset++] & 0xFF) << 24)
+ | ((long) (in[offset++] & 0xFF) << 32)
+ | ((long) (in[offset++] & 0xFF) << 40)
+ | ((long) (in[offset++] & 0xFF) << 48)
+ | ((long) (in[offset++] & 0xFF) << 56);
+ x1 = ((long) in[offset++] & 0xFF)
+ | ((long) (in[offset++] & 0xFF) << 8)
+ | ((long) (in[offset++] & 0xFF) << 16)
+ | ((long) (in[offset++] & 0xFF) << 24)
+ | ((long) (in[offset++] & 0xFF) << 32)
+ | ((long) (in[offset++] & 0xFF) << 40)
+ | ((long) (in[offset++] & 0xFF) << 48)
+ | ((long) (in[offset++] & 0xFF) << 56);
+ x2 = ((long) in[offset++] & 0xFF)
+ | ((long) (in[offset++] & 0xFF) << 8)
+ | ((long) (in[offset++] & 0xFF) << 16)
+ | ((long) (in[offset++] & 0xFF) << 24)
+ | ((long) (in[offset++] & 0xFF) << 32)
+ | ((long) (in[offset++] & 0xFF) << 40)
+ | ((long) (in[offset++] & 0xFF) << 48)
+ | ((long) (in[offset++] & 0xFF) << 56);
+ x3 = ((long) in[offset++] & 0xFF)
+ | ((long) (in[offset++] & 0xFF) << 8)
+ | ((long) (in[offset++] & 0xFF) << 16)
+ | ((long) (in[offset++] & 0xFF) << 24)
+ | ((long) (in[offset++] & 0xFF) << 32)
+ | ((long) (in[offset++] & 0xFF) << 40)
+ | ((long) (in[offset++] & 0xFF) << 48)
+ | ((long) (in[offset++] & 0xFF) << 56);
+ x4 = ((long) in[offset++] & 0xFF)
+ | ((long) (in[offset++] & 0xFF) << 8)
+ | ((long) (in[offset++] & 0xFF) << 16)
+ | ((long) (in[offset++] & 0xFF) << 24)
+ | ((long) (in[offset++] & 0xFF) << 32)
+ | ((long) (in[offset++] & 0xFF) << 40)
+ | ((long) (in[offset++] & 0xFF) << 48)
+ | ((long) (in[offset++] & 0xFF) << 56);
+ x5 = ((long) in[offset++] & 0xFF)
+ | ((long) (in[offset++] & 0xFF) << 8)
+ | ((long) (in[offset++] & 0xFF) << 16)
+ | ((long) (in[offset++] & 0xFF) << 24)
+ | ((long) (in[offset++] & 0xFF) << 32)
+ | ((long) (in[offset++] & 0xFF) << 40)
+ | ((long) (in[offset++] & 0xFF) << 48)
+ | ((long) (in[offset++] & 0xFF) << 56);
+ x6 = ((long) in[offset++] & 0xFF)
+ | ((long) (in[offset++] & 0xFF) << 8)
+ | ((long) (in[offset++] & 0xFF) << 16)
+ | ((long) (in[offset++] & 0xFF) << 24)
+ | ((long) (in[offset++] & 0xFF) << 32)
+ | ((long) (in[offset++] & 0xFF) << 40)
+ | ((long) (in[offset++] & 0xFF) << 48)
+ | ((long) (in[offset++] & 0xFF) << 56);
+ x7 = ((long) in[offset++] & 0xFF)
+ | ((long) (in[offset++] & 0xFF) << 8)
+ | ((long) (in[offset++] & 0xFF) << 16)
+ | ((long) (in[offset++] & 0xFF) << 24)
+ | ((long) (in[offset++] & 0xFF) << 32)
+ | ((long) (in[offset++] & 0xFF) << 40)
+ | ((long) (in[offset++] & 0xFF) << 48)
+ | ((long) (in[offset ] & 0xFF) << 56);
// save_abc ::=
long aa = a, bb = b, cc = c;
-
// pass(aa, bb, cc, 5) ::=
cc ^= x0;
- aa -= T1[(int) cc & 0xff] ^ T2[(int) (cc >> 16) & 0xff]
- ^ T3[(int) (cc >> 32) & 0xff] ^ T4[(int) (cc >> 48) & 0xff];
- bb += T4[(int) (cc >> 8) & 0xff] ^ T3[(int) (cc >> 24) & 0xff]
- ^ T2[(int) (cc >> 40) & 0xff] ^ T1[(int) (cc >> 56) & 0xff];
+ aa -= T1[(int) cc & 0xff]
+ ^ T2[(int)(cc >> 16) & 0xff]
+ ^ T3[(int)(cc >> 32) & 0xff]
+ ^ T4[(int)(cc >> 48) & 0xff];
+ bb += T4[(int)(cc >> 8) & 0xff]
+ ^ T3[(int)(cc >> 24) & 0xff]
+ ^ T2[(int)(cc >> 40) & 0xff]
+ ^ T1[(int)(cc >> 56) & 0xff];
bb *= 5;
aa ^= x1;
- bb -= T1[(int) aa & 0xff] ^ T2[(int) (aa >> 16) & 0xff]
- ^ T3[(int) (aa >> 32) & 0xff] ^ T4[(int) (aa >> 48) & 0xff];
- cc += T4[(int) (aa >> 8) & 0xff] ^ T3[(int) (aa >> 24) & 0xff]
- ^ T2[(int) (aa >> 40) & 0xff] ^ T1[(int) (aa >> 56) & 0xff];
+ bb -= T1[(int) aa & 0xff]
+ ^ T2[(int)(aa >> 16) & 0xff]
+ ^ T3[(int)(aa >> 32) & 0xff]
+ ^ T4[(int)(aa >> 48) & 0xff];
+ cc += T4[(int)(aa >> 8) & 0xff]
+ ^ T3[(int)(aa >> 24) & 0xff]
+ ^ T2[(int)(aa >> 40) & 0xff]
+ ^ T1[(int)(aa >> 56) & 0xff];
cc *= 5;
bb ^= x2;
- cc -= T1[(int) bb & 0xff] ^ T2[(int) (bb >> 16) & 0xff]
- ^ T3[(int) (bb >> 32) & 0xff] ^ T4[(int) (bb >> 48) & 0xff];
- aa += T4[(int) (bb >> 8) & 0xff] ^ T3[(int) (bb >> 24) & 0xff]
- ^ T2[(int) (bb >> 40) & 0xff] ^ T1[(int) (bb >> 56) & 0xff];
+ cc -= T1[(int) bb & 0xff]
+ ^ T2[(int)(bb >> 16) & 0xff]
+ ^ T3[(int)(bb >> 32) & 0xff]
+ ^ T4[(int)(bb >> 48) & 0xff];
+ aa += T4[(int)(bb >> 8) & 0xff]
+ ^ T3[(int)(bb >> 24) & 0xff]
+ ^ T2[(int)(bb >> 40) & 0xff]
+ ^ T1[(int)(bb >> 56) & 0xff];
aa *= 5;
cc ^= x3;
- aa -= T1[(int) cc & 0xff] ^ T2[(int) (cc >> 16) & 0xff]
- ^ T3[(int) (cc >> 32) & 0xff] ^ T4[(int) (cc >> 48) & 0xff];
- bb += T4[(int) (cc >> 8) & 0xff] ^ T3[(int) (cc >> 24) & 0xff]
- ^ T2[(int) (cc >> 40) & 0xff] ^ T1[(int) (cc >> 56) & 0xff];
+ aa -= T1[(int) cc & 0xff]
+ ^ T2[(int)(cc >> 16) & 0xff]
+ ^ T3[(int)(cc >> 32) & 0xff]
+ ^ T4[(int)(cc >> 48) & 0xff];
+ bb += T4[(int)(cc >> 8) & 0xff]
+ ^ T3[(int)(cc >> 24) & 0xff]
+ ^ T2[(int)(cc >> 40) & 0xff]
+ ^ T1[(int)(cc >> 56) & 0xff];
bb *= 5;
aa ^= x4;
- bb -= T1[(int) aa & 0xff] ^ T2[(int) (aa >> 16) & 0xff]
- ^ T3[(int) (aa >> 32) & 0xff] ^ T4[(int) (aa >> 48) & 0xff];
- cc += T4[(int) (aa >> 8) & 0xff] ^ T3[(int) (aa >> 24) & 0xff]
- ^ T2[(int) (aa >> 40) & 0xff] ^ T1[(int) (aa >> 56) & 0xff];
+ bb -= T1[(int) aa & 0xff]
+ ^ T2[(int)(aa >> 16) & 0xff]
+ ^ T3[(int)(aa >> 32) & 0xff]
+ ^ T4[(int)(aa >> 48) & 0xff];
+ cc += T4[(int)(aa >> 8) & 0xff]
+ ^ T3[(int)(aa >> 24) & 0xff]
+ ^ T2[(int)(aa >> 40) & 0xff]
+ ^ T1[(int)(aa >> 56) & 0xff];
cc *= 5;
bb ^= x5;
- cc -= T1[(int) bb & 0xff] ^ T2[(int) (bb >> 16) & 0xff]
- ^ T3[(int) (bb >> 32) & 0xff] ^ T4[(int) (bb >> 48) & 0xff];
- aa += T4[(int) (bb >> 8) & 0xff] ^ T3[(int) (bb >> 24) & 0xff]
- ^ T2[(int) (bb >> 40) & 0xff] ^ T1[(int) (bb >> 56) & 0xff];
+ cc -= T1[(int) bb & 0xff]
+ ^ T2[(int)(bb >> 16) & 0xff]
+ ^ T3[(int)(bb >> 32) & 0xff]
+ ^ T4[(int)(bb >> 48) & 0xff];
+ aa += T4[(int)(bb >> 8) & 0xff]
+ ^ T3[(int)(bb >> 24) & 0xff]
+ ^ T2[(int)(bb >> 40) & 0xff]
+ ^ T1[(int)(bb >> 56) & 0xff];
aa *= 5;
cc ^= x6;
- aa -= T1[(int) cc & 0xff] ^ T2[(int) (cc >> 16) & 0xff]
- ^ T3[(int) (cc >> 32) & 0xff] ^ T4[(int) (cc >> 48) & 0xff];
- bb += T4[(int) (cc >> 8) & 0xff] ^ T3[(int) (cc >> 24) & 0xff]
- ^ T2[(int) (cc >> 40) & 0xff] ^ T1[(int) (cc >> 56) & 0xff];
+ aa -= T1[(int) cc & 0xff]
+ ^ T2[(int)(cc >> 16) & 0xff]
+ ^ T3[(int)(cc >> 32) & 0xff]
+ ^ T4[(int)(cc >> 48) & 0xff];
+ bb += T4[(int)(cc >> 8) & 0xff]
+ ^ T3[(int)(cc >> 24) & 0xff]
+ ^ T2[(int)(cc >> 40) & 0xff]
+ ^ T1[(int)(cc >> 56) & 0xff];
bb *= 5;
aa ^= x7;
- bb -= T1[(int) aa & 0xff] ^ T2[(int) (aa >> 16) & 0xff]
- ^ T3[(int) (aa >> 32) & 0xff] ^ T4[(int) (aa >> 48) & 0xff];
- cc += T4[(int) (aa >> 8) & 0xff] ^ T3[(int) (aa >> 24) & 0xff]
- ^ T2[(int) (aa >> 40) & 0xff] ^ T1[(int) (aa >> 56) & 0xff];
+ bb -= T1[(int) aa & 0xff]
+ ^ T2[(int)(aa >> 16) & 0xff]
+ ^ T3[(int)(aa >> 32) & 0xff]
+ ^ T4[(int)(aa >> 48) & 0xff];
+ cc += T4[(int)(aa >> 8) & 0xff]
+ ^ T3[(int)(aa >> 24) & 0xff]
+ ^ T2[(int)(aa >> 40) & 0xff]
+ ^ T1[(int)(aa >> 56) & 0xff];
cc *= 5;
-
// key_schedule ::=
x0 -= x7 ^ 0xA5A5A5A5A5A5A5A5L;
x1 ^= x0;
@@ -816,57 +677,87 @@ public class Tiger extends BaseHash
x5 ^= x4;
x6 += x5;
x7 -= x6 ^ 0x0123456789ABCDEFL;
-
// pass(cc, aa, bb, 7) ::=
bb ^= x0;
- cc -= T1[(int) bb & 0xff] ^ T2[(int) (bb >> 16) & 0xff]
- ^ T3[(int) (bb >> 32) & 0xff] ^ T4[(int) (bb >> 48) & 0xff];
- aa += T4[(int) (bb >> 8) & 0xff] ^ T3[(int) (bb >> 24) & 0xff]
- ^ T2[(int) (bb >> 40) & 0xff] ^ T1[(int) (bb >> 56) & 0xff];
+ cc -= T1[(int) bb & 0xff]
+ ^ T2[(int)(bb >> 16) & 0xff]
+ ^ T3[(int)(bb >> 32) & 0xff]
+ ^ T4[(int)(bb >> 48) & 0xff];
+ aa += T4[(int)(bb >> 8) & 0xff]
+ ^ T3[(int)(bb >> 24) & 0xff]
+ ^ T2[(int)(bb >> 40) & 0xff]
+ ^ T1[(int)(bb >> 56) & 0xff];
aa *= 7;
cc ^= x1;
- aa -= T1[(int) cc & 0xff] ^ T2[(int) (cc >> 16) & 0xff]
- ^ T3[(int) (cc >> 32) & 0xff] ^ T4[(int) (cc >> 48) & 0xff];
- bb += T4[(int) (cc >> 8) & 0xff] ^ T3[(int) (cc >> 24) & 0xff]
- ^ T2[(int) (cc >> 40) & 0xff] ^ T1[(int) (cc >> 56) & 0xff];
+ aa -= T1[(int) cc & 0xff]
+ ^ T2[(int)(cc >> 16) & 0xff]
+ ^ T3[(int)(cc >> 32) & 0xff]
+ ^ T4[(int)(cc >> 48) & 0xff];
+ bb += T4[(int)(cc >> 8) & 0xff]
+ ^ T3[(int)(cc >> 24) & 0xff]
+ ^ T2[(int)(cc >> 40) & 0xff]
+ ^ T1[(int)(cc >> 56) & 0xff];
bb *= 7;
aa ^= x2;
- bb -= T1[(int) aa & 0xff] ^ T2[(int) (aa >> 16) & 0xff]
- ^ T3[(int) (aa >> 32) & 0xff] ^ T4[(int) (aa >> 48) & 0xff];
- cc += T4[(int) (aa >> 8) & 0xff] ^ T3[(int) (aa >> 24) & 0xff]
- ^ T2[(int) (aa >> 40) & 0xff] ^ T1[(int) (aa >> 56) & 0xff];
+ bb -= T1[(int) aa & 0xff]
+ ^ T2[(int)(aa >> 16) & 0xff]
+ ^ T3[(int)(aa >> 32) & 0xff]
+ ^ T4[(int)(aa >> 48) & 0xff];
+ cc += T4[(int)(aa >> 8) & 0xff]
+ ^ T3[(int)(aa >> 24) & 0xff]
+ ^ T2[(int)(aa >> 40) & 0xff]
+ ^ T1[(int)(aa >> 56) & 0xff];
cc *= 7;
bb ^= x3;
- cc -= T1[(int) bb & 0xff] ^ T2[(int) (bb >> 16) & 0xff]
- ^ T3[(int) (bb >> 32) & 0xff] ^ T4[(int) (bb >> 48) & 0xff];
- aa += T4[(int) (bb >> 8) & 0xff] ^ T3[(int) (bb >> 24) & 0xff]
- ^ T2[(int) (bb >> 40) & 0xff] ^ T1[(int) (bb >> 56) & 0xff];
+ cc -= T1[(int) bb & 0xff]
+ ^ T2[(int)(bb >> 16) & 0xff]
+ ^ T3[(int)(bb >> 32) & 0xff]
+ ^ T4[(int)(bb >> 48) & 0xff];
+ aa += T4[(int)(bb >> 8) & 0xff]
+ ^ T3[(int)(bb >> 24) & 0xff]
+ ^ T2[(int)(bb >> 40) & 0xff]
+ ^ T1[(int)(bb >> 56) & 0xff];
aa *= 7;
cc ^= x4;
- aa -= T1[(int) cc & 0xff] ^ T2[(int) (cc >> 16) & 0xff]
- ^ T3[(int) (cc >> 32) & 0xff] ^ T4[(int) (cc >> 48) & 0xff];
- bb += T4[(int) (cc >> 8) & 0xff] ^ T3[(int) (cc >> 24) & 0xff]
- ^ T2[(int) (cc >> 40) & 0xff] ^ T1[(int) (cc >> 56) & 0xff];
+ aa -= T1[(int) cc & 0xff]
+ ^ T2[(int)(cc >> 16) & 0xff]
+ ^ T3[(int)(cc >> 32) & 0xff]
+ ^ T4[(int)(cc >> 48) & 0xff];
+ bb += T4[(int)(cc >> 8) & 0xff]
+ ^ T3[(int)(cc >> 24) & 0xff]
+ ^ T2[(int)(cc >> 40) & 0xff]
+ ^ T1[(int)(cc >> 56) & 0xff];
bb *= 7;
aa ^= x5;
- bb -= T1[(int) aa & 0xff] ^ T2[(int) (aa >> 16) & 0xff]
- ^ T3[(int) (aa >> 32) & 0xff] ^ T4[(int) (aa >> 48) & 0xff];
- cc += T4[(int) (aa >> 8) & 0xff] ^ T3[(int) (aa >> 24) & 0xff]
- ^ T2[(int) (aa >> 40) & 0xff] ^ T1[(int) (aa >> 56) & 0xff];
+ bb -= T1[(int) aa & 0xff]
+ ^ T2[(int)(aa >> 16) & 0xff]
+ ^ T3[(int)(aa >> 32) & 0xff]
+ ^ T4[(int)(aa >> 48) & 0xff];
+ cc += T4[(int)(aa >> 8) & 0xff]
+ ^ T3[(int)(aa >> 24) & 0xff]
+ ^ T2[(int)(aa >> 40) & 0xff]
+ ^ T1[(int)(aa >> 56) & 0xff];
cc *= 7;
bb ^= x6;
- cc -= T1[(int) bb & 0xff] ^ T2[(int) (bb >> 16) & 0xff]
- ^ T3[(int) (bb >> 32) & 0xff] ^ T4[(int) (bb >> 48) & 0xff];
- aa += T4[(int) (bb >> 8) & 0xff] ^ T3[(int) (bb >> 24) & 0xff]
- ^ T2[(int) (bb >> 40) & 0xff] ^ T1[(int) (bb >> 56) & 0xff];
+ cc -= T1[(int) bb & 0xff]
+ ^ T2[(int)(bb >> 16) & 0xff]
+ ^ T3[(int)(bb >> 32) & 0xff]
+ ^ T4[(int)(bb >> 48) & 0xff];
+ aa += T4[(int)(bb >> 8) & 0xff]
+ ^ T3[(int)(bb >> 24) & 0xff]
+ ^ T2[(int)(bb >> 40) & 0xff]
+ ^ T1[(int)(bb >> 56) & 0xff];
aa *= 7;
cc ^= x7;
- aa -= T1[(int) cc & 0xff] ^ T2[(int) (cc >> 16) & 0xff]
- ^ T3[(int) (cc >> 32) & 0xff] ^ T4[(int) (cc >> 48) & 0xff];
- bb += T4[(int) (cc >> 8) & 0xff] ^ T3[(int) (cc >> 24) & 0xff]
- ^ T2[(int) (cc >> 40) & 0xff] ^ T1[(int) (cc >> 56) & 0xff];
+ aa -= T1[(int) cc & 0xff]
+ ^ T2[(int)(cc >> 16) & 0xff]
+ ^ T3[(int)(cc >> 32) & 0xff]
+ ^ T4[(int)(cc >> 48) & 0xff];
+ bb += T4[(int)(cc >> 8) & 0xff]
+ ^ T3[(int)(cc >> 24) & 0xff]
+ ^ T2[(int)(cc >> 40) & 0xff]
+ ^ T1[(int)(cc >> 56) & 0xff];
bb *= 7;
-
// key_schedule ::=
x0 -= x7 ^ 0xA5A5A5A5A5A5A5A5L;
x1 ^= x0;
@@ -884,57 +775,87 @@ public class Tiger extends BaseHash
x5 ^= x4;
x6 += x5;
x7 -= x6 ^ 0x0123456789ABCDEFL;
-
// pass(bb,cc,aa,9) ::=
aa ^= x0;
- bb -= T1[(int) aa & 0xff] ^ T2[(int) (aa >> 16) & 0xff]
- ^ T3[(int) (aa >> 32) & 0xff] ^ T4[(int) (aa >> 48) & 0xff];
- cc += T4[(int) (aa >> 8) & 0xff] ^ T3[(int) (aa >> 24) & 0xff]
- ^ T2[(int) (aa >> 40) & 0xff] ^ T1[(int) (aa >> 56) & 0xff];
+ bb -= T1[(int) aa & 0xff]
+ ^ T2[(int)(aa >> 16) & 0xff]
+ ^ T3[(int)(aa >> 32) & 0xff]
+ ^ T4[(int)(aa >> 48) & 0xff];
+ cc += T4[(int)(aa >> 8) & 0xff]
+ ^ T3[(int)(aa >> 24) & 0xff]
+ ^ T2[(int)(aa >> 40) & 0xff]
+ ^ T1[(int)(aa >> 56) & 0xff];
cc *= 9;
bb ^= x1;
- cc -= T1[(int) bb & 0xff] ^ T2[(int) (bb >> 16) & 0xff]
- ^ T3[(int) (bb >> 32) & 0xff] ^ T4[(int) (bb >> 48) & 0xff];
- aa += T4[(int) (bb >> 8) & 0xff] ^ T3[(int) (bb >> 24) & 0xff]
- ^ T2[(int) (bb >> 40) & 0xff] ^ T1[(int) (bb >> 56) & 0xff];
+ cc -= T1[(int) bb & 0xff]
+ ^ T2[(int)(bb >> 16) & 0xff]
+ ^ T3[(int)(bb >> 32) & 0xff]
+ ^ T4[(int)(bb >> 48) & 0xff];
+ aa += T4[(int)(bb >> 8) & 0xff]
+ ^ T3[(int)(bb >> 24) & 0xff]
+ ^ T2[(int)(bb >> 40) & 0xff]
+ ^ T1[(int)(bb >> 56) & 0xff];
aa *= 9;
cc ^= x2;
- aa -= T1[(int) cc & 0xff] ^ T2[(int) (cc >> 16) & 0xff]
- ^ T3[(int) (cc >> 32) & 0xff] ^ T4[(int) (cc >> 48) & 0xff];
- bb += T4[(int) (cc >> 8) & 0xff] ^ T3[(int) (cc >> 24) & 0xff]
- ^ T2[(int) (cc >> 40) & 0xff] ^ T1[(int) (cc >> 56) & 0xff];
+ aa -= T1[(int) cc & 0xff]
+ ^ T2[(int)(cc >> 16) & 0xff]
+ ^ T3[(int)(cc >> 32) & 0xff]
+ ^ T4[(int)(cc >> 48) & 0xff];
+ bb += T4[(int)(cc >> 8) & 0xff]
+ ^ T3[(int)(cc >> 24) & 0xff]
+ ^ T2[(int)(cc >> 40) & 0xff]
+ ^ T1[(int)(cc >> 56) & 0xff];
bb *= 9;
aa ^= x3;
- bb -= T1[(int) aa & 0xff] ^ T2[(int) (aa >> 16) & 0xff]
- ^ T3[(int) (aa >> 32) & 0xff] ^ T4[(int) (aa >> 48) & 0xff];
- cc += T4[(int) (aa >> 8) & 0xff] ^ T3[(int) (aa >> 24) & 0xff]
- ^ T2[(int) (aa >> 40) & 0xff] ^ T1[(int) (aa >> 56) & 0xff];
+ bb -= T1[(int) aa & 0xff]
+ ^ T2[(int)(aa >> 16) & 0xff]
+ ^ T3[(int)(aa >> 32) & 0xff]
+ ^ T4[(int)(aa >> 48) & 0xff];
+ cc += T4[(int)(aa >> 8) & 0xff]
+ ^ T3[(int)(aa >> 24) & 0xff]
+ ^ T2[(int)(aa >> 40) & 0xff]
+ ^ T1[(int)(aa >> 56) & 0xff];
cc *= 9;
bb ^= x4;
- cc -= T1[(int) bb & 0xff] ^ T2[(int) (bb >> 16) & 0xff]
- ^ T3[(int) (bb >> 32) & 0xff] ^ T4[(int) (bb >> 48) & 0xff];
- aa += T4[(int) (bb >> 8) & 0xff] ^ T3[(int) (bb >> 24) & 0xff]
- ^ T2[(int) (bb >> 40) & 0xff] ^ T1[(int) (bb >> 56) & 0xff];
+ cc -= T1[(int) bb & 0xff]
+ ^ T2[(int)(bb >> 16) & 0xff]
+ ^ T3[(int)(bb >> 32) & 0xff]
+ ^ T4[(int)(bb >> 48) & 0xff];
+ aa += T4[(int)(bb >> 8) & 0xff]
+ ^ T3[(int)(bb >> 24) & 0xff]
+ ^ T2[(int)(bb >> 40) & 0xff]
+ ^ T1[(int)(bb >> 56) & 0xff];
aa *= 9;
cc ^= x5;
- aa -= T1[(int) cc & 0xff] ^ T2[(int) (cc >> 16) & 0xff]
- ^ T3[(int) (cc >> 32) & 0xff] ^ T4[(int) (cc >> 48) & 0xff];
- bb += T4[(int) (cc >> 8) & 0xff] ^ T3[(int) (cc >> 24) & 0xff]
- ^ T2[(int) (cc >> 40) & 0xff] ^ T1[(int) (cc >> 56) & 0xff];
+ aa -= T1[(int) cc & 0xff]
+ ^ T2[(int)(cc >> 16) & 0xff]
+ ^ T3[(int)(cc >> 32) & 0xff]
+ ^ T4[(int)(cc >> 48) & 0xff];
+ bb += T4[(int)(cc >> 8) & 0xff]
+ ^ T3[(int)(cc >> 24) & 0xff]
+ ^ T2[(int)(cc >> 40) & 0xff]
+ ^ T1[(int)(cc >> 56) & 0xff];
bb *= 9;
aa ^= x6;
- bb -= T1[(int) aa & 0xff] ^ T2[(int) (aa >> 16) & 0xff]
- ^ T3[(int) (aa >> 32) & 0xff] ^ T4[(int) (aa >> 48) & 0xff];
- cc += T4[(int) (aa >> 8) & 0xff] ^ T3[(int) (aa >> 24) & 0xff]
- ^ T2[(int) (aa >> 40) & 0xff] ^ T1[(int) (aa >> 56) & 0xff];
+ bb -= T1[(int) aa & 0xff]
+ ^ T2[(int)(aa >> 16) & 0xff]
+ ^ T3[(int)(aa >> 32) & 0xff]
+ ^ T4[(int)(aa >> 48) & 0xff];
+ cc += T4[(int)(aa >> 8) & 0xff]
+ ^ T3[(int)(aa >> 24) & 0xff]
+ ^ T2[(int)(aa >> 40) & 0xff]
+ ^ T1[(int)(aa >> 56) & 0xff];
cc *= 9;
bb ^= x7;
- cc -= T1[(int) bb & 0xff] ^ T2[(int) (bb >> 16) & 0xff]
- ^ T3[(int) (bb >> 32) & 0xff] ^ T4[(int) (bb >> 48) & 0xff];
- aa += T4[(int) (bb >> 8) & 0xff] ^ T3[(int) (bb >> 24) & 0xff]
- ^ T2[(int) (bb >> 40) & 0xff] ^ T1[(int) (bb >> 56) & 0xff];
+ cc -= T1[(int) bb & 0xff]
+ ^ T2[(int)(bb >> 16) & 0xff]
+ ^ T3[(int)(bb >> 32) & 0xff]
+ ^ T4[(int)(bb >> 48) & 0xff];
+ aa += T4[(int)(bb >> 8) & 0xff]
+ ^ T3[(int)(bb >> 24) & 0xff]
+ ^ T2[(int)(bb >> 40) & 0xff]
+ ^ T1[(int)(bb >> 56) & 0xff];
aa *= 9;
-
// feedforward ::=
a ^= aa;
b = bb - b;
diff --git a/libjava/classpath/gnu/java/security/hash/Whirlpool.java b/libjava/classpath/gnu/java/security/hash/Whirlpool.java
index b10fa53..89df5c5 100644
--- a/libjava/classpath/gnu/java/security/hash/Whirlpool.java
+++ b/libjava/classpath/gnu/java/security/hash/Whirlpool.java
@@ -38,9 +38,12 @@ exception statement from your version. */
package gnu.java.security.hash;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
+import java.util.logging.Logger;
+
/**
* Whirlpool, a new 512-bit hashing function operating on messages less than
* 2 ** 256 bits in length. The function structure is designed according to the
@@ -59,18 +62,10 @@ import gnu.java.security.util.Util;
* Vincent Rijmen.HAVAL
Service Provider Interface
- * (SPI) Adapter.initialize()
method), the GNU Crypto provider
- * uses a default modulus size (keysize) of 1024 bits.initialize()
method), the GNU provider uses a
+ * default modulus size (keysize) of 1024 bits.
*/
-public class DSSKeyPairGeneratorSpi extends KeyPairGeneratorAdapter implements
- DSAKeyPairGenerator
+public class DSSKeyPairGeneratorSpi
+ extends KeyPairGeneratorAdapter
+ implements DSAKeyPairGenerator
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public DSSKeyPairGeneratorSpi()
{
super(Registry.DSS_KPG);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
public void initialize(int keysize, SecureRandom random)
{
this.initialize(keysize, false, random);
@@ -90,43 +78,34 @@ public class DSSKeyPairGeneratorSpi extends KeyPairGeneratorAdapter implements
HashMap attributes = new HashMap();
if (params != null)
{
- if (!(params instanceof DSAParameterSpec))
+ if (! (params instanceof DSAParameterSpec))
throw new InvalidAlgorithmParameterException(
- "Parameters argument is not a non-null instance, or " +
- "sub-instance, of java.security.spec.DSAParameterSpec");
-
+ "Parameters argument is not a non-null instance, or "
+ + "sub-instance, of java.security.spec.DSAParameterSpec");
attributes.put(DSSKeyPairGenerator.DSS_PARAMETERS, params);
}
-
if (random != null)
- {
- attributes.put(DSSKeyPairGenerator.SOURCE_OF_RANDOMNESS, random);
- }
+ attributes.put(DSSKeyPairGenerator.SOURCE_OF_RANDOMNESS, random);
attributes.put(DSSKeyPairGenerator.PREFERRED_ENCODING_FORMAT,
- new Integer(Registry.ASN1_ENCODING_ID));
+ Integer.valueOf(Registry.ASN1_ENCODING_ID));
try
{
adaptee.setup(attributes);
}
catch (IllegalArgumentException x)
{
- InvalidAlgorithmParameterException y =
- new InvalidAlgorithmParameterException();
- y.initCause(x);
- throw y;
+ throw new InvalidAlgorithmParameterException(x.getMessage(), x);
}
}
- // java.security.interfaces.DSAKeyPairGenerator interface implementation -----
-
public void initialize(DSAParams params, SecureRandom random)
throws InvalidParameterException
{
if (params == null || !(params instanceof DSAParameterSpec))
throw new InvalidParameterException(
- "Parameters argument is either null or is not an instance, or " +
- "sub-instance, of java.security.spec.DSAParameterSpec");
+ "Parameters argument is either null or is not an instance, or "
+ + "sub-instance, of java.security.spec.DSAParameterSpec");
DSAParameterSpec spec = (DSAParameterSpec) params;
try
{
@@ -134,7 +113,7 @@ public class DSSKeyPairGeneratorSpi extends KeyPairGeneratorAdapter implements
}
catch (InvalidAlgorithmParameterException x)
{
- InvalidParameterException y = new InvalidParameterException();
+ InvalidParameterException y = new InvalidParameterException(x.getMessage());
y.initCause(x);
throw y;
}
@@ -144,22 +123,22 @@ public class DSSKeyPairGeneratorSpi extends KeyPairGeneratorAdapter implements
throws InvalidParameterException
{
HashMap attributes = new HashMap();
- attributes.put(DSSKeyPairGenerator.MODULUS_LENGTH, new Integer(modlen));
+ attributes.put(DSSKeyPairGenerator.MODULUS_LENGTH, Integer.valueOf(modlen));
if (random != null)
attributes.put(DSSKeyPairGenerator.SOURCE_OF_RANDOMNESS, random);
attributes.put(DSSKeyPairGenerator.USE_DEFAULTS,
- Boolean.valueOf(!genParams));
+ Boolean.valueOf(! genParams));
attributes.put(DSSKeyPairGenerator.STRICT_DEFAULTS, Boolean.TRUE);
attributes.put(DSSKeyPairGenerator.PREFERRED_ENCODING_FORMAT,
- new Integer(Registry.ASN1_ENCODING_ID));
+ Integer.valueOf(Registry.ASN1_ENCODING_ID));
try
{
adaptee.setup(attributes);
}
catch (IllegalArgumentException x)
{
- InvalidParameterException y = new InvalidParameterException();
+ InvalidParameterException y = new InvalidParameterException(x.getMessage());
y.initCause(x);
throw y;
}
diff --git a/libjava/classpath/gnu/java/security/jce/sig/DSSParameters.java b/libjava/classpath/gnu/java/security/jce/sig/DSSParameters.java
index ba1f414..eaccb00 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/DSSParameters.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/DSSParameters.java
@@ -136,7 +136,6 @@ public class DSSParameters
if (! format.equalsIgnoreCase(Registry.ASN1_ENCODING_SHORT_NAME))
throw new IOException("Unknown or unsupported format: " + format);
}
-
engineInit(params);
}
@@ -191,7 +190,6 @@ public class DSSParameters
if (! format.equalsIgnoreCase(Registry.ASN1_ENCODING_SHORT_NAME))
throw new IOException("Unknown or unsupported format: " + format);
}
-
return engineGetEncoded();
}
diff --git a/libjava/classpath/gnu/java/security/jce/sig/DSSRawSignatureSpi.java b/libjava/classpath/gnu/java/security/jce/sig/DSSRawSignatureSpi.java
index a63c51a..9b20c03 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/DSSRawSignatureSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/DSSRawSignatureSpi.java
@@ -42,27 +42,15 @@ import gnu.java.security.Registry;
import gnu.java.security.sig.dss.DSSSignatureRawCodec;
/**
- * The implementation of Service Provider Interface (SPI) adapter
- * for the DSS (Digital Signature Standard) signature scheme, encoded and/or
- * decoded in RAW format.initialize()
method), the GNU Crypto provider
- * supplies (and document) default values to be used. For example, the GNU
- * Crypto provider uses a default modulus size (keysize) of 1024 bits for
- * the DSS (Digital Signature Standard) a.k.a DSA.initialize()
method), the GNU provider supplies
+ * (and document) default values to be used. For example, the GNU provider uses
+ * a default modulus size (keysize) of 1024 bits for the DSS (Digital
+ * Signature Standard) a.k.a DSA.
*/
-public abstract class KeyPairGeneratorAdapter extends KeyPairGenerator
+public abstract class KeyPairGeneratorAdapter
+ extends KeyPairGenerator
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** Our underlying keypair instance. */
protected IKeyPairGenerator adaptee;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Trivial protected constructor.
- *
+ *
* @param kpgName the canonical name of the keypair generator algorithm.
*/
protected KeyPairGeneratorAdapter(String kpgName)
@@ -88,12 +82,6 @@ public abstract class KeyPairGeneratorAdapter extends KeyPairGenerator
this.adaptee = KeyPairGeneratorFactory.getInstance(kpgName);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // java.security.KeyPairGeneratorSpi interface implementation
- // -------------------------------------------------------------------------
-
public abstract void initialize(int keysize, SecureRandom random);
public abstract void initialize(AlgorithmParameterSpec params,
diff --git a/libjava/classpath/gnu/java/security/jce/sig/RSAKeyFactory.java b/libjava/classpath/gnu/java/security/jce/sig/RSAKeyFactory.java
index 674e2af..3ba49ed 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/RSAKeyFactory.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/RSAKeyFactory.java
@@ -76,7 +76,6 @@ public class RSAKeyFactory
BigInteger e = spec.getPublicExponent();
return new GnuRSAPublicKey(Registry.X509_ENCODING_ID, n, e);
}
-
if (keySpec instanceof X509EncodedKeySpec)
{
X509EncodedKeySpec spec = (X509EncodedKeySpec) keySpec;
@@ -88,12 +87,9 @@ public class RSAKeyFactory
}
catch (RuntimeException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
-
throw new InvalidKeySpecException("Unsupported (public) key specification");
}
@@ -114,16 +110,6 @@ public class RSAKeyFactory
return new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID,
n, e, d, p, q, dP, dQ, qInv);
}
-
-// if (keySpec instanceof RSAPrivateKeySpec)
-// {
-// RSAPrivateKeySpec spec = (RSAPrivateKeySpec) keySpec;
-// BigInteger n = spec.getModulus();
-// BigInteger d = spec.getPrivateExponent();
-// return new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID,
-// n, null, d, null, null, null, null, null);
-// }
-
if (keySpec instanceof PKCS8EncodedKeySpec)
{
PKCS8EncodedKeySpec spec = (PKCS8EncodedKeySpec) keySpec;
@@ -135,12 +121,9 @@ public class RSAKeyFactory
}
catch (RuntimeException x)
{
- InvalidKeySpecException y = new InvalidKeySpecException();
- y.initCause(x);
- throw y;
+ throw new InvalidKeySpecException(x.getMessage(), x);
}
}
-
throw new InvalidKeySpecException("Unsupported (private) key specification");
}
@@ -156,7 +139,6 @@ public class RSAKeyFactory
BigInteger e = rsaKey.getPublicExponent();
return new RSAPublicKeySpec(n, e);
}
-
if (keySpec.isAssignableFrom(X509EncodedKeySpec.class))
{
if (key instanceof GnuRSAPublicKey)
@@ -171,13 +153,11 @@ public class RSAKeyFactory
byte[] encoded = key.getEncoded();
return new X509EncodedKeySpec(encoded);
}
-
- throw new InvalidKeySpecException("Wrong key type or unsupported (public) key specification");
+ throw new InvalidKeySpecException(
+ "Wrong key type or unsupported (public) key specification");
}
-
throw new InvalidKeySpecException("Unsupported (public) key specification");
}
-
if ((key instanceof RSAPrivateCrtKey)
&& keySpec.isAssignableFrom(RSAPrivateCrtKeySpec.class))
{
@@ -192,7 +172,6 @@ public class RSAKeyFactory
BigInteger qInv = rsaKey.getCrtCoefficient();
return new RSAPrivateCrtKeySpec(n, e, d, p, q, dP, dQ, qInv);
}
-
if ((key instanceof RSAPrivateKey)
&& keySpec.isAssignableFrom(RSAPrivateKeySpec.class))
{
@@ -201,7 +180,6 @@ public class RSAKeyFactory
BigInteger d = rsaKey.getPrivateExponent();
return new RSAPrivateKeySpec(n, d);
}
-
if (keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class))
{
if (key instanceof GnuRSAPrivateKey)
@@ -210,17 +188,16 @@ public class RSAKeyFactory
byte[] encoded = rsaKey.getEncoded(Registry.PKCS8_ENCODING_ID);
return new PKCS8EncodedKeySpec(encoded);
}
-
if (Registry.PKCS8_ENCODING_SHORT_NAME.equalsIgnoreCase(key.getFormat()))
{
byte[] encoded = key.getEncoded();
return new PKCS8EncodedKeySpec(encoded);
}
-
- throw new InvalidKeySpecException("Wrong key type or unsupported (private) key specification");
+ throw new InvalidKeySpecException(
+ "Wrong key type or unsupported (private) key specification");
}
-
- throw new InvalidKeySpecException("Wrong key type or unsupported key specification");
+ throw new InvalidKeySpecException(
+ "Wrong key type or unsupported key specification");
}
protected Key engineTranslateKey(Key key) throws InvalidKeyException
@@ -235,7 +212,6 @@ public class RSAKeyFactory
BigInteger e = rsaKey.getPublicExponent();
return new GnuRSAPublicKey(Registry.X509_ENCODING_ID, n, e);
}
-
if (key instanceof RSAPrivateCrtKey)
{
RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key;
@@ -250,16 +226,6 @@ public class RSAKeyFactory
return new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID,
n, e, d, p, q, dP, dQ, qInv);
}
-
-// if (key instanceof RSAPrivateKey)
-// {
-// RSAPrivateKey rsaKey = (RSAPrivateKey) key;
-// BigInteger n = rsaKey.getModulus();
-// BigInteger d = rsaKey.getPrivateExponent();
-// return new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID,
-// n, null, d, null, null, null, null, null);
-// }
-
throw new InvalidKeyException("Unsupported key type");
}
}
diff --git a/libjava/classpath/gnu/java/security/jce/sig/RSAKeyPairGeneratorSpi.java b/libjava/classpath/gnu/java/security/jce/sig/RSAKeyPairGeneratorSpi.java
index 24dc7c5..ef53b81 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/RSAKeyPairGeneratorSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/RSAKeyPairGeneratorSpi.java
@@ -49,43 +49,29 @@ import java.util.HashMap;
/**
* The implementation of a {@link java.security.KeyPairGenerator} adapter class
- * to wrap gnu.crypto RSA keypair generator instances.initialize()
method), the GNU Crypto provider
- * uses a default modulus size (keysize) of 1024 bits.initialize()
method), the GNU provider uses a
+ * default modulus size (keysize) of 1024 bits.
*/
-public class RSAKeyPairGeneratorSpi extends KeyPairGeneratorAdapter
+public class RSAKeyPairGeneratorSpi
+ extends KeyPairGeneratorAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public RSAKeyPairGeneratorSpi()
{
super(Registry.RSA_KPG);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
public void initialize(int keysize, SecureRandom random)
{
HashMap attributes = new HashMap();
- attributes.put(RSAKeyPairGenerator.MODULUS_LENGTH, new Integer(keysize));
+ attributes.put(RSAKeyPairGenerator.MODULUS_LENGTH, Integer.valueOf(keysize));
if (random != null)
- {
- attributes.put(RSAKeyPairGenerator.SOURCE_OF_RANDOMNESS, random);
- }
+ attributes.put(RSAKeyPairGenerator.SOURCE_OF_RANDOMNESS, random);
attributes.put(RSAKeyPairGenerator.PREFERRED_ENCODING_FORMAT,
- new Integer(Registry.ASN1_ENCODING_ID));
+ Integer.valueOf(Registry.ASN1_ENCODING_ID));
adaptee.setup(attributes);
}
@@ -95,21 +81,16 @@ public class RSAKeyPairGeneratorSpi extends KeyPairGeneratorAdapter
HashMap attributes = new HashMap();
if (params != null)
{
- if (!(params instanceof RSAKeyGenParameterSpec))
- {
- throw new InvalidAlgorithmParameterException("params");
- }
+ if (! (params instanceof RSAKeyGenParameterSpec))
+ throw new InvalidAlgorithmParameterException("params");
attributes.put(RSAKeyPairGenerator.RSA_PARAMETERS, params);
}
-
if (random != null)
- {
- attributes.put(RSAKeyPairGenerator.SOURCE_OF_RANDOMNESS, random);
- }
+ attributes.put(RSAKeyPairGenerator.SOURCE_OF_RANDOMNESS, random);
attributes.put(RSAKeyPairGenerator.PREFERRED_ENCODING_FORMAT,
- new Integer(Registry.ASN1_ENCODING_ID));
+ Integer.valueOf(Registry.ASN1_ENCODING_ID));
adaptee.setup(attributes);
}
}
diff --git a/libjava/classpath/gnu/java/security/jce/sig/RSAPSSRawSignatureSpi.java b/libjava/classpath/gnu/java/security/jce/sig/RSAPSSRawSignatureSpi.java
index f3548d8..f1ccbde 100644
--- a/libjava/classpath/gnu/java/security/jce/sig/RSAPSSRawSignatureSpi.java
+++ b/libjava/classpath/gnu/java/security/jce/sig/RSAPSSRawSignatureSpi.java
@@ -42,26 +42,15 @@ import gnu.java.security.Registry;
import gnu.java.security.sig.rsa.RSAPSSSignatureRawCodec;
/**
- * The implementation of Service Provider Interface (SPI) adapter
- * for the RSA-PSS signature scheme, encoded and/or decoded in RAW format.null
if none
- * found.
+ * @return an instance of the keypair generator, or null
if
+ * none found.
*/
public static IKeyPairGenerator getInstance(String name)
{
if (name == null)
- {
- return null;
- }
+ return null;
name = name.trim();
IKeyPairGenerator result = null;
if (name.equalsIgnoreCase(Registry.DSA_KPG)
|| name.equalsIgnoreCase(Registry.DSS_KPG))
- {
- result = new DSSKeyPairGenerator();
- }
+ result = new DSSKeyPairGenerator();
else if (name.equalsIgnoreCase(Registry.RSA_KPG))
- {
- result = new RSAKeyPairGenerator();
- }
+ result = new RSAKeyPairGenerator();
else if (name.equalsIgnoreCase(Registry.DH_KPG))
- {
- result = makeInstance ("gnu.javax.crypto.key.dh.GnuDHKeyPairGenerator");
- }
+ result = makeInstance("gnu.javax.crypto.key.dh.GnuDHKeyPairGenerator");
else if (name.equalsIgnoreCase(Registry.SRP_KPG))
- {
- result = makeInstance ("gnu.javax.crypto.key.srp6.SRPKeyPairGenerator");
- }
+ result = makeInstance("gnu.javax.crypto.key.srp6.SRPKeyPairGenerator");
return result;
}
/**
- * p
,
- * q
and g
.q
and g
.
+ * getEncoded()
methods of each of the private and
- * public keys.getEncoded()
methods of each of the private and
+ * public keys.
+ * null
.
+ *
* @see DSSPrivateKey#getEncoded
* @see DSSPublicKey#getEncoded
*/
-public abstract class DSSKey implements Key, DSAKey
+public abstract class DSSKey
+ implements Key, DSAKey
{
- // Constants and variables
- // -------------------------------------------------------------------------
-
/**
- * A prime modulus, where 2L-1 < p < 2L
- * for 512 <= L <= 1024
and L
a multiple of
+ * A prime modulus, where
+ * 2L-1 < p < 2L
for
+ * 512 <= L <= 1024
and L
a multiple of
* 64
.
*/
protected final BigInteger p;
/**
- * A prime divisor of p - 1
, where 2159 < q
+ * A prime divisor of
p - 1
, where
+ * 2159 < q
* < 2160
.
*/
protected final BigInteger q;
/**
- * g = h(p-1)/q mod p
, where h
is any
- * integer with 1 < h < p - 1
such that h
- * (p-1)/q mod p > 1
(g
has order q mod p
+ *
g = h(p-1)/q mod p
, where h
is
+ * any integer with 1 < h < p - 1
such that h
+ * (p-1)/q mod p > 1
(g
+ * has order q mod p
*
).
*/
protected final BigInteger g;
/**
- * Identifier of the default encoding format to use when externalizing the
- * key material.
+ * Identifier of the default encoding format to use when externalizing the key
+ * material.
*/
protected final int defaultFormat;
/** String representation of this key. Cached for speed. */
private transient String str;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Trivial protected constructor.
*
* @param defaultFormat the identifier of the encoding format to use by
- * default when externalizing the key.
+ * default when externalizing the key.
* @param p the DSS parameter p
.
* @param q the DSS parameter q
.
* @param g the DSS parameter g
.
@@ -121,21 +124,11 @@ public abstract class DSSKey implements Key, DSAKey
this.g = g;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.security.interfaces.DSAKey interface implementation ----------------
-
public DSAParams getParams()
{
return new DSAParameterSpec(p, q, g);
}
- // java.security.Key interface implementation ------------------------------
-
public String getAlgorithm()
{
return Registry.DSS_KPG;
@@ -152,27 +145,31 @@ public abstract class DSSKey implements Key, DSAKey
return FormatUtil.getEncodingShortName(defaultFormat);
}
- // Other instance methods --------------------------------------------------
-
/**
- * true
if the designated object is an instance of
+ * Returns true
if the designated object is an instance of
* {@link DSAKey} and has the same DSS (Digital Signature Standard) parameter
- * values as this one.false
if the MPIs of this key are
+ * inherited. This may be the case when the key is re-constructed from
+ * an X.509 certificate with absent or NULL AlgorithmIdentifier's parameters
+ * field.
+ *
* @param obj the other non-null DSS key to compare to.
- * @return true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(Object obj)
{
+ if (hasInheritedParameters())
+ return false;
+
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof DSAKey))
- {
- return false;
- }
+ return false;
+
+ if (! (obj instanceof DSAKey))
+ return false;
+
DSAKey that = (DSAKey) obj;
return p.equals(that.getParams().getP())
&& q.equals(that.getParams().getQ())
@@ -183,19 +180,32 @@ public abstract class DSSKey implements Key, DSAKey
{
if (str == null)
{
- String ls = SystemProperties.getProperty("line.separator");
- str = new StringBuilder().append(ls)
- .append("defaultFormat=").append(defaultFormat).append(",").append(ls)
- .append("p=0x").append(p.toString(16)).append(",").append(ls)
- .append("q=0x").append(q.toString(16)).append(",").append(ls)
- .append("g=0x").append(g.toString(16))
- .toString();
+ String ls = (String) AccessController.doPrivileged(new GetPropertyAction("line.separator"));
+ StringBuilder sb = new StringBuilder(ls)
+ .append("defaultFormat=").append(defaultFormat).append(",")
+ .append(ls);
+ if (hasInheritedParameters())
+ sb.append("p=inherited,").append(ls)
+ .append("q=inherited,").append(ls)
+ .append("g=inherited");
+ else
+ sb.append("p=0x").append(p.toString(16)).append(",").append(ls)
+ .append("q=0x").append(q.toString(16)).append(",").append(ls)
+ .append("g=0x").append(g.toString(16));
+ str = sb.toString();
}
-
return str;
}
- // abstract methods to be implemented by subclasses ------------------------
-
public abstract byte[] getEncoded(int format);
+
+ /**
+ * @return true
if p
, q
and
+ * g
are all null
. Returns
+ * false
otherwise.
+ */
+ public boolean hasInheritedParameters()
+ {
+ return p == null && q == null && g == null;
+ }
}
diff --git a/libjava/classpath/gnu/java/security/key/dss/DSSKeyPairGenerator.java b/libjava/classpath/gnu/java/security/key/dss/DSSKeyPairGenerator.java
index 5aa7461..1bad0b6 100644
--- a/libjava/classpath/gnu/java/security/key/dss/DSSKeyPairGenerator.java
+++ b/libjava/classpath/gnu/java/security/key/dss/DSSKeyPairGenerator.java
@@ -38,12 +38,12 @@ exception statement from your version. */
package gnu.java.security.key.dss;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.hash.Sha160;
import gnu.java.security.key.IKeyPairGenerator;
import gnu.java.security.util.PRNG;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.PrivateKey;
@@ -51,76 +51,57 @@ import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.DSAParameterSpec;
import java.util.Map;
+import java.util.logging.Logger;
/**
- *
+ * A key-pair generator for asymetric keys to use in conjunction with the DSS
+ * (Digital Signature Standard).
+ * p
, q
and g
for
- * a given modulus length. The ultimate behaviour of this generator with
+ * computed values of p
, q
and g
+ * for a given modulus length. The ultimate behaviour of this generator with
* regard to using pre-computed parameter sets will depend on the value of
* this property and of the following one {@link #STRICT_DEFAULTS}:
- *
*
- *
- *
* The default value of this property is {@link Boolean#TRUE}.
*/
public static final String USE_DEFAULTS = "gnu.crypto.dss.use.defaults";
@@ -145,8 +126,8 @@ public class DSSKeyPairGenerator implements IKeyPairGenerator
/**
* Property name of an optional {@link DSAParameterSpec} instance to use for
- * this generator's 512
and
- * 1024
, and is of the form 512 + 64 * n
. In
- * addition, a new paramter set will always be generated; i.e. no pre-
- * computed values are used.512
, 768
and 1024
. Any
- * other value, of the modulus length, even if between 512
and
- * 1024
, and of the form 512 + 64 * n
, will cause
- * an {@link IllegalArgumentException} to be thrown. When those modulus
- * length (512
, 768
, and 1024
) are
- * specified, the paramter set is always the same.512
,
- * 768
, or 1024
.512
and
+ * 1024
, and is of the form 512 + 64 * n
. In
+ * addition, a new paramter set will always be generated; i.e. no pre-
+ * computed values are used.512
, 768
and 1024
. Any
+ * other value, of the modulus length, even if between 512
and
+ * 1024
, and of the form 512 + 64 * n
, will
+ * cause an {@link IllegalArgumentException} to be thrown. When those modulus
+ * length (512
, 768
, and 1024
)
+ * are specified, the paramter set is always the same.512
,
+ * 768
, or 1024
.p
, q
, and g
values.
- * The default is to generate these values or use pre-computed ones,
+ * this generator's p
, q
, and g
+ * values. The default is to generate these values or use pre-computed ones,
* depending on the value of the USE_DEFAULTS
attribute.
*/
public static final String DSS_PARAMETERS = "gnu.crypto.dss.params";
@@ -165,55 +146,41 @@ public class DSSKeyPairGenerator implements IKeyPairGenerator
private static final int DEFAULT_ENCODING_FORMAT = Registry.RAW_ENCODING_ID;
/** Initial SHS context. */
- private static final int[] T_SHS = new int[] { 0x67452301, 0xEFCDAB89,
- 0x98BADCFE, 0x10325476,
- 0xC3D2E1F0 };
+ private static final int[] T_SHS = new int[] {
+ 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0
+ };
// from jdk1.3.1/docs/guide/security/CryptoSpec.html#AppB
public static final DSAParameterSpec KEY_PARAMS_512 = new DSAParameterSpec(
- new BigInteger(
- "fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae"
- + "01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17",
- 16),
- new BigInteger(
- "962eddcc369cba8ebb260ee6b6a126d9346e38c5",
- 16),
- new BigInteger(
- "678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e"
- + "35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4",
- 16));
-
+ new BigInteger(
+ "fca682ce8e12caba26efccf7110e526db078b05edecbcd1eb4a208f3ae1617ae"
+ + "01f35b91a47e6df63413c5e12ed0899bcd132acd50d99151bdc43ee737592e17", 16),
+ new BigInteger("962eddcc369cba8ebb260ee6b6a126d9346e38c5", 16),
+ new BigInteger(
+ "678471b27a9cf44ee91a49c5147db1a9aaf244f05a434d6486931d2d14271b9e"
+ + "35030b71fd73da179069b32e2935630e1c2062354d0da20a6c416e50be794ca4", 16));
public static final DSAParameterSpec KEY_PARAMS_768 = new DSAParameterSpec(
- new BigInteger(
- "e9e642599d355f37c97ffd3567120b8e25c9cd43e927b3a9670fbec5d8901419"
- + "22d2c3b3ad2480093799869d1e846aab49fab0ad26d2ce6a22219d470bce7d77"
- + "7d4a21fbe9c270b57f607002f3cef8393694cf45ee3688c11a8c56ab127a3daf",
- 16),
- new BigInteger(
- "9cdbd84c9f1ac2f38d0f80f42ab952e7338bf511",
- 16),
- new BigInteger(
- "30470ad5a005fb14ce2d9dcd87e38bc7d1b1c5facbaecbe95f190aa7a31d23c4"
- + "dbbcbe06174544401a5b2c020965d8c2bd2171d3668445771f74ba084d2029d8"
- + "3c1c158547f3a9f1a2715be23d51ae4d3e5a1f6a7064f316933a346d3f529252",
- 16));
-
+ new BigInteger(
+ "e9e642599d355f37c97ffd3567120b8e25c9cd43e927b3a9670fbec5d8901419"
+ + "22d2c3b3ad2480093799869d1e846aab49fab0ad26d2ce6a22219d470bce7d77"
+ + "7d4a21fbe9c270b57f607002f3cef8393694cf45ee3688c11a8c56ab127a3daf", 16),
+ new BigInteger("9cdbd84c9f1ac2f38d0f80f42ab952e7338bf511", 16),
+ new BigInteger(
+ "30470ad5a005fb14ce2d9dcd87e38bc7d1b1c5facbaecbe95f190aa7a31d23c4"
+ + "dbbcbe06174544401a5b2c020965d8c2bd2171d3668445771f74ba084d2029d8"
+ + "3c1c158547f3a9f1a2715be23d51ae4d3e5a1f6a7064f316933a346d3f529252", 16));
public static final DSAParameterSpec KEY_PARAMS_1024 = new DSAParameterSpec(
- new BigInteger(
- "fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669"
- + "455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b7"
- + "6b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb"
- + "83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c7",
- 16),
- new BigInteger(
- "9760508f15230bccb292b982a2eb840bf0581cf5",
- 16),
- new BigInteger(
- "f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d078267"
- + "5159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e1"
- + "3c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243b"
- + "cca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a",
- 16));
+ new BigInteger(
+ "fd7f53811d75122952df4a9c2eece4e7f611b7523cef4400c31e3f80b6512669"
+ + "455d402251fb593d8d58fabfc5f5ba30f6cb9b556cd7813b801d346ff26660b7"
+ + "6b9950a5a49f9fe8047b1022c24fbba9d7feb7c61bf83b57e7c6a8a6150f04fb"
+ + "83f6d3c51ec3023554135a169132f675f3ae2b61d72aeff22203199dd14801c7", 16),
+ new BigInteger("9760508f15230bccb292b982a2eb840bf0581cf5", 16),
+ new BigInteger(
+ "f7e1a085d69b3ddecbbcab5c36b857b97994afbbfa3aea82f9574c0b3d078267"
+ + "5159578ebad4594fe67107108180b449167123e84c281613b7cf09328cc8a6e1"
+ + "3c167a8b547c8d28e0a3ae1e2bb3a675916ea37f0bfa213562f1fb627a01243b"
+ + "cca4f1bea8519089a883dfe15ae59f06928b665e807b552564014c3bfecf492a", 16));
private static final BigInteger TWO_POW_160 = TWO.pow(160);
@@ -243,31 +210,18 @@ public class DSSKeyPairGenerator implements IKeyPairGenerator
/** Preferred encoding format of generated keys. */
private int preferredFormat;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
- // implicit 0-arguments constructor
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // gnu.crypto.key.IKeyPairGenerator interface implementation ---------------
-
public String name()
{
return Registry.DSS_KPG;
}
/**
- * 512 + 64j
.
+ * @exception IllegalArgumentException if the designated MODULUS_LENGTH value
+ * is not greater than 512, less than 1024 and not of the form
+ * 512 + 64j
.
*/
public void setup(Map attributes)
{
@@ -280,9 +234,7 @@ public class DSSKeyPairGenerator implements IKeyPairGenerator
// should we use the default pre-computed params?
Boolean useDefaults = (Boolean) attributes.get(USE_DEFAULTS);
if (useDefaults == null)
- {
- useDefaults = Boolean.TRUE;
- }
+ useDefaults = Boolean.TRUE;
Boolean strictDefaults = (Boolean) attributes.get(STRICT_DEFAULTS);
if (strictDefaults == null)
@@ -334,16 +286,12 @@ public class DSSKeyPairGenerator implements IKeyPairGenerator
q = null;
g = null;
}
-
// do we have a SecureRandom, or should we use our own?
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
-
// what is the preferred encoding format
Integer formatID = (Integer) attributes.get(PREFERRED_ENCODING_FORMAT);
- preferredFormat = formatID == null
- ? DEFAULT_ENCODING_FORMAT
- : formatID.intValue();
-
+ preferredFormat = formatID == null ? DEFAULT_ENCODING_FORMAT
+ : formatID.intValue();
// set the seed-key
byte[] kb = new byte[20]; // we need 160 bits of randomness
nextRandomBytes(kb);
@@ -361,76 +309,65 @@ public class DSSKeyPairGenerator implements IKeyPairGenerator
p = params[FIPS186.DSA_PARAMS_P];
e = params[FIPS186.DSA_PARAMS_E];
g = params[FIPS186.DSA_PARAMS_G];
- if (DEBUG && debuglevel > 0)
+ if (Configuration.DEBUG)
{
- debug("seed: " + seed.toString(16));
- debug("counter: " + counter.intValue());
- debug("q: " + q.toString(16));
- debug("p: " + p.toString(16));
- debug("e: " + e.toString(16));
- debug("g: " + g.toString(16));
+ log.fine("seed: " + seed.toString(16));
+ log.fine("counter: " + counter.intValue());
+ log.fine("q: " + q.toString(16));
+ log.fine("p: " + p.toString(16));
+ log.fine("e: " + e.toString(16));
+ log.fine("g: " + g.toString(16));
}
}
-
BigInteger x = nextX();
BigInteger y = g.modPow(x, p);
-
PublicKey pubK = new DSSPublicKey(preferredFormat, p, q, g, y);
PrivateKey secK = new DSSPrivateKey(preferredFormat, p, q, g, x);
-
return new KeyPair(pubK, secK);
}
- // Other instance methods --------------------------------------------------
-
/**
- *
- *
- *
- * b
is the length of a secret b-bit seed-key (XKEY).b
is the length of a secret b-bit seed-key (XKEY).
+ *
- *
- *
+ *
* @param key the key to encode.
* @return the Raw format encoding of the designated key.
* @throws IllegalArgumentException if the designated key is not a DSS
- * (Digital Signature Standard) one.
+ * (Digital Signature Standard) one.
* @see Registry#MAGIC_RAW_DSS_PUBLIC_KEY
*/
public byte[] encodePublicKey(PublicKey key)
{
- if (!(key instanceof DSSPublicKey))
- {
- throw new IllegalArgumentException("key");
- }
+ if (! (key instanceof DSSPublicKey))
+ throw new IllegalArgumentException("key");
DSSPublicKey dssKey = (DSSPublicKey) key;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_DSS_PUBLIC_KEY[0]);
baos.write(Registry.MAGIC_RAW_DSS_PUBLIC_KEY[1]);
baos.write(Registry.MAGIC_RAW_DSS_PUBLIC_KEY[2]);
baos.write(Registry.MAGIC_RAW_DSS_PUBLIC_KEY[3]);
-
// version
baos.write(0x01);
-
// p
byte[] buffer = dssKey.getParams().getP().toByteArray();
int length = buffer.length;
@@ -140,7 +121,6 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// q
buffer = dssKey.getParams().getQ().toByteArray();
length = buffer.length;
@@ -149,7 +129,6 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// g
buffer = dssKey.getParams().getG().toByteArray();
length = buffer.length;
@@ -158,7 +137,6 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// y
buffer = dssKey.getY().toByteArray();
length = buffer.length;
@@ -167,7 +145,6 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -178,112 +155,106 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
|| k[1] != Registry.MAGIC_RAW_DSS_PUBLIC_KEY[1]
|| k[2] != Registry.MAGIC_RAW_DSS_PUBLIC_KEY[2]
|| k[3] != Registry.MAGIC_RAW_DSS_PUBLIC_KEY[3])
- {
- throw new IllegalArgumentException("magic");
- }
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
- int i = 5;
+ throw new IllegalArgumentException("version");
+ int i = 5;
int l;
byte[] buffer;
-
// p
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger p = new BigInteger(1, buffer);
-
// q
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger q = new BigInteger(1, buffer);
-
// g
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger g = new BigInteger(1, buffer);
-
// y
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger y = new BigInteger(1, buffer);
-
return new DSSPublicKey(p, q, g, y);
}
/**
- * p
in internet order,toByteArray()
method on the DSA parameter
- * p
,q
,toByteArray()
method on the DSA parameter
- * q
,g
,toByteArray()
method on the DSA parameter
- * g
,y
,toByteArray()
method on the DSA parameter
- * y
,p
in internet order,toByteArray()
method on the DSA parameter p
,
+ * q
,toByteArray()
method on the DSA parameter q
,
+ * g
,toByteArray()
method on the DSA parameter g
,
+ * y
,toByteArray()
method on the DSA parameter y
,
+ *
- *
- *
+ *
* @param key the key to encode.
* @return the Raw format encoding of the designated key.
* @throws IllegalArgumentException if the designated key is not a DSS
- * (Digital Signature Standard) one.
+ * (Digital Signature Standard) one.
*/
public byte[] encodePrivateKey(PrivateKey key)
{
- if (!(key instanceof DSSPrivateKey))
- {
- throw new IllegalArgumentException("key");
- }
+ if (! (key instanceof DSSPrivateKey))
+ throw new IllegalArgumentException("key");
DSSPrivateKey dssKey = (DSSPrivateKey) key;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_DSS_PRIVATE_KEY[0]);
baos.write(Registry.MAGIC_RAW_DSS_PRIVATE_KEY[1]);
baos.write(Registry.MAGIC_RAW_DSS_PRIVATE_KEY[2]);
baos.write(Registry.MAGIC_RAW_DSS_PRIVATE_KEY[3]);
-
// version
baos.write(0x01);
-
// p
byte[] buffer = dssKey.getParams().getP().toByteArray();
int length = buffer.length;
@@ -292,7 +263,6 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// q
buffer = dssKey.getParams().getQ().toByteArray();
length = buffer.length;
@@ -301,7 +271,6 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// g
buffer = dssKey.getParams().getG().toByteArray();
length = buffer.length;
@@ -310,7 +279,6 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// x
buffer = dssKey.getX().toByteArray();
length = buffer.length;
@@ -319,7 +287,6 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -330,52 +297,51 @@ public class DSSKeyPairRawCodec implements IKeyPairCodec
|| k[1] != Registry.MAGIC_RAW_DSS_PRIVATE_KEY[1]
|| k[2] != Registry.MAGIC_RAW_DSS_PRIVATE_KEY[2]
|| k[3] != Registry.MAGIC_RAW_DSS_PRIVATE_KEY[3])
- {
- throw new IllegalArgumentException("magic");
- }
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
- int i = 5;
+ throw new IllegalArgumentException("version");
+ int i = 5;
int l;
byte[] buffer;
-
// p
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger p = new BigInteger(1, buffer);
-
// q
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger q = new BigInteger(1, buffer);
-
// g
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger g = new BigInteger(1, buffer);
-
// x
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger x = new BigInteger(1, buffer);
-
return new DSSPrivateKey(p, q, g, x);
}
}
diff --git a/libjava/classpath/gnu/java/security/key/dss/DSSKeyPairX509Codec.java b/libjava/classpath/gnu/java/security/key/dss/DSSKeyPairX509Codec.java
index 516ef92..a5e8e9d 100644
--- a/libjava/classpath/gnu/java/security/key/dss/DSSKeyPairX509Codec.java
+++ b/libjava/classpath/gnu/java/security/key/dss/DSSKeyPairX509Codec.java
@@ -94,9 +94,15 @@ public class DSSKeyPairX509Codec
* g INTEGER
* }
*
- *
- * p
in internet order,toByteArray()
method on the DSA parameter
- * p
,q
,toByteArray()
method on the DSA parameter
- * q
,g
,toByteArray()
method on the DSA parameter
- * g
,x
,toByteArray()
method on the DSA parameter
- * x
,p
in internet order,toByteArray()
method on the DSA parameter p
,
+ * q
,toByteArray()
method on the DSA parameter q
,
+ * g
,toByteArray()
method on the DSA parameter g
,
+ * x
,toByteArray()
method on the DSA parameter x
,
+ *
* DSAPublicKey ::= INTEGER -- public key, Y
@@ -118,20 +124,25 @@ public class DSSKeyPairX509Codec
DERValue derOID = new DERValue(DER.OBJECT_IDENTIFIER, DSA_ALG_OID);
DSSPublicKey dssKey = (DSSPublicKey) key;
- BigInteger p = dssKey.getParams().getP();
- BigInteger q = dssKey.getParams().getQ();
- BigInteger g = dssKey.getParams().getG();
- BigInteger y = dssKey.getY();
-
- DERValue derP = new DERValue(DER.INTEGER, p);
- DERValue derQ = new DERValue(DER.INTEGER, q);
- DERValue derG = new DERValue(DER.INTEGER, g);
-
- ArrayList params = new ArrayList(3);
- params.add(derP);
- params.add(derQ);
- params.add(derG);
- DERValue derParams = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, params);
+ DERValue derParams;
+ if (dssKey.hasInheritedParameters())
+ derParams = new DERValue(DER.NULL, null);
+ else
+ {
+ BigInteger p = dssKey.getParams().getP();
+ BigInteger q = dssKey.getParams().getQ();
+ BigInteger g = dssKey.getParams().getG();
+
+ DERValue derP = new DERValue(DER.INTEGER, p);
+ DERValue derQ = new DERValue(DER.INTEGER, q);
+ DERValue derG = new DERValue(DER.INTEGER, g);
+
+ ArrayList params = new ArrayList(3);
+ params.add(derP);
+ params.add(derQ);
+ params.add(derG);
+ derParams = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE, params);
+ }
ArrayList algorithmID = new ArrayList(2);
algorithmID.add(derOID);
@@ -139,6 +150,7 @@ public class DSSKeyPairX509Codec
DERValue derAlgorithmID = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
algorithmID);
+ BigInteger y = dssKey.getY();
DERValue derDSAPublicKey = new DERValue(DER.INTEGER, y);
byte[] yBytes = derDSAPublicKey.getEncoded();
DERValue derSPK = new DERValue(DER.BIT_STRING, new BitString(yBytes));
@@ -157,11 +169,10 @@ public class DSSKeyPairX509Codec
}
catch (IOException x)
{
- InvalidParameterException e = new InvalidParameterException();
+ InvalidParameterException e = new InvalidParameterException(x.getMessage());
e.initCause(x);
throw e;
}
-
return result;
}
@@ -186,7 +197,10 @@ public class DSSKeyPairX509Codec
if (input == null)
throw new InvalidParameterException("Input bytes MUST NOT be null");
- BigInteger p, g, q, y;
+ BigInteger p = null;
+ BigInteger g = null;
+ BigInteger q = null;
+ BigInteger y;
DERReader der = new DERReader(input);
try
{
@@ -204,20 +218,35 @@ public class DSSKeyPairX509Codec
if (! algOID.equals(DSA_ALG_OID))
throw new InvalidParameterException("Unexpected OID: " + algOID);
- DERValue derParams = der.read();
- DerUtil.checkIsConstructed(derParams, "Wrong DSS Parameters field");
-
DERValue val = der.read();
- DerUtil.checkIsBigInteger(val, "Wrong P field");
- p = (BigInteger) val.getValue();
- val = der.read();
- DerUtil.checkIsBigInteger(val, "Wrong Q field");
- q = (BigInteger) val.getValue();
- val = der.read();
- DerUtil.checkIsBigInteger(val, "Wrong G field");
- g = (BigInteger) val.getValue();
-
- val = der.read();
+ // RFC-3280, page 79 states: "If the subjectPublicKeyInfo field of the
+ // certificate contains an algorithm field with null parameters or
+ // parameters are omitted, compare the certificate subjectPublicKey
+ // algorithm to the working_public_key_algorithm. If the certificate
+ // subjectPublicKey algorithm and the working_public_key_algorithm are
+ // different, set the working_public_key_parameters to null."
+ // in other words, the parameters field of an AlgorithmIdentifier
+ // element MAY NOT be present at all, or if present MAY be NULL!
+ // the Mauve test ValidDSAParameterInheritenceTest5, in
+ // gnu.testlet.java.security.cert.pkix.pkits, is/was failing because
+ // of this.
+ if (val.getTag() == DER.NULL)
+ val = der.read();
+ else if (val.isConstructed())
+ {
+ val = der.read();
+ DerUtil.checkIsBigInteger(val, "Wrong P field");
+ p = (BigInteger) val.getValue();
+ val = der.read();
+ DerUtil.checkIsBigInteger(val, "Wrong Q field");
+ q = (BigInteger) val.getValue();
+ val = der.read();
+ DerUtil.checkIsBigInteger(val, "Wrong G field");
+ g = (BigInteger) val.getValue();
+
+ val = der.read();
+ }
+
if (! (val.getValue() instanceof BitString))
throw new InvalidParameterException("Wrong SubjectPublicKey field");
@@ -230,11 +259,10 @@ public class DSSKeyPairX509Codec
}
catch (IOException x)
{
- InvalidParameterException e = new InvalidParameterException();
+ InvalidParameterException e = new InvalidParameterException(x.getMessage());
e.initCause(x);
throw e;
}
-
return new DSSPublicKey(Registry.X509_ENCODING_ID, p, q, g, y);
}
diff --git a/libjava/classpath/gnu/java/security/key/dss/DSSPrivateKey.java b/libjava/classpath/gnu/java/security/key/dss/DSSPrivateKey.java
index fe59cb6..6ed8de8 100644
--- a/libjava/classpath/gnu/java/security/key/dss/DSSPrivateKey.java
+++ b/libjava/classpath/gnu/java/security/key/dss/DSSPrivateKey.java
@@ -38,38 +38,34 @@ exception statement from your version. */
package gnu.java.security.key.dss;
-import gnu.classpath.SystemProperties;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
+import gnu.java.security.action.GetPropertyAction;
import gnu.java.security.key.IKeyPairCodec;
import java.math.BigInteger;
+import java.security.AccessController;
import java.security.PrivateKey;
import java.security.interfaces.DSAPrivateKey;
/**
- *
0 < x <
- * q
.0 < x <
+ * q
.
*/
private final BigInteger x;
/** String representation of this key. Cached for speed. */
private transient String str;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Convenience constructor. Calls the constructor with 5 arguments passing
* {@link Registry#RAW_ENCODING_ID} as the identifier of the preferred
@@ -104,13 +100,9 @@ public class DSSPrivateKey extends DSSKey implements PrivateKey, DSAPrivateKey
super(preferredFormat == Registry.ASN1_ENCODING_ID ? Registry.PKCS8_ENCODING_ID
: preferredFormat,
p, q, g);
-
this.x = x;
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
* A class method that takes the output of the encodePrivateKey()
* method of a DSS keypair codec object (an instance implementing
@@ -135,30 +127,22 @@ public class DSSPrivateKey extends DSSKey implements PrivateKey, DSAPrivateKey
catch (IllegalArgumentException ignored)
{
}
-
// try PKCS#8 codec
return (DSSPrivateKey) new DSSKeyPairPKCS8Codec().decodePrivateKey(k);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.security.interfaces.DSAPrivateKey interface implementation ---------
-
public BigInteger getX()
{
return x;
}
- // Other instance methods --------------------------------------------------
-
/**
- * true
if the designated object is an instance of
+ * Returns true
if the designated object is an instance of
* {@link DSAPrivateKey} and has the same DSS (Digital Signature Standard)
- * parameter values as this one.true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(Object obj)
{
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof DSAPrivateKey))
- {
- return false;
- }
+ return false;
+
+ if (! (obj instanceof DSAPrivateKey))
+ return false;
+
DSAPrivateKey that = (DSAPrivateKey) obj;
return super.equals(that) && x.equals(that.getX());
}
@@ -207,13 +189,15 @@ public class DSSPrivateKey extends DSSKey implements PrivateKey, DSAPrivateKey
{
if (str == null)
{
- String ls = SystemProperties.getProperty("line.separator");
+ String ls = (String) AccessController.doPrivileged
+ (new GetPropertyAction("line.separator"));
str = new StringBuilder(this.getClass().getName()).append("(")
- .append(super.toString()).append(",").append(ls)
- .append("x=0x").append(DEBUG ? x.toString(16) : "**...*").append(ls)
- .append(")").toString();
+ .append(super.toString()).append(",").append(ls)
+ .append("x=0x").append(Configuration.DEBUG ? x.toString(16)
+ : "**...*").append(ls)
+ .append(")")
+ .toString();
}
-
return str;
}
}
diff --git a/libjava/classpath/gnu/java/security/key/dss/DSSPublicKey.java b/libjava/classpath/gnu/java/security/key/dss/DSSPublicKey.java
index 5229213..9e1c4cf 100644
--- a/libjava/classpath/gnu/java/security/key/dss/DSSPublicKey.java
+++ b/libjava/classpath/gnu/java/security/key/dss/DSSPublicKey.java
@@ -38,36 +38,33 @@ exception statement from your version. */
package gnu.java.security.key.dss;
-import gnu.classpath.SystemProperties;
import gnu.java.security.Registry;
+import gnu.java.security.action.GetPropertyAction;
import gnu.java.security.key.IKeyPairCodec;
import java.math.BigInteger;
+import java.security.AccessController;
import java.security.PublicKey;
import java.security.interfaces.DSAPublicKey;
/**
- * y = gx mod p
where x
is the private
- * part of the DSA key.
+ * y = gx mod p
where x
is the
+ * private part of the DSA key.
*/
private final BigInteger y;
/** String representation of this key. Cached for speed. */
private transient String str;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Conveience constructor. Calls the constructor with 5 arguments passing
* {@link Registry#RAW_ENCODING_ID} as the identifier of the preferred
@@ -85,8 +82,8 @@ public class DSSPublicKey extends DSSKey implements PublicKey, DSAPublicKey
}
/**
- * Constructs a new instance of DSSPublicKey
given the designated
- * arguments.
+ * Constructs a new instance of DSSPublicKey
given the
+ * designated arguments.
*
* @param preferredFormat the identifier of the preferred encoding format to
* use when externalizing this key.
@@ -102,13 +99,9 @@ public class DSSPublicKey extends DSSKey implements PublicKey, DSAPublicKey
super(preferredFormat == Registry.ASN1_ENCODING_ID ? Registry.X509_ENCODING_ID
: preferredFormat,
p, q, g);
-
this.y = y;
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
* A class method that takes the output of the encodePublicKey()
* method of a DSS keypair codec object (an instance implementing
@@ -133,30 +126,22 @@ public class DSSPublicKey extends DSSKey implements PublicKey, DSAPublicKey
catch (IllegalArgumentException ignored)
{
}
-
// try X.509 codec
return (DSSPublicKey) new DSSKeyPairX509Codec().decodePublicKey(k);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.security.interfaces.DSAPublicKey interface implementation ----------
-
public BigInteger getY()
{
return y;
}
- // Other instance methods --------------------------------------------------
-
/**
- * true
if the designated object is an instance of
+ * Returns true
if the designated object is an instance of
* {@link DSAPublicKey} and has the same DSS (Digital Signature Standard)
- * parameter values as this one.true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(Object obj)
{
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof DSAPublicKey))
- {
- return false;
- }
+ return false;
+
+ if (! (obj instanceof DSAPublicKey))
+ return false;
+
DSAPublicKey that = (DSAPublicKey) obj;
return super.equals(that) && y.equals(that.getY());
}
@@ -205,13 +188,14 @@ public class DSSPublicKey extends DSSKey implements PublicKey, DSAPublicKey
{
if (str == null)
{
- String ls = SystemProperties.getProperty("line.separator");
+ String ls = (String) AccessController.doPrivileged
+ (new GetPropertyAction("line.separator"));
str = new StringBuilder(this.getClass().getName()).append("(")
- .append(super.toString()).append(",").append(ls)
- .append("y=0x").append(y.toString(16)).append(ls)
- .append(")").toString();
+ .append(super.toString()).append(",").append(ls)
+ .append("y=0x").append(y.toString(16)).append(ls)
+ .append(")")
+ .toString();
}
-
return str;
}
}
diff --git a/libjava/classpath/gnu/java/security/key/dss/FIPS186.java b/libjava/classpath/gnu/java/security/key/dss/FIPS186.java
index 5984bcc..7277599 100644
--- a/libjava/classpath/gnu/java/security/key/dss/FIPS186.java
+++ b/libjava/classpath/gnu/java/security/key/dss/FIPS186.java
@@ -40,26 +40,21 @@ package gnu.java.security.key.dss;
import gnu.java.security.hash.Sha160;
import gnu.java.security.util.PRNG;
-import gnu.java.security.util.Prime2;
import java.math.BigInteger;
import java.security.SecureRandom;
/**
- *
+ * An implementation of the DSA parameters generation as described in FIPS-186.
+ * p
, q
, and
* g
parameters only when L
(the modulus length)
* is not one of the following: 512
, 768
and
- * 1024
. For those values of L
, this implementation
- * uses pre-computed values of p
, q
, and
- * g
given in the document CryptoSpec included in the
- * security guide documentation of the standard JDK distribution.1024
. For those values of L
, this
+ * implementation uses pre-computed values of p
,
+ * q
, and g
given in the document CryptoSpec
+ * included in the security guide documentation of the standard JDK
+ * distribution.
+ * p
and q
,
* satisfying the following three conditions:
- *
*
- *
- *
* The algorithm used to find these primes is as described in FIPS-186,
* section 2.2: GENERATION OF PRIMES. This prime generation scheme starts by
- * using the {@link Sha160} and a user supplied SEED
- * to construct a prime, 2159 < q < 2160
2L-1 < p < 2L
for a
- * specified L
, where L = 512 + 64j
for some
- * 0 <= j <= 8
2159 < q < 2160
2L-1 < p < 2L
for a
+ * specified L
, where L = 512 + 64j
for some
+ * 0 <= j <= 8
q
, in the range 2159 < q
- * < 2160. Once this is accomplished, the same SEED
- * value is used to construct an X
in the range 2L-1
+ * using the {@link Sha160} and a user supplied SEED to construct a
+ * prime,
q
, in the range 2159 < q < 2160.
+ * Once this is accomplished, the same SEED value is used to construct
+ * an X
in the range 2L-1
* < X < 2L. The prime,
p
, is then
* formed by rounding X
to a number congruent to 1 mod
* 2q
. In this implementation we use the same SEED value given
@@ -169,9 +154,8 @@ public class FIPS186
u = sha.digest();
}
for (int i = 0; i < a.length; i++)
- {
- a[i] ^= u[i];
- }
+ a[i] ^= u[i];
+
U = new BigInteger(1, a);
// 3. Form q from U by setting the most significant bit (the
// 2**159 bit) and the least significant bit to 1. In terms of
@@ -183,12 +167,9 @@ public class FIPS186
// probability of a non-prime number passing the test is at
// most 1/2**80.
// 5. If q is not prime, go to step 1.
- if (Prime2.isProbablePrime(q))
- {
- break step1;
- }
+ if (q.isProbablePrime(80))
+ break step1;
} // step1
-
// 6. Let counter = 0 and offset = 2.
counter = 0;
offset = 2;
@@ -201,9 +182,9 @@ public class FIPS186
{
for (int k = 0; k <= n; k++)
{
- a = SEED_PLUS_OFFSET.add(
- BigInteger.valueOf(k & 0xFFFFFFFFL)).mod(
- TWO_POW_160).toByteArray();
+ a = SEED_PLUS_OFFSET
+ .add(BigInteger.valueOf(k & 0xFFFFFFFFL))
+ .mod(TWO_POW_160).toByteArray();
sha.update(a, 0, a.length);
V[k] = new BigInteger(1, sha.digest());
}
@@ -214,9 +195,8 @@ public class FIPS186
// Note that 0 <= W < 2**(L-1) and hence 2**(L-1) <= X < 2**L.
W = V[0];
for (int k = 1; k < n; k++)
- {
- W = W.add(V[k].multiply(TWO.pow(k * 160)));
- }
+ W = W.add(V[k].multiply(TWO.pow(k * 160)));
+
W = W.add(V[n].mod(TWO.pow(b)).multiply(TWO.pow(n * 160)));
X = W.add(TWO.pow(L - 1));
// 9. Let c = X mod 2q and set p = X - (c - 1).
@@ -228,22 +208,17 @@ public class FIPS186
{
// 11. Perform a robust primality test on p.
// 12. If p passes the test performed in step 11, go to step 15.
- if (Prime2.isProbablePrime(p))
- {
- break algorithm;
- }
+ if (p.isProbablePrime(80))
+ break algorithm;
}
// 13. Let counter = counter + 1 and offset = offset + n + 1.
counter++;
offset += n + 1;
// 14. If counter >= 4096 go to step 1, otherwise go to step 7.
if (counter >= 4096)
- {
- continue algorithm;
- }
+ continue algorithm;
} // step7
} // algorithm
-
// compute g. from FIPS-186, Appendix 4:
// 1. Generate p and q as specified in Appendix 2.
// 2. Let e = (p - 1) / q
@@ -258,28 +233,21 @@ public class FIPS186
// 4. Set g = h**e mod p
g = h.modPow(e, p);
// 5. If g = 1, go to step 3
- if (!g.equals(BigInteger.ONE))
- {
- break;
- }
+ if (! g.equals(BigInteger.ONE))
+ break;
}
-
return new BigInteger[] { SEED, BigInteger.valueOf(counter), q, p, e, g };
}
- // helper methods ----------------------------------------------------------
-
/**
* Fills the designated byte array with random data.
- *
+ *
* @param buffer the byte array to fill with random data.
*/
private void nextRandomBytes(byte[] buffer)
{
if (rnd != null)
- {
- rnd.nextBytes(buffer);
- }
+ rnd.nextBytes(buffer);
else
getDefaultPRNG().nextBytes(buffer);
}
diff --git a/libjava/classpath/gnu/java/security/key/rsa/GnuRSAKey.java b/libjava/classpath/gnu/java/security/key/rsa/GnuRSAKey.java
index 3009dd7..4bdce40 100644
--- a/libjava/classpath/gnu/java/security/key/rsa/GnuRSAKey.java
+++ b/libjava/classpath/gnu/java/security/key/rsa/GnuRSAKey.java
@@ -38,23 +38,21 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
-import gnu.classpath.SystemProperties;
import gnu.java.security.Registry;
+import gnu.java.security.action.GetPropertyAction;
import gnu.java.security.util.FormatUtil;
import java.math.BigInteger;
+import java.security.AccessController;
import java.security.Key;
import java.security.interfaces.RSAKey;
/**
- * n
.n
.
+ *
* @return the modulus n
.
*/
public BigInteger getN()
@@ -135,8 +118,8 @@ public abstract class GnuRSAKey implements Key, RSAKey
}
/**
- * e
.e
.
+ *
* @return the public exponent e
.
*/
public BigInteger getPublicExponent()
@@ -145,8 +128,8 @@ public abstract class GnuRSAKey implements Key, RSAKey
}
/**
- * e
.
*/
public BigInteger getE()
@@ -155,23 +138,21 @@ public abstract class GnuRSAKey implements Key, RSAKey
}
/**
- * true
if the designated object is an instance of
- * {@link RSAKey} and has the same RSA parameter values as this one.true
if the designated object is an instance of
+ * {@link RSAKey} and has the same RSA parameter values as this one.
+ *
* @param obj the other non-null RSA key to compare to.
- * @return true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(final Object obj)
{
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof RSAKey))
- {
- return false;
- }
+ return false;
+
+ if (! (obj instanceof RSAKey))
+ return false;
+
final RSAKey that = (RSAKey) obj;
return n.equals(that.getModulus());
}
@@ -180,8 +161,9 @@ public abstract class GnuRSAKey implements Key, RSAKey
{
if (str == null)
{
- String ls = SystemProperties.getProperty("line.separator");
- str = new StringBuilder().append(ls)
+ String ls = (String) AccessController.doPrivileged
+ (new GetPropertyAction("line.separator"));
+ str = new StringBuilder(ls)
.append("defaultFormat=").append(defaultFormat).append(",").append(ls)
.append("n=0x").append(n.toString(16)).append(",").append(ls)
.append("e=0x").append(e.toString(16))
@@ -190,7 +172,5 @@ public abstract class GnuRSAKey implements Key, RSAKey
return str;
}
- // abstract methods to be implemented by subclasses ------------------------
-
public abstract byte[] getEncoded(int format);
}
diff --git a/libjava/classpath/gnu/java/security/key/rsa/GnuRSAPrivateKey.java b/libjava/classpath/gnu/java/security/key/rsa/GnuRSAPrivateKey.java
index 9205344..00a1b82 100644
--- a/libjava/classpath/gnu/java/security/key/rsa/GnuRSAPrivateKey.java
+++ b/libjava/classpath/gnu/java/security/key/rsa/GnuRSAPrivateKey.java
@@ -38,42 +38,39 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
-import gnu.classpath.SystemProperties;
+import gnu.java.security.Configuration;
+import gnu.java.security.action.GetPropertyAction;
import gnu.java.security.Registry;
import gnu.java.security.key.IKeyPairCodec;
import java.math.BigInteger;
+import java.security.AccessController;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
/**
- *
- *
*/
-public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
- RSAPrivateCrtKey
+public class GnuRSAPrivateKey
+ extends GnuRSAKey
+ implements PrivateKey, RSAPrivateCrtKey
{
- // Constants and variables
- // -------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
-
/** The first prime divisor of the modulus. */
private final BigInteger p;
/** The second prime divisor of the modulus. */
private final BigInteger q;
- /** The public exponent of an RSA key. */
- // private final BigInteger e;
/** The private exponent of an RSA private key. */
private final BigInteger d;
@@ -89,21 +86,17 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
/** String representation of this key. Cached for speed. */
private transient String str;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Convenience constructor. Calls the constructor with 5 arguments passing
* {@link Registry#RAW_ENCODING_ID} as the identifier of the preferred
* encoding format.
- *
+ *
* @param p the modulus first prime divisor.
* @param q the modulus second prime divisor.
* @param e the public exponent.
* @param d the private exponent.
*/
- public GnuRSAPrivateKey(BigInteger p, BigInteger q, BigInteger e,
- BigInteger d)
+ public GnuRSAPrivateKey(BigInteger p, BigInteger q, BigInteger e, BigInteger d)
{
this(Registry.RAW_ENCODING_ID, p, q, e, d);
}
@@ -122,7 +115,9 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
public GnuRSAPrivateKey(int preferredFormat, BigInteger p, BigInteger q,
BigInteger e, BigInteger d)
{
- this(preferredFormat, p.multiply(q), e, d, p, q,
+ this(preferredFormat,
+ p.multiply(q),
+ e, d, p, q,
e.modInverse(p.subtract(BigInteger.ONE)),
e.modInverse(q.subtract(BigInteger.ONE)),
q.modInverse(p));
@@ -135,19 +130,20 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
* @param preferredFormat the indetifier of the preferred encoding format to
* use when externalizing this key.
* @param n the public modulus, which is also the product of
- * Primitive specification and supporting documentation.
- * Jakob Jonsson and Burt Kaliski.
+ * Primitive specification and supporting documentation.
+ * Jakob Jonsson and Burt Kaliski.p
- * and q
.
+ * and q
.
* @param e the public exponent.
* @param d the private exponent.
* @param p the modulus first prime divisor.
* @param q the modulus second prime divisor.
* @param dP the first prime's exponen. A positive integer less than
- * p
and q
, satisfying e * dP = 1 (mod p-1)
- *
.
+ * p
and q
, satisfying
+ * e * dP = 1 (mod p-1)
.
* @param dQ the second prime's exponent. A positive integer less than
- * p
and q
, satisfying e * dQ = 1 (mod p-1)
- *
.
+ * p
and q
, satisfying
+ * e * dQ = 1 (mod p-1)
.
* @param qInv the Chinese Remainder Theorem coefiicient. A positive integer
- * less than p
, satisfying q * qInv = 1 (mod p)
.
+ * less than p
, satisfying
+ * q * qInv = 1 (mod p)
.
*/
public GnuRSAPrivateKey(int preferredFormat, BigInteger n, BigInteger e,
BigInteger d, BigInteger p, BigInteger q,
@@ -156,24 +152,20 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
super(preferredFormat == Registry.ASN1_ENCODING_ID ? Registry.PKCS8_ENCODING_ID
: preferredFormat,
n, e);
-
this.d = d;
this.p = p;
this.q = q;
// the exponents dP and dQ are positive integers less than p and q
// respectively satisfying
- // e * dP = 1 (mod p-1);
- // e * dQ = 1 (mod q-1),
+ // e * dP = 1 (mod p-1);
+ // e * dQ = 1 (mod q-1),
this.dP = dP;
this.dQ = dQ;
// the CRT coefficient qInv is a positive integer less than p satisfying
- // q * qInv = 1 (mod p).
+ // q * qInv = 1 (mod p).
this.qInv = qInv;
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
* A class method that takes the output of the encodePrivateKey()
* method of an RSA keypair codec object (an instance implementing
@@ -198,14 +190,10 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
catch (IllegalArgumentException ignored)
{
}
-
// try PKCS#8 codec
return (GnuRSAPrivateKey) new RSAKeyPairPKCS8Codec().decodePrivateKey(k);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
public BigInteger getPrimeP()
{
return p;
@@ -231,22 +219,18 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
return qInv;
}
- // java.security.interfaces.RSAPrivateKey interface implementation ---------
-
public BigInteger getPrivateExponent()
{
return d;
}
- // Other instance methods --------------------------------------------------
-
/**
- * Returns the encoded form of this private key according to the
- * designated format.
- *
+ * Returns the encoded form of this private key according to the designated
+ * format.
+ *
* @param format the desired format identifier of the resulting encoding.
* @return the byte sequence encoding this key according to the designated
- * format.
+ * format.
* @throws IllegalArgumentException if the format is not supported.
* @see RSAKeyPairRawCodec
* @see RSAKeyPairPKCS8Codec
@@ -270,19 +254,18 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
}
/**
- * true
if the designated object is an instance of
- * this class and has the same RSA parameter values as this one.true
if the designated object is an instance of this
+ * class and has the same RSA parameter values as this one.
+ *
* @param obj the other non-null RSA key to compare to.
* @return true
if the designated object is of the same type
- * and value as this one.
+ * and value as this one.
*/
public boolean equals(final Object obj)
{
if (obj == null)
- {
- return false;
- }
+ return false;
+
if (obj instanceof RSAPrivateKey)
{
final RSAPrivateKey that = (RSAPrivateKey) obj;
@@ -304,16 +287,24 @@ public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
{
if (str == null)
{
- String ls = SystemProperties.getProperty("line.separator");
+ String ls = (String) AccessController.doPrivileged
+ (new GetPropertyAction("line.separator"));
str = new StringBuilder(this.getClass().getName()).append("(")
.append(super.toString()).append(",").append(ls)
- .append("d=0x").append(DEBUG ? d.toString(16) : "**...*").append(ls)
- .append("p=0x").append(DEBUG ? p.toString(16) : "**...*").append(ls)
- .append("q=0x").append(DEBUG ? q.toString(16) : "**...*").append(ls)
- .append("dP=0x").append(DEBUG ? dP.toString(16) : "**...*").append(ls)
- .append("dQ=0x").append(DEBUG ? dQ.toString(16) : "**...*").append(ls)
- .append("qInv=0x").append(DEBUG ? qInv.toString(16) : "**...*").append(ls)
- .append(")").toString();
+ .append("d=0x").append(Configuration.DEBUG ? d.toString(16)
+ : "**...*").append(ls)
+ .append("p=0x").append(Configuration.DEBUG ? p.toString(16)
+ : "**...*").append(ls)
+ .append("q=0x").append(Configuration.DEBUG ? q.toString(16)
+ : "**...*").append(ls)
+ .append("dP=0x").append(Configuration.DEBUG ? dP.toString(16)
+ : "**...*").append(ls)
+ .append("dQ=0x").append(Configuration.DEBUG ? dQ.toString(16)
+ : "**...*").append(ls)
+ .append("qInv=0x").append(Configuration.DEBUG ? qInv.toString(16)
+ : "**...*").append(ls)
+ .append(")")
+ .toString();
}
return str;
}
diff --git a/libjava/classpath/gnu/java/security/key/rsa/GnuRSAPublicKey.java b/libjava/classpath/gnu/java/security/key/rsa/GnuRSAPublicKey.java
index 8badede..fe28d0b 100644
--- a/libjava/classpath/gnu/java/security/key/rsa/GnuRSAPublicKey.java
+++ b/libjava/classpath/gnu/java/security/key/rsa/GnuRSAPublicKey.java
@@ -38,42 +38,39 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
-import gnu.classpath.SystemProperties;
import gnu.java.security.Registry;
+import gnu.java.security.action.GetPropertyAction;
import gnu.java.security.key.IKeyPairCodec;
import java.math.BigInteger;
+import java.security.AccessController;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
/**
- *
- *
*/
-public class GnuRSAPublicKey extends GnuRSAKey implements PublicKey,
- RSAPublicKey
+public class GnuRSAPublicKey
+ extends GnuRSAKey
+ implements PublicKey, RSAPublicKey
{
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** String representation of this key. Cached for speed. */
private transient String str;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Conveience constructor. Calls the constructor with 3 arguments passing
* {@link Registry#RAW_ENCODING_ID} as the identifier of the preferred
* encoding format.
- *
+ *
* @param n the modulus.
* @param e the public exponent.
*/
@@ -98,9 +95,6 @@ public class GnuRSAPublicKey extends GnuRSAKey implements PublicKey,
n, e);
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
* A class method that takes the output of the
- * Primitive specification and supporting documentation.
- * Jakob Jonsson and Burt Kaliski.
+ * Primitive specification and supporting documentation.
+ * Jakob Jonsson and Burt Kaliski.encodePublicKey()
* method of an RSA keypair codec object (an instance implementing
@@ -125,21 +119,17 @@ public class GnuRSAPublicKey extends GnuRSAKey implements PublicKey,
catch (IllegalArgumentException ignored)
{
}
-
// try X.509 codec
return (GnuRSAPublicKey) new RSAKeyPairX509Codec().decodePublicKey(k);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
- * true
if the designated object is an instance of
- * this class and has the same RSA parameter values as this one.true
if the designated object is an instance of this
+ * class and has the same RSA parameter values as this one.
+ *
* @param obj the other non-null RSA key to compare to.
- * @return true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(final Object obj)
{
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof RSAPublicKey))
- {
- return false;
- }
+ return false;
+
+ if (! (obj instanceof RSAPublicKey))
+ return false;
+
final RSAPublicKey that = (RSAPublicKey) obj;
return super.equals(that)
&& getPublicExponent().equals(that.getPublicExponent());
@@ -188,10 +176,12 @@ public class GnuRSAPublicKey extends GnuRSAKey implements PublicKey,
{
if (str == null)
{
- String ls = SystemProperties.getProperty("line.separator");
+ String ls = (String) AccessController.doPrivileged
+ (new GetPropertyAction("line.separator"));
str = new StringBuilder(this.getClass().getName()).append("(")
.append(super.toString()).append(",").append(ls)
- .append(")").toString();
+ .append(")")
+ .toString();
}
return str;
}
diff --git a/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairGenerator.java b/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairGenerator.java
index 3906338..c31cc4c 100644
--- a/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairGenerator.java
+++ b/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairGenerator.java
@@ -38,10 +38,10 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.key.IKeyPairGenerator;
import gnu.java.security.util.PRNG;
-import gnu.java.security.util.Prime2;
import java.math.BigInteger;
import java.security.KeyPair;
@@ -53,25 +53,23 @@ import java.util.Map;
import java.util.logging.Logger;
/**
- *
- *
*/
-public class RSAKeyPairGenerator implements IKeyPairGenerator
+public class RSAKeyPairGenerator
+ implements IKeyPairGenerator
{
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final Logger log = Logger.getLogger(RSAKeyPairGenerator.class.getName());
/** The BigInteger constant 1. */
@@ -90,8 +88,8 @@ public class RSAKeyPairGenerator implements IKeyPairGenerator
public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.rsa.prng";
/**
- * Property name of an optional {@link RSAKeyGenParameterSpec} instance to
- * use for this generator's n
, and e
values. The
+ * Property name of an optional {@link RSAKeyGenParameterSpec} instance to use
+ * for this generator's n
, and e
values. The
* default is to generate n
and use a fixed value for
* e (Fermat's F4 number).
*/
@@ -128,38 +126,28 @@ public class RSAKeyPairGenerator implements IKeyPairGenerator
/** Preferred encoding format of generated keys. */
private int preferredFormat;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// implicit 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // gnu.crypto.key.IKeyPairGenerator interface implementation ---------------
-
public String name()
{
return Registry.RSA_KPG;
}
/**
- *
* PrivateKeyInfo ::= SEQUENCE {
* version INTEGER, -- MUST be 0
@@ -97,10 +97,12 @@ public class RSAKeyPairPKCS8Codec
* parameters ANY DEFINED BY algorithm OPTIONAL
* }
*
- *
- *
* RSAPrivateKey ::= SEQUENCE {
* version INTEGER, -- MUST be 0
@@ -122,8 +124,8 @@ public class RSAKeyPairPKCS8Codec
*/
public byte[] encodePrivateKey(PrivateKey key)
{
- log.entering(this.getClass().getName(), "encodePrivateKey()", key);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "encodePrivateKey()", key);
if (! (key instanceof GnuRSAPrivateKey))
throw new InvalidParameterException("Wrong key type");
@@ -141,8 +143,9 @@ public class RSAKeyPairPKCS8Codec
DERValue derOID = new DERValue(DER.OBJECT_IDENTIFIER, RSA_ALG_OID);
- ArrayList algorithmID = new ArrayList(1);
+ ArrayList algorithmID = new ArrayList(2);
algorithmID.add(derOID);
+ algorithmID.add(new DERValue(DER.NULL, null));
DERValue derAlgorithmID = new DERValue(DER.CONSTRUCTED | DER.SEQUENCE,
algorithmID);
@@ -190,8 +193,8 @@ public class RSAKeyPairPKCS8Codec
y.initCause(x);
throw y;
}
-
- log.exiting(this.getClass().getName(), "encodePrivateKey()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "encodePrivateKey()", result);
return result;
}
@@ -213,8 +216,8 @@ public class RSAKeyPairPKCS8Codec
*/
public PrivateKey decodePrivateKey(byte[] input)
{
- log.entering(this.getClass().getName(), "decodePrivateKey()", input);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "decodePrivateKey()", input);
if (input == null)
throw new InvalidParameterException("Input bytes MUST NOT be null");
@@ -239,9 +242,12 @@ public class RSAKeyPairPKCS8Codec
if (! algOID.equals(RSA_ALG_OID))
throw new InvalidParameterException("Unexpected OID: " + algOID);
+ // rfc-2459 states that this field is OPTIONAL but NULL if/when present
DERValue val = der.read();
- byte[] pkBytes = (byte[]) val.getValue();
+ if (val.getTag() == DER.NULL)
+ val = der.read();
+ byte[] pkBytes = (byte[]) val.getValue();
der = new DERReader(pkBytes);
DERValue derRSAPrivateKey = der.read();
DerUtil.checkIsConstructed(derRSAPrivateKey, "Wrong RSAPrivateKey field");
@@ -284,10 +290,10 @@ public class RSAKeyPairPKCS8Codec
y.initCause(x);
throw y;
}
-
- PrivateKey result = new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID, n, e,
- d, p, q, dP, dQ, qInv);
- log.exiting(this.getClass().getName(), "decodePrivateKey()", result);
+ PrivateKey result = new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID,
+ n, e, d, p, q, dP, dQ, qInv);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "decodePrivateKey()", result);
return result;
}
}
diff --git a/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairRawCodec.java b/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairRawCodec.java
index fb7cea9..c2650e6 100644
--- a/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairRawCodec.java
+++ b/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairRawCodec.java
@@ -47,80 +47,60 @@ import java.security.PrivateKey;
import java.security.PublicKey;
/**
- *
- *
- *
+ *
* @param key the key to encode.
* @return the Raw format encoding of the designated key.
* @exception IllegalArgumentException if the designated key is not an RSA
- * one.
+ * one.
*/
public byte[] encodePublicKey(PublicKey key)
{
- if (!(key instanceof GnuRSAPublicKey))
- {
- throw new IllegalArgumentException("key");
- }
+ if (! (key instanceof GnuRSAPublicKey))
+ throw new IllegalArgumentException("key");
GnuRSAPublicKey rsaKey = (GnuRSAPublicKey) key;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_RSA_PUBLIC_KEY[0]);
baos.write(Registry.MAGIC_RAW_RSA_PUBLIC_KEY[1]);
baos.write(Registry.MAGIC_RAW_RSA_PUBLIC_KEY[2]);
baos.write(Registry.MAGIC_RAW_RSA_PUBLIC_KEY[3]);
-
// version
baos.write(0x01);
-
// n
byte[] buffer = rsaKey.getModulus().toByteArray();
int length = buffer.length;
@@ -129,7 +109,6 @@ public class RSAKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// e
buffer = rsaKey.getPublicExponent().toByteArray();
length = buffer.length;
@@ -138,7 +117,6 @@ public class RSAKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -149,92 +127,87 @@ public class RSAKeyPairRawCodec implements IKeyPairCodec
|| k[1] != Registry.MAGIC_RAW_RSA_PUBLIC_KEY[1]
|| k[2] != Registry.MAGIC_RAW_RSA_PUBLIC_KEY[2]
|| k[3] != Registry.MAGIC_RAW_RSA_PUBLIC_KEY[3])
- {
- throw new IllegalArgumentException("magic");
- }
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
- int i = 5;
+ throw new IllegalArgumentException("version");
+ int i = 5;
int l;
byte[] buffer;
-
// n
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger n = new BigInteger(1, buffer);
-
// e
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger e = new BigInteger(1, buffer);
-
return new GnuRSAPublicKey(n, e);
}
/**
- * n
(the modulus) in internet order,toByteArray()
method on the RSA parameter n
,e
(the public exponent) in internet order,toByteArray()
method on the RSA parameter e
.n
(the modulus) in internet order,toByteArray()
method on the RSA parameter n
,
+ * e
(the public exponent) in internet order,toByteArray()
method on the RSA parameter e
.
+ *
- *
- *
+ *
* @param key the key to encode.
* @return the Raw format encoding of the designated key.
*/
public byte[] encodePrivateKey(PrivateKey key)
{
- if (!(key instanceof GnuRSAPrivateKey))
- {
- throw new IllegalArgumentException("key");
- }
+ if (! (key instanceof GnuRSAPrivateKey))
+ throw new IllegalArgumentException("key");
GnuRSAPrivateKey rsaKey = (GnuRSAPrivateKey) key;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_RSA_PRIVATE_KEY[0]);
baos.write(Registry.MAGIC_RAW_RSA_PRIVATE_KEY[1]);
baos.write(Registry.MAGIC_RAW_RSA_PRIVATE_KEY[2]);
baos.write(Registry.MAGIC_RAW_RSA_PRIVATE_KEY[3]);
-
// version
baos.write(0x01);
-
// p
byte[] buffer = rsaKey.getPrimeP().toByteArray();
int length = buffer.length;
@@ -243,7 +216,6 @@ public class RSAKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// q
buffer = rsaKey.getPrimeQ().toByteArray();
length = buffer.length;
@@ -252,7 +224,6 @@ public class RSAKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// e
buffer = rsaKey.getPublicExponent().toByteArray();
length = buffer.length;
@@ -261,7 +232,6 @@ public class RSAKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// d
buffer = rsaKey.getPrivateExponent().toByteArray();
length = buffer.length;
@@ -270,7 +240,6 @@ public class RSAKeyPairRawCodec implements IKeyPairCodec
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -281,52 +250,51 @@ public class RSAKeyPairRawCodec implements IKeyPairCodec
|| k[1] != Registry.MAGIC_RAW_RSA_PRIVATE_KEY[1]
|| k[2] != Registry.MAGIC_RAW_RSA_PRIVATE_KEY[2]
|| k[3] != Registry.MAGIC_RAW_RSA_PRIVATE_KEY[3])
- {
- throw new IllegalArgumentException("magic");
- }
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
- int i = 5;
+ throw new IllegalArgumentException("version");
+ int i = 5;
int l;
byte[] buffer;
-
// p
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger p = new BigInteger(1, buffer);
-
// q
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger q = new BigInteger(1, buffer);
-
// e
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger e = new BigInteger(1, buffer);
-
// d
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger d = new BigInteger(1, buffer);
-
return new GnuRSAPrivateKey(p, q, e, d);
}
}
diff --git a/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairX509Codec.java b/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairX509Codec.java
index 882d9c7..b11e1c0 100644
--- a/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairX509Codec.java
+++ b/libjava/classpath/gnu/java/security/key/rsa/RSAKeyPairX509Codec.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.java.security.key.rsa;
+import gnu.java.security.Configuration;
import gnu.java.security.OID;
import gnu.java.security.Registry;
import gnu.java.security.der.BitString;
@@ -114,8 +115,8 @@ public class RSAKeyPairX509Codec
*/
public byte[] encodePublicKey(PublicKey key)
{
- log.entering(this.getClass().getName(), "encodePublicKey()", key);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "encodePublicKey()", key);
if (! (key instanceof GnuRSAPublicKey))
throw new InvalidParameterException("key");
@@ -156,12 +157,12 @@ public class RSAKeyPairX509Codec
}
catch (IOException x)
{
- InvalidParameterException y = new InvalidParameterException();
+ InvalidParameterException y = new InvalidParameterException(x.getMessage());
y.initCause(x);
throw y;
}
-
- log.exiting(this.getClass().getName(), "encodePublicKey()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "encodePublicKey()", result);
return result;
}
@@ -183,8 +184,8 @@ public class RSAKeyPairX509Codec
*/
public PublicKey decodePublicKey(byte[] input)
{
- log.entering(this.getClass().getName(), "decodePublicKey()", input);
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "decodePublicKey()", input);
if (input == null)
throw new InvalidParameterException("Input bytes MUST NOT be null");
@@ -229,13 +230,13 @@ public class RSAKeyPairX509Codec
}
catch (IOException x)
{
- InvalidParameterException y = new InvalidParameterException();
+ InvalidParameterException y = new InvalidParameterException(x.getMessage());
y.initCause(x);
throw y;
}
-
PublicKey result = new GnuRSAPublicKey(Registry.X509_ENCODING_ID, n, e);
- log.exiting(this.getClass().getName(), "decodePublicKey()", result);
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "decodePublicKey()", result);
return result;
}
diff --git a/libjava/classpath/gnu/java/security/pkcs/PKCS7SignedData.java b/libjava/classpath/gnu/java/security/pkcs/PKCS7SignedData.java
index 0781f4b..d59dba3 100644
--- a/libjava/classpath/gnu/java/security/pkcs/PKCS7SignedData.java
+++ b/libjava/classpath/gnu/java/security/pkcs/PKCS7SignedData.java
@@ -37,6 +37,7 @@ exception statement from your version. */
package gnu.java.security.pkcs;
+import gnu.java.security.Configuration;
import gnu.java.security.OID;
import gnu.java.security.ber.BER;
import gnu.java.security.ber.BEREncodingException;
@@ -52,9 +53,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-
import java.math.BigInteger;
-
import java.security.cert.CRL;
import java.security.cert.CRLException;
import java.security.cert.Certificate;
@@ -62,7 +61,6 @@ import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509CRL;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@@ -174,21 +172,22 @@ public class PKCS7SignedData
if (!val.isConstructed())
throw new BEREncodingException("malformed SignedData");
- log.finest("SignedData: " + val);
+ if (Configuration.DEBUG)
+ log.fine("SignedData: " + val);
val = ber.read();
if (val.getTag() != BER.INTEGER)
throw new BEREncodingException("expecting Version");
version = (BigInteger) val.getValue();
-
- log.finest(" Version: " + version);
+ if (Configuration.DEBUG)
+ log.fine(" Version: " + version);
digestAlgorithms = new HashSet();
val = ber.read();
if (!val.isConstructed())
throw new BEREncodingException("malformed DigestAlgorithmIdentifiers");
-
- log.finest(" DigestAlgorithmIdentifiers: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" DigestAlgorithmIdentifiers: " + val);
int count = 0;
DERValue val2 = ber.read();
while (val2 != BER.END_OF_SEQUENCE &&
@@ -196,14 +195,14 @@ public class PKCS7SignedData
{
if (!val2.isConstructed())
throw new BEREncodingException("malformed AlgorithmIdentifier");
-
- log.finest(" AlgorithmIdentifier: " + val2);
+ if (Configuration.DEBUG)
+ log.fine(" AlgorithmIdentifier: " + val2);
count += val2.getEncodedLength();
val2 = ber.read();
if (val2.getTag() != BER.OBJECT_IDENTIFIER)
throw new BEREncodingException("malformed AlgorithmIdentifier");
-
- log.finest(" digestAlgorithmIdentifiers OID: " + val2.getValue());
+ if (Configuration.DEBUG)
+ log.fine(" digestAlgorithmIdentifiers OID: " + val2.getValue());
List algId = new ArrayList(2);
algId.add(val2.getValue());
val2 = ber.read();
@@ -224,23 +223,27 @@ public class PKCS7SignedData
else
algId.add(null);
- log.finest(" digestAlgorithmIdentifiers params: ");
- log.finest(Util.dumpString((byte[]) algId.get(1),
- " digestAlgorithmIdentifiers params: "));
+ if (Configuration.DEBUG)
+ {
+ log.fine(" digestAlgorithmIdentifiers params: ");
+ log.fine(Util.dumpString((byte[]) algId.get(1),
+ " digestAlgorithmIdentifiers params: "));
+ }
digestAlgorithms.add(algId);
}
val = ber.read();
if (!val.isConstructed())
throw new BEREncodingException("malformed ContentInfo");
-
- log.finest(" ContentInfo: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" ContentInfo: " + val);
val2 = ber.read();
if (val2.getTag() != BER.OBJECT_IDENTIFIER)
throw new BEREncodingException("malformed ContentType");
contentType = (OID) val2.getValue();
- log.finest(" ContentType OID: " + contentType);
+ if (Configuration.DEBUG)
+ log.fine(" ContentType OID: " + contentType);
if (BERValue.isIndefinite(val)
|| (val.getLength() > 0 && val.getLength() > val2.getEncodedLength()))
{
@@ -252,17 +255,18 @@ public class PKCS7SignedData
val2 = ber.read();
}
}
-
- log.finest(" Content: ");
- log.finest(Util.dumpString(content, " Content: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" Content: ");
+ log.fine(Util.dumpString(content, " Content: "));
+ }
val = ber.read();
if (val.getTag() == 0)
{
if (!val.isConstructed())
throw new BEREncodingException("malformed ExtendedCertificatesAndCertificates");
-
- log.finest(" ExtendedCertificatesAndCertificates: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" ExtendedCertificatesAndCertificates: " + val);
count = 0;
val2 = ber.read();
List certs = new LinkedList();
@@ -271,7 +275,8 @@ public class PKCS7SignedData
{
Certificate cert =
x509.generateCertificate(new ByteArrayInputStream(val2.getEncoded()));
- log.finest(" Certificate: " + cert);
+ if (Configuration.DEBUG)
+ log.fine(" Certificate: " + cert);
certs.add(cert);
count += val2.getEncodedLength();
ber.skip(val2.getLength());
@@ -286,8 +291,8 @@ public class PKCS7SignedData
{
if (!val.isConstructed())
throw new BEREncodingException("malformed CertificateRevocationLists");
-
- log.finest(" CertificateRevocationLists: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" CertificateRevocationLists: " + val);
count = 0;
val2 = ber.read();
List crls = new LinkedList();
@@ -295,7 +300,8 @@ public class PKCS7SignedData
(val.getLength() > 0 && val.getLength() > count))
{
CRL crl = x509.generateCRL(new ByteArrayInputStream(val2.getEncoded()));
- log.finest(" CRL: " + crl);
+ if (Configuration.DEBUG)
+ log.fine(" CRL: " + crl);
crls.add(crl);
count += val2.getEncodedLength();
ber.skip(val2.getLength());
@@ -309,8 +315,8 @@ public class PKCS7SignedData
signerInfos = new HashSet();
if (!val.isConstructed())
throw new BEREncodingException("malformed SignerInfos");
-
- log.finest(" SignerInfos: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" SignerInfos: " + val);
// FIXME read this more carefully.
// Since we are just reading a file (probably) we just read until we
diff --git a/libjava/classpath/gnu/java/security/pkcs/SignerInfo.java b/libjava/classpath/gnu/java/security/pkcs/SignerInfo.java
index 7b38bfe..3066401 100644
--- a/libjava/classpath/gnu/java/security/pkcs/SignerInfo.java
+++ b/libjava/classpath/gnu/java/security/pkcs/SignerInfo.java
@@ -37,6 +37,7 @@ exception statement from your version. */
package gnu.java.security.pkcs;
+import gnu.java.security.Configuration;
import gnu.java.security.OID;
import gnu.java.security.ber.BER;
import gnu.java.security.ber.BEREncodingException;
@@ -50,7 +51,6 @@ import gnu.java.security.util.Util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.logging.Logger;
@@ -101,7 +101,8 @@ public class SignerInfo
public SignerInfo(BERReader ber) throws IOException
{
DERValue val = ber.read();
- log.finest("SignerInfo: " + val);
+ if (Configuration.DEBUG)
+ log.fine("SignerInfo: " + val);
if (!val.isConstructed())
throw new BEREncodingException("malformed SignerInfo");
@@ -110,13 +111,13 @@ public class SignerInfo
throw new BEREncodingException("malformed Version");
version = (BigInteger) val.getValue();
- log.finest(" Version: " + version);
+ log.fine(" Version: " + version);
val = ber.read();
if (!val.isConstructed())
throw new BEREncodingException("malformed IssuerAndSerialNumber");
-
- log.finest(" IssuerAndSerialNumber: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" IssuerAndSerialNumber: " + val);
val = ber.read();
if (!val.isConstructed())
@@ -124,20 +125,22 @@ public class SignerInfo
issuer = new X500Principal(val.getEncoded());
ber.skip(val.getLength());
- log.finest(" Issuer: " + issuer);
+ if (Configuration.DEBUG)
+ log.fine(" Issuer: " + issuer);
val = ber.read();
if (val.getTag() != BER.INTEGER)
throw new BEREncodingException("malformed SerialNumber");
serialNumber = (BigInteger) val.getValue();
- log.finest(" SerialNumber: " + serialNumber);
+ if (Configuration.DEBUG)
+ log.fine(" SerialNumber: " + serialNumber);
val = ber.read();
if (!val.isConstructed())
throw new BEREncodingException("malformed DigestAlgorithmIdentifier");
-
- log.finest(" DigestAlgorithmIdentifier: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" DigestAlgorithmIdentifier: " + val);
int count = 0;
DERValue val2 = ber.read();
@@ -145,7 +148,8 @@ public class SignerInfo
throw new BEREncodingException("malformed AlgorithmIdentifier");
digestAlgorithmId = (OID) val2.getValue();
- log.finest(" digestAlgorithm OID: " + digestAlgorithmId);
+ if (Configuration.DEBUG)
+ log.fine(" digestAlgorithm OID: " + digestAlgorithmId);
if (BERValue.isIndefinite(val))
{
@@ -170,10 +174,12 @@ public class SignerInfo
else
digestAlgorithmParams = null;
- log.finest(" digestAlgorithm params: ");
- log.finest(Util.dumpString(digestAlgorithmParams,
- " digestAlgorithm params: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" digestAlgorithm params: ");
+ log.fine(Util.dumpString(digestAlgorithmParams,
+ " digestAlgorithm params: "));
+ }
val = ber.read();
if (val.getTag() == 0)
{
@@ -187,21 +193,24 @@ public class SignerInfo
else
authenticatedAttributes = null;
- log.finest(" AuthenticatedAttributes: ");
- log.finest(Util.dumpString(authenticatedAttributes,
- " AuthenticatedAttributes: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" AuthenticatedAttributes: ");
+ log.fine(Util.dumpString(authenticatedAttributes,
+ " AuthenticatedAttributes: "));
+ }
if (!val.isConstructed())
throw new BEREncodingException("malformed DigestEncryptionAlgorithmIdentifier");
-
- log.finest(" DigestEncryptionAlgorithmIdentifier: " + val);
+ if (Configuration.DEBUG)
+ log.fine(" DigestEncryptionAlgorithmIdentifier: " + val);
count = 0;
val2 = ber.read();
if (val2.getTag() != BER.OBJECT_IDENTIFIER)
throw new BEREncodingException("malformed AlgorithmIdentifier");
digestEncryptionAlgorithmId = (OID) val2.getValue();
- log.finest(" digestEncryptionAlgorithm OID: " + digestEncryptionAlgorithmId);
+ if (Configuration.DEBUG)
+ log.fine(" digestEncryptionAlgorithm OID: " + digestEncryptionAlgorithmId);
if (BERValue.isIndefinite(val))
{
@@ -226,27 +235,33 @@ public class SignerInfo
else
digestEncryptionAlgorithmParams = null;
- log.finest(" digestEncryptionAlgorithm params: ");
- log.finest(Util.dumpString(digestEncryptionAlgorithmParams,
- " digestEncryptionAlgorithm params: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" digestEncryptionAlgorithm params: ");
+ log.fine(Util.dumpString(digestEncryptionAlgorithmParams,
+ " digestEncryptionAlgorithm params: "));
+ }
val = ber.read();
if (val.getTag() != BER.OCTET_STRING)
throw new BEREncodingException("malformed EncryptedDigest");
encryptedDigest = (byte[]) val.getValue();
- log.finest(" EncryptedDigest: ");
- log.finest(Util.dumpString(encryptedDigest, " EncryptedDigest: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" EncryptedDigest: ");
+ log.fine(Util.dumpString(encryptedDigest, " EncryptedDigest: "));
+ }
if (ber.peek() == 1)
unauthenticatedAttributes = ber.read().getEncoded();
else
unauthenticatedAttributes = null;
- log.finest(" UnauthenticatedAttributes: ");
- log.finest(Util.dumpString(unauthenticatedAttributes,
- " UnauthenticatedAttributes: "));
-
+ if (Configuration.DEBUG)
+ {
+ log.fine(" UnauthenticatedAttributes: ");
+ log.fine(Util.dumpString(unauthenticatedAttributes,
+ " UnauthenticatedAttributes: "));
+ }
if (ber.peek() == 0)
ber.read();
}
diff --git a/libjava/classpath/gnu/java/security/prng/BasePRNG.java b/libjava/classpath/gnu/java/security/prng/BasePRNG.java
index fe815d7..3b7c8cf 100644
--- a/libjava/classpath/gnu/java/security/prng/BasePRNG.java
+++ b/libjava/classpath/gnu/java/security/prng/BasePRNG.java
@@ -41,14 +41,11 @@ package gnu.java.security.prng;
import java.util.Map;
/**
- * p
(the first prime factor of the modulus) in internet
- * order,toByteArray()
method on the RSA parameter p
,q
(the second prime factor of the modulus) in internet
- * order,toByteArray()
method on the RSA parameter q
,e
(the public exponent) in internet order,toByteArray()
method on the RSA parameter e
,d
(the private exponent) in internet order,toByteArray()
method on the RSA parameter d
,p
(the first prime factor of the modulus) in internet order,
+ * toByteArray()
method on the RSA parameter p
,
+ * q
(the second prime factor of the modulus) in internet
+ * order,toByteArray()
method on the RSA parameter q
,
+ * e
(the public exponent) in internet order,toByteArray()
method on the RSA parameter e
,
+ * d
(the private exponent) in internet order,toByteArray()
method on the RSA parameter d
,
+ *
- *
- *
- * L
bits of an output sequence S
,
- * can predict the (L+1)
st bit of S
with a
- * probability significantly grater than 1/2
."L
bits of an output sequence S
,
+ * can predict the (L+1)
st bit of S
with a
+ * probability significantly greater than 1/2
."
- *
*/
-public interface IRandom extends Cloneable
+public interface IRandom
+ extends Cloneable
{
-
- // Constants
- // -------------------------------------------------------------------------
-
- // Methods
- // -------------------------------------------------------------------------
-
/**
- *
- * CRC Press, Inc. ISBN 0-8493-8523-7, 1997
- * Menezes, A., van Oorschot, P. and S. Vanstone.
+ * CRC Press, Inc. ISBN 0-8493-8523-7, 1997
+ * Menezes, A., van Oorschot, P. and S. Vanstone.offset
, for a maximum of length
bytes with the
- * output of this generator instance.
- *
+ * Fills the designated byte array, starting from byte at index
+ * offset
, for a maximum of length
bytes with
+ * the output of this generator instance.
+ *
* @param out the placeholder to contain the generated random bytes.
* @param offset the starting index in out to consider. This method
- * does nothing if this parameter is not within 0
and
- * out.length
.
- * @param length the maximum number of required random bytes. This method
- * does nothing if this parameter is less than 1
.
+ * does nothing if this parameter is not within 0
and
+ * out.length
.
+ * @param length the maximum number of required random bytes. This method does
+ * nothing if this parameter is less than 1
.
* @exception IllegalStateException if the instance is not yet initialised.
* @exception LimitReachedException if this instance has reached its
- * theoretical limit for generating non-repetitive pseudo-random data.
+ * theoretical limit for generating non-repetitive pseudo-random
+ * data.
*/
void nextBytes(byte[] out, int offset, int length)
throws IllegalStateException, LimitReachedException;
/**
- * seed
, and then (b)
- * continuously re-hashing its output. If no hash algorithm name is specified
- * in the {@link Map} of attributes used to initialise the instance then the
+ * A simple pseudo-random number generator that relies on a hash algorithm, that
+ * (a) starts its operation by hashing a seed
, and then (b)
+ * continuously re-hashing its output. If no hash algorithm name is specified in
+ * the {@link Map} of attributes used to initialise the instance then the
* SHA-160 algorithm is used as the underlying hash function. Also, if no
- * seed
is given, an empty octet sequence is used.seed
is given, an empty octet sequence is used.
*/
-public class MDGenerator extends BasePRNG implements Cloneable
+public class MDGenerator
+ extends BasePRNG
+ implements Cloneable
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** Property name of underlying hash algorithm for this generator. */
public static final String MD_NAME = "gnu.crypto.prng.md.hash.name";
@@ -67,23 +65,12 @@ public class MDGenerator extends BasePRNG implements Cloneable
/** The underlying hash instance. */
private IMessageDigest md;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public MDGenerator()
{
super(Registry.MD_PRNG);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // Implementation of abstract methods in BaseRandom ------------------------
-
public void setup(Map attributes)
{
// find out which hash to use
@@ -95,22 +82,15 @@ public class MDGenerator extends BasePRNG implements Cloneable
// ensure we have a reliable implementation of this hash
md = HashFactory.getInstance(Registry.SHA160_HASH);
}
- else
- { // a clone. reset it for reuse
- md.reset();
- }
- }
- else
- { // ensure we have a reliable implementation of this hash
- md = HashFactory.getInstance(underlyingMD);
+ else // a clone. reset it for reuse
+ md.reset();
}
-
+ else // ensure we have a reliable implementation of this hash
+ md = HashFactory.getInstance(underlyingMD);
// get the seeed
byte[] seed = (byte[]) attributes.get(SEEED);
if (seed == null)
- {
- seed = new byte[0];
- }
+ seed = new byte[0];
md.update(seed, 0, seed.length);
}
@@ -122,22 +102,20 @@ public class MDGenerator extends BasePRNG implements Cloneable
md.update(buffer, 0, buffer.length);
}
- public void addRandomByte (final byte b)
+ public void addRandomByte(final byte b)
{
if (md == null)
- throw new IllegalStateException ("not initialized");
- md.update (b);
+ throw new IllegalStateException("not initialized");
+ md.update(b);
}
- public void addRandomBytes (final byte[] buf, final int off, final int len)
+ public void addRandomBytes(final byte[] buf, final int off, final int len)
{
if (md == null)
- throw new IllegalStateException ("not initialized");
- md.update (buf, off, len);
+ throw new IllegalStateException("not initialized");
+ md.update(buf, off, len);
}
- // Cloneable interface implementation ---------------------------------------
-
public Object clone() throws CloneNotSupportedException
{
MDGenerator result = (MDGenerator) super.clone();
diff --git a/libjava/classpath/gnu/java/security/prng/PRNGFactory.java b/libjava/classpath/gnu/java/security/prng/PRNGFactory.java
index 8b51414..ae15d05 100644
--- a/libjava/classpath/gnu/java/security/prng/PRNGFactory.java
+++ b/libjava/classpath/gnu/java/security/prng/PRNGFactory.java
@@ -42,60 +42,46 @@ import gnu.java.security.Registry;
import java.util.Collections;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Set;
/**
- *
*
- *
+ *
* @param crl The CRL being checked.
* @param path The path this CRL is being checked against.
* @param now The value to use as 'now'.
- * @param pubKeySubject The subject of the public key.
+ * @param pubKeyCert The certificate authenticating the public key.
* @param pubKey The public key to check.
* @return True if the CRL is acceptable.
*/
- private static boolean checkCRL(X509CRL crl, X509Certificate[] path, Date now,
- X509Certificate pubKeyCert, PublicKey pubKey,
- List certStores)
+ private static boolean checkCRL(X509CRL crl, X509Certificate[] path,
+ Date now, X509Certificate pubKeyCert,
+ PublicKey pubKey, List certStores)
{
Date nextUpdate = crl.getNextUpdate();
if (nextUpdate != null && nextUpdate.compareTo(now) < 0)
@@ -450,12 +422,12 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
return false;
for (int i = 0; i < path.length; i++)
{
- if (!path[i].getSubjectDN().equals(crl.getIssuerDN()))
+ if (! path[i].getSubjectDN().equals(crl.getIssuerDN()))
continue;
boolean[] keyUsage = path[i].getKeyUsage();
if (keyUsage != null)
{
- if (!keyUsage[KeyUsage.CRL_SIGN])
+ if (! keyUsage[KeyUsage.CRL_SIGN])
continue;
}
try
@@ -474,7 +446,7 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
boolean[] keyUsage = pubKeyCert.getKeyUsage();
if (keyUsage != null)
{
- if (!keyUsage[KeyUsage.CRL_SIGN])
+ if (! keyUsage[KeyUsage.CRL_SIGN])
throw new Exception();
}
crl.verify(pubKey);
@@ -489,7 +461,7 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
X509CertSelectorImpl select = new X509CertSelectorImpl();
select.addSubjectName(crl.getIssuerDN());
List certs = new LinkedList();
- for (Iterator it = certStores.iterator(); it.hasNext(); )
+ for (Iterator it = certStores.iterator(); it.hasNext();)
{
CertStore cs = (CertStore) it.next();
try
@@ -500,17 +472,17 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
{
}
}
- for (Iterator it = certs.iterator(); it.hasNext(); )
+ for (Iterator it = certs.iterator(); it.hasNext();)
{
X509Certificate c = (X509Certificate) it.next();
for (int i = 0; i < path.length; i++)
{
- if (!c.getIssuerDN().equals(path[i].getSubjectDN()))
+ if (! c.getIssuerDN().equals(path[i].getSubjectDN()))
continue;
boolean[] keyUsage = c.getKeyUsage();
if (keyUsage != null)
{
- if (!keyUsage[KeyUsage.CRL_SIGN])
+ if (! keyUsage[KeyUsage.CRL_SIGN])
continue;
}
try
@@ -542,10 +514,10 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
if (cert instanceof GnuPKIExtension)
{
Collection exts = ((GnuPKIExtension) cert).getExtensions();
- for (Iterator it = exts.iterator(); it.hasNext(); )
+ for (Iterator it = exts.iterator(); it.hasNext();)
{
Extension ext = (Extension) it.next();
- if (ext.isCritical() && !ext.isSupported())
+ if (ext.isCritical() && ! ext.isSupported())
s.add(ext.getOid().toString());
}
}
@@ -558,13 +530,13 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
* Perform a basic sanity check on the CA certificate at index
.
*/
private static void basicSanity(X509Certificate[] path, int index)
- throws CertPathValidatorException
+ throws CertPathValidatorException
{
X509Certificate cert = path[index];
int pathLen = 0;
for (int i = index - 1; i > 0; i--)
{
- if (!path[i].getIssuerDN().equals(path[i].getSubjectDN()))
+ if (! path[i].getIssuerDN().equals(path[i].getSubjectDN()))
pathLen++;
}
Extension e = null;
@@ -585,25 +557,30 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
if (e == null)
throw new CertPathValidatorException("no basicConstraints");
BasicConstraints bc = (BasicConstraints) e.getValue();
- if (!bc.isCA())
- throw new CertPathValidatorException("certificate cannot be used to verify signatures");
- if (bc.getPathLengthConstraint() >= 0 && bc.getPathLengthConstraint() < pathLen)
+ if (! bc.isCA())
+ throw new CertPathValidatorException(
+ "certificate cannot be used to verify signatures");
+ if (bc.getPathLengthConstraint() >= 0
+ && bc.getPathLengthConstraint() < pathLen)
throw new CertPathValidatorException("path is too long");
boolean[] keyUsage = cert.getKeyUsage();
if (keyUsage != null)
{
- if (!keyUsage[KeyUsage.KEY_CERT_SIGN])
- throw new CertPathValidatorException("certificate cannot be used to sign certificates");
+ if (! keyUsage[KeyUsage.KEY_CERT_SIGN])
+ throw new CertPathValidatorException(
+ "certificate cannot be used to sign certificates");
}
}
- private static void updatePolicyTree(X509Certificate cert, PolicyNodeImpl root,
- int depth, PKIXParameters params,
+ private static void updatePolicyTree(X509Certificate cert,
+ PolicyNodeImpl root, int depth,
+ PKIXParameters params,
boolean explicitPolicy)
- throws CertPathValidatorException
+ throws CertPathValidatorException
{
- if (DEBUG) debug("updatePolicyTree depth == " + depth);
+ if (Configuration.DEBUG)
+ log.fine("updatePolicyTree depth == " + depth);
Set nodes = new HashSet();
LinkedList stack = new LinkedList();
Iterator current = null;
@@ -614,21 +591,24 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
while (current.hasNext())
{
PolicyNodeImpl p = (PolicyNodeImpl) current.next();
- if (DEBUG) debug("visiting node == " + p);
+ if (Configuration.DEBUG)
+ log.fine("visiting node == " + p);
if (p.getDepth() == depth - 1)
{
- if (DEBUG) debug("added node");
+ if (Configuration.DEBUG)
+ log.fine("added node");
nodes.add(p);
}
else
{
- if (DEBUG) debug("skipped node");
+ if (Configuration.DEBUG)
+ log.fine("skipped node");
stack.addLast(current);
current = p.getChildren();
}
}
}
- while (!stack.isEmpty());
+ while (! stack.isEmpty());
Extension e = null;
CertificatePolicies policies = null;
@@ -646,18 +626,23 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
else
cp = Collections.EMPTY_LIST;
boolean match = false;
- if (DEBUG) debug("nodes are == " + nodes);
- if (DEBUG) debug("cert policies are == " + cp);
- for (Iterator it = nodes.iterator(); it.hasNext(); )
+ if (Configuration.DEBUG)
+ {
+ log.fine("nodes are == " + nodes);
+ log.fine("cert policies are == " + cp);
+ }
+ for (Iterator it = nodes.iterator(); it.hasNext();)
{
PolicyNodeImpl parent = (PolicyNodeImpl) it.next();
- if (DEBUG) debug("adding policies to " + parent);
- for (Iterator it2 = cp.iterator(); it2.hasNext(); )
+ if (Configuration.DEBUG)
+ log.fine("adding policies to " + parent);
+ for (Iterator it2 = cp.iterator(); it2.hasNext();)
{
OID policy = (OID) it2.next();
- if (DEBUG) debug("trying to add policy == " + policy);
- if (policy.toString().equals(ANY_POLICY) &&
- params.isAnyPolicyInhibited())
+ if (Configuration.DEBUG)
+ log.fine("trying to add policy == " + policy);
+ if (policy.toString().equals(ANY_POLICY)
+ && params.isAnyPolicyInhibited())
continue;
PolicyNodeImpl child = new PolicyNodeImpl();
child.setValidPolicy(policy.toString());
@@ -672,32 +657,34 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi
parent.addChild(child);
match = true;
}
- else if (ANY_POLICY.equals (policy.toString()))
+ else if (ANY_POLICY.equals(policy.toString()))
{
- parent.addChild (child);
+ parent.addChild(child);
match = true;
}
if (match && policies != null)
{
- List qualifiers = policies.getPolicyQualifierInfos (policy);
+ List qualifiers = policies.getPolicyQualifierInfos(policy);
if (qualifiers != null)
- child.addAllPolicyQualifiers (qualifiers);
+ child.addAllPolicyQualifiers(qualifiers);
}
}
}
- if (!match && (params.isExplicitPolicyRequired() || explicitPolicy))
+ if (! match && (params.isExplicitPolicyRequired() || explicitPolicy))
throw new CertPathValidatorException("policy tree building failed");
}
- private boolean checkExplicitPolicy (int depth, List explicitPolicies)
+ private boolean checkExplicitPolicy(int depth, List explicitPolicies)
{
- if (DEBUG) debug ("checkExplicitPolicy depth=" + depth);
- for (Iterator it = explicitPolicies.iterator(); it.hasNext(); )
+ if (Configuration.DEBUG)
+ log.fine("checkExplicitPolicy depth=" + depth);
+ for (Iterator it = explicitPolicies.iterator(); it.hasNext();)
{
int[] i = (int[]) it.next();
int caDepth = i[0];
int limit = i[1];
- if (DEBUG) debug (" caDepth=" + caDepth + " limit=" + limit);
+ if (Configuration.DEBUG)
+ log.fine(" caDepth=" + caDepth + " limit=" + limit);
if (depth - caDepth >= limit)
return true;
}
diff --git a/libjava/classpath/gnu/java/security/provider/X509CertificateFactory.java b/libjava/classpath/gnu/java/security/provider/X509CertificateFactory.java
index 1a415ea..7d61779 100644
--- a/libjava/classpath/gnu/java/security/provider/X509CertificateFactory.java
+++ b/libjava/classpath/gnu/java/security/provider/X509CertificateFactory.java
@@ -59,30 +59,24 @@ import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
-public class X509CertificateFactory extends CertificateFactorySpi
+public class X509CertificateFactory
+ extends CertificateFactorySpi
{
-
- // Constants.
- // ------------------------------------------------------------------------
-
public static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----";
+
public static final String END_CERTIFICATE = "-----END CERTIFICATE-----";
+
public static final String BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
- public static final String END_X509_CRL = "-----END X509 CRL-----";
- // Constructors.
- // ------------------------------------------------------------------------
+ public static final String END_X509_CRL = "-----END X509 CRL-----";
public X509CertificateFactory()
{
super();
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
public Certificate engineGenerateCertificate(InputStream inStream)
- throws CertificateException
+ throws CertificateException
{
try
{
@@ -91,13 +85,13 @@ public class X509CertificateFactory extends CertificateFactorySpi
catch (IOException ioe)
{
CertificateException ce = new CertificateException(ioe.getMessage());
- ce.initCause (ioe);
+ ce.initCause(ioe);
throw ce;
}
}
public Collection engineGenerateCertificates(InputStream inStream)
- throws CertificateException
+ throws CertificateException
{
LinkedList certs = new LinkedList();
while (true)
@@ -113,7 +107,7 @@ public class X509CertificateFactory extends CertificateFactorySpi
catch (IOException ioe)
{
CertificateException ce = new CertificateException(ioe.getMessage());
- ce.initCause (ioe);
+ ce.initCause(ioe);
throw ce;
}
}
@@ -129,13 +123,13 @@ public class X509CertificateFactory extends CertificateFactorySpi
catch (IOException ioe)
{
CRLException crle = new CRLException(ioe.getMessage());
- crle.initCause (ioe);
+ crle.initCause(ioe);
throw crle;
}
}
public Collection engineGenerateCRLs(InputStream inStream)
- throws CRLException
+ throws CRLException
{
LinkedList crls = new LinkedList();
while (true)
@@ -151,7 +145,7 @@ public class X509CertificateFactory extends CertificateFactorySpi
catch (IOException ioe)
{
CRLException crle = new CRLException(ioe.getMessage());
- crle.initCause (ioe);
+ crle.initCause(ioe);
throw crle;
}
}
@@ -164,13 +158,13 @@ public class X509CertificateFactory extends CertificateFactorySpi
}
public CertPath engineGenerateCertPath(InputStream in)
- throws CertificateEncodingException
+ throws CertificateEncodingException
{
return new X509CertPath(in);
}
public CertPath engineGenerateCertPath(InputStream in, String encoding)
- throws CertificateEncodingException
+ throws CertificateEncodingException
{
return new X509CertPath(in, encoding);
}
@@ -180,21 +174,17 @@ public class X509CertificateFactory extends CertificateFactorySpi
return X509CertPath.ENCODINGS.iterator();
}
- // Own methods.
- // ------------------------------------------------------------------------
-
private X509Certificate generateCert(InputStream inStream)
- throws IOException, CertificateException
+ throws IOException, CertificateException
{
if (inStream == null)
throw new CertificateException("missing input stream");
- if (!inStream.markSupported())
+ if (! inStream.markSupported())
inStream = new BufferedInputStream(inStream, 8192);
inStream.mark(20);
int i = inStream.read();
if (i == -1)
throw new EOFException();
-
// If the input is in binary DER format, the first byte MUST be
// 0x30, which stands for the ASN.1 [UNIVERSAL 16], which is the
// UNIVERSAL SEQUENCE, with the CONSTRUCTED bit (0x20) set.
@@ -217,9 +207,9 @@ public class X509CertificateFactory extends CertificateFactorySpi
}
while (i != '\n' && i != '\r');
}
- while (!line.toString().equals(BEGIN_CERTIFICATE));
+ while (! line.toString().equals(BEGIN_CERTIFICATE));
X509Certificate ret = new X509Certificate(
- new BufferedInputStream(new Base64InputStream(inStream), 8192));
+ new BufferedInputStream(new Base64InputStream(inStream), 8192));
line.setLength(0);
line.append('-'); // Base64InputStream will eat this.
do
@@ -232,7 +222,7 @@ public class X509CertificateFactory extends CertificateFactorySpi
}
while (i != '\n' && i != '\r');
// XXX ???
- if (!line.toString().equals(END_CERTIFICATE))
+ if (! line.toString().equals(END_CERTIFICATE))
throw new CertificateException("no end-of-certificate marker");
return ret;
}
@@ -243,18 +233,17 @@ public class X509CertificateFactory extends CertificateFactorySpi
}
}
- private X509CRL generateCRL(InputStream inStream)
- throws IOException, CRLException
+ private X509CRL generateCRL(InputStream inStream) throws IOException,
+ CRLException
{
if (inStream == null)
throw new CRLException("missing input stream");
- if (!inStream.markSupported())
+ if (! inStream.markSupported())
inStream = new BufferedInputStream(inStream, 8192);
inStream.mark(20);
int i = inStream.read();
if (i == -1)
throw new EOFException();
-
// If the input is in binary DER format, the first byte MUST be
// 0x30, which stands for the ASN.1 [UNIVERSAL 16], which is the
// UNIVERSAL SEQUENCE, with the CONSTRUCTED bit (0x20) set.
@@ -277,9 +266,9 @@ public class X509CertificateFactory extends CertificateFactorySpi
}
while (i != '\n' && i != '\r');
}
- while (!line.toString().startsWith(BEGIN_X509_CRL));
+ while (! line.toString().startsWith(BEGIN_X509_CRL));
X509CRL ret = new X509CRL(
- new BufferedInputStream(new Base64InputStream(inStream), 8192));
+ new BufferedInputStream(new Base64InputStream(inStream), 8192));
line.setLength(0);
line.append('-'); // Base64InputStream will eat this.
do
@@ -292,7 +281,7 @@ public class X509CertificateFactory extends CertificateFactorySpi
}
while (i != '\n' && i != '\r');
// XXX ???
- if (!line.toString().startsWith(END_X509_CRL))
+ if (! line.toString().startsWith(END_X509_CRL))
throw new CRLException("no end-of-CRL marker");
return ret;
}
diff --git a/libjava/classpath/gnu/java/security/sig/BaseSignature.java b/libjava/classpath/gnu/java/security/sig/BaseSignature.java
index dd964d4..9c76cac 100644
--- a/libjava/classpath/gnu/java/security/sig/BaseSignature.java
+++ b/libjava/classpath/gnu/java/security/sig/BaseSignature.java
@@ -49,15 +49,11 @@ import java.util.Map;
import java.util.Random;
/**
- *
- *
*/
-public interface ISignature extends Cloneable
+public interface ISignature
+ extends Cloneable
{
-
- // Constants
- // -------------------------------------------------------------------------
-
/** Property name of the verifier's public key. */
public static final String VERIFIER_KEY = "gnu.crypto.sig.public.key";
@@ -71,96 +67,93 @@ public interface ISignature extends Cloneable
/**
* Property name of an optional {@link java.security.SecureRandom},
- * {@link java.util.Random}, or {@link gnu.crypto.prng.IRandom} instance to
- * use. The default is to use a classloader singleton from
- * {@link gnu.crypto.util.PRNG}.
+ * {@link java.util.Random}, or {@link gnu.java.security.prng.IRandom}
+ * instance to use. The default is to use a classloader singleton from
+ * {@link gnu.java.security.util.PRNG}.
*/
public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.sig.prng";
- // Methods
- // -------------------------------------------------------------------------
-
/**
- * buffer
of the first byte
- * to consider.
- * @param length the number of bytes in buffer
starting from the
- * byte at index offset
to digest.
- * @throws IllegalStateException if this instance was not setup for
- * signature generation/verification.
+ * to consider.
+ * @param length the number of bytes in buffer
starting from
+ * the byte at index offset
to digest.
+ * @throws IllegalStateException if this instance was not setup for signature
+ * generation/verification.
*/
void update(byte[] buffer, int offset, int length)
throws IllegalStateException;
/**
- * sign()
method.
+ * invocation of the sign()
method.
* @return true
iff the outpout of the verification phase
- * confirms that the designated signature object has been generated using the
- * corresponding public key of the recepient.
- * @throws IllegalStateException if this instance was not setup for
- * signature verification.
+ * confirms that the designated signature object has been generated
+ * using the corresponding public key of the recepient.
+ * @throws IllegalStateException if this instance was not setup for signature
+ * verification.
*/
boolean verify(Object signature) throws IllegalStateException;
/**
- * null
if none found.
*/
public static final ISignature getInstance(String ssa)
{
if (ssa == null)
- {
- return null;
- }
+ return null;
ssa = ssa.trim();
ssa = ssa.toLowerCase();
ISignature result = null;
if (ssa.equalsIgnoreCase(Registry.DSA_SIG) || ssa.equals(Registry.DSS_SIG))
- {
- result = new DSSSignature();
- }
+ result = new DSSSignature();
else if (ssa.startsWith(Registry.RSA_SIG_PREFIX))
result = RSASignatureFactory.getInstance(ssa);
@@ -92,9 +82,9 @@ public class SignatureFactory
}
/**
- * Returns a {@link Set} of signature-with-appendix scheme names supported
- * by this Factory.
- *
+ * Returns a {@link Set} of signature-with-appendix scheme names supported by
+ * this Factory.
+ *
* @return a {@link Set} of signature-with-appendix scheme names (Strings).
*/
public static synchronized final Set getNames()
@@ -104,10 +94,8 @@ public class SignatureFactory
HashSet hs = new HashSet();
hs.add(Registry.DSS_SIG);
hs.addAll(RSASignatureFactory.getNames());
-
names = Collections.unmodifiableSet(hs);
}
-
return names;
}
}
diff --git a/libjava/classpath/gnu/java/security/sig/dss/DSSSignature.java b/libjava/classpath/gnu/java/security/sig/dss/DSSSignature.java
index 370a938..1ef1bea 100644
--- a/libjava/classpath/gnu/java/security/sig/dss/DSSSignature.java
+++ b/libjava/classpath/gnu/java/security/sig/dss/DSSSignature.java
@@ -55,72 +55,65 @@ import java.util.Map;
import java.util.Random;
/**
- *
- *
- *
- * 2L-1 < p < 2L
- *
for 512 <= L <= 1024
and L
a
- * multiple of 64
.p - 1
, where 2159
+ *
2L-1 < p < 2L
for 512 <= L
+ * <= 1024
and L
a multiple of 64
.p - 1
, where 2159
* < q < 2160
.g = h(p-1)/q mod p
, where
- * h
is any integer with 1 < h < p - 1
such
- * that h (p-1)/q mod p > 1
(g
has order
- * q mod p
).0 < x
+ *
g = h(p-1)/q mod p
, where
+ * h
is any integer with 1 < h < p - 1
such
+ * that h (p-1)/q mod p > 1
(g
has order
+ * q mod p
).0 < x
* < q
.y = gx mod p
.0 < k
+ *
y = gx mod p
.0 < k
* < q
.p
, q
, and g
can be
+ * p
, q
, and g
can be
* public and can be common to a group of users. A user's private and public
- * keys are x
and y
, respectively. They are normally
- * fixed for a period of time. Parameters x
and k
are
- * used for signature generation only, and must be kept secret. Parameter
- * k
must be regenerated for each signature.M
is the pair of numbers r
- * and s
computed according to the equations below:x
and y
, respectively. They are
+ * normally fixed for a period of time. Parameters x
and
+ * k
are used for signature generation only, and must be kept
+ * secret. Parameter k
must be regenerated for each signature.
+ * M
is the pair of numbers
+ * r
and s
computed according to the equations below:
*
- *
- *
- * r = (gk mod p) mod q
ands = (k-1(SHA(M) + xr)) mod q
.r = (gk mod p) mod q
ands = (k-1(SHA(M) + xr)) mod q
.k-1
is the multiplicative inverse of
- * k
, mod q
; i.e., (k-1 k) mod q = 1
- *
and 0 < k-1 < q
. The value of SHA(M)
- * is a 160-bit string output by the Secure Hash Algorithm specified in FIPS 180.
- * For use in computing s
, this string must be converted to an
- * integer.r == 0
or s == 0
- *
. If either r == 0
or s == 0
, a new value
- * of k
should be generated and the signature should be
- * recalculated (it is extremely unlikely that r == 0
or s ==
- * 0
if signatures are generated properly).k-1
is the multiplicative inverse of
+ * k
, mod q
; i.e., (k-1 k) mod q =
+ * 1
and 0 < k-1 < q
. The value of SHA(M)
+ * is a 160-bit string output by the Secure Hash Algorithm specified in FIPS
+ * 180. For use in computing s
, this string must be converted to
+ * an integer.
+ * r == 0
or s == 0
+ *
.
+ * If either r == 0
or s == 0
, a new value of
+ * k
should be generated and the signature should be recalculated
+ * (it is extremely unlikely that r == 0
or s == 0
if
+ * signatures are generated properly).
+ *
- *
*/
-public class DSSSignature extends BaseSignature
+public class DSSSignature
+ extends BaseSignature
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public DSSSignature()
{
@@ -137,16 +130,12 @@ public class DSSSignature extends BaseSignature
this.md = (IMessageDigest) that.md.clone();
}
- // Class methods
- // -------------------------------------------------------------------------
-
public static final BigInteger[] sign(final DSAPrivateKey k, final byte[] h)
{
final DSSSignature sig = new DSSSignature();
final Map attributes = new HashMap();
attributes.put(ISignature.SIGNER_KEY, k);
sig.setupSign(attributes);
-
return sig.computeRS(h);
}
@@ -157,11 +146,9 @@ public class DSSSignature extends BaseSignature
final Map attributes = new HashMap();
attributes.put(ISignature.SIGNER_KEY, k);
if (rnd != null)
- {
- attributes.put(ISignature.SOURCE_OF_RANDOMNESS, rnd);
- }
- sig.setupSign(attributes);
+ attributes.put(ISignature.SOURCE_OF_RANDOMNESS, rnd);
+ sig.setupSign(attributes);
return sig.computeRS(h);
}
@@ -172,11 +159,9 @@ public class DSSSignature extends BaseSignature
final Map attributes = new HashMap();
attributes.put(ISignature.SIGNER_KEY, k);
if (irnd != null)
- {
- attributes.put(ISignature.SOURCE_OF_RANDOMNESS, irnd);
- }
- sig.setupSign(attributes);
+ attributes.put(ISignature.SOURCE_OF_RANDOMNESS, irnd);
+ sig.setupSign(attributes);
return sig.computeRS(h);
}
@@ -187,13 +172,9 @@ public class DSSSignature extends BaseSignature
final Map attributes = new HashMap();
attributes.put(ISignature.VERIFIER_KEY, k);
sig.setupVerify(attributes);
-
return sig.checkRS(rs, h);
}
- // Implementation of abstract methods in superclass
- // -------------------------------------------------------------------------
-
public Object clone()
{
return new DSSSignature(this);
@@ -202,81 +183,37 @@ public class DSSSignature extends BaseSignature
protected void setupForVerification(PublicKey k)
throws IllegalArgumentException
{
- if (!(k instanceof DSAPublicKey))
- {
- throw new IllegalArgumentException();
- }
+ if (! (k instanceof DSAPublicKey))
+ throw new IllegalArgumentException();
+
this.publicKey = k;
}
protected void setupForSigning(PrivateKey k) throws IllegalArgumentException
{
- if (!(k instanceof DSAPrivateKey))
- {
- throw new IllegalArgumentException();
- }
+ if (! (k instanceof DSAPrivateKey))
+ throw new IllegalArgumentException();
+
this.privateKey = k;
}
protected Object generateSignature() throws IllegalStateException
{
- // BigInteger p = ((DSAPrivateKey) privateKey).getParams().getP();
- // BigInteger q = ((DSAPrivateKey) privateKey).getParams().getQ();
- // BigInteger g = ((DSAPrivateKey) privateKey).getParams().getG();
- // BigInteger x = ((DSAPrivateKey) privateKey).getX();
- // BigInteger m = new BigInteger(1, md.digest());
- // BigInteger k, r, s;
- //
- // byte[] kb = new byte[20]; // we'll use 159 bits only
- // while (true) {
- // this.nextRandomBytes(kb);
- // k = new BigInteger(1, kb);
- // k.clearBit(159);
- // r = g.modPow(k, p).mod(q);
- // if (r.equals(BigInteger.ZERO)) {
- // continue;
- // }
- // s = m.add(x.multiply(r)).multiply(k.modInverse(q)).mod(q);
- // if (s.equals(BigInteger.ZERO)) {
- // continue;
- // }
- // break;
- // }
final BigInteger[] rs = computeRS(md.digest());
-
- // return encodeSignature(r, s);
return encodeSignature(rs[0], rs[1]);
}
protected boolean verifySignature(Object sig) throws IllegalStateException
{
final BigInteger[] rs = decodeSignature(sig);
- // BigInteger r = rs[0];
- // BigInteger s = rs[1];
- //
- // BigInteger g = ((DSAPublicKey) publicKey).getParams().getG();
- // BigInteger p = ((DSAPublicKey) publicKey).getParams().getP();
- // BigInteger q = ((DSAPublicKey) publicKey).getParams().getQ();
- // BigInteger y = ((DSAPublicKey) publicKey).getY();
- // BigInteger w = s.modInverse(q);
- //
- // byte bytes[] = md.digest();
- // BigInteger u1 = w.multiply(new BigInteger(1, bytes)).mod(q);
- // BigInteger u2 = r.multiply(w).mod(q);
- //
- // BigInteger v = g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q);
- // return v.equals(r);
return checkRS(rs, md.digest());
}
- // Other instance methods
- // -------------------------------------------------------------------------
-
/**
- * Returns the output of a signature generation phase.r
and
- * s
.
+ * s
.
*/
private Object encodeSignature(BigInteger r, BigInteger s)
{
@@ -284,9 +221,9 @@ public class DSSSignature extends BaseSignature
}
/**
- * Returns the output of a previously generated signature object as a pair
- * of {@link java.math.BigInteger}.r
and s
.
*/
private BigInteger[] decodeSignature(Object signature)
@@ -302,7 +239,6 @@ public class DSSSignature extends BaseSignature
final BigInteger x = ((DSAPrivateKey) privateKey).getX();
final BigInteger m = new BigInteger(1, digestBytes);
BigInteger k, r, s;
-
final byte[] kb = new byte[20]; // we'll use 159 bits only
while (true)
{
@@ -311,17 +247,14 @@ public class DSSSignature extends BaseSignature
k.clearBit(159);
r = g.modPow(k, p).mod(q);
if (r.equals(BigInteger.ZERO))
- {
- continue;
- }
+ continue;
+
s = m.add(x.multiply(r)).multiply(k.modInverse(q)).mod(q);
if (s.equals(BigInteger.ZERO))
- {
- continue;
- }
+ continue;
+
break;
}
-
return new BigInteger[] { r, s };
}
@@ -329,16 +262,13 @@ public class DSSSignature extends BaseSignature
{
final BigInteger r = rs[0];
final BigInteger s = rs[1];
-
final BigInteger g = ((DSAPublicKey) publicKey).getParams().getG();
final BigInteger p = ((DSAPublicKey) publicKey).getParams().getP();
final BigInteger q = ((DSAPublicKey) publicKey).getParams().getQ();
final BigInteger y = ((DSAPublicKey) publicKey).getY();
final BigInteger w = s.modInverse(q);
-
final BigInteger u1 = w.multiply(new BigInteger(1, digestBytes)).mod(q);
final BigInteger u2 = r.multiply(w).mod(q);
-
final BigInteger v = g.modPow(u1, p).multiply(y.modPow(u2, p)).mod(p).mod(q);
return v.equals(r);
}
diff --git a/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureRawCodec.java b/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureRawCodec.java
index b0590a5..903d7aa 100644
--- a/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureRawCodec.java
+++ b/libjava/classpath/gnu/java/security/sig/dss/DSSSignatureRawCodec.java
@@ -45,61 +45,46 @@ import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
/**
- *
- *
- *
+ *
* @param signature the signature to encode, consisting of the two DSS
- * parameters r
in internet order,toByteArray()
method on the DSS parameter r
,s
,toByteArray()
method on the DSS parameter s
.r
in internet order,toByteArray()
method on the DSS parameter r
,
+ * s
,toByteArray()
method on the DSS parameter s
.
+ * r
and s
as a {@link java.math.BigInteger}
- * array.
+ * parameters r
and s
as a
+ * {@link BigInteger} array.
* @return the Raw format encoding of the designated signature.
* @exception IllegalArgumentException if the designated signature is not a
- * DSS (Digital Signature Standard) one.
+ * DSS (Digital Signature Standard) one.
*/
public byte[] encodeSignature(Object signature)
{
@@ -112,38 +97,32 @@ public class DSSSignatureRawCodec implements ISignatureCodec
}
catch (Exception x)
{
- throw new IllegalArgumentException("key");
+ throw new IllegalArgumentException("signature");
}
-
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_DSS_SIGNATURE[0]);
baos.write(Registry.MAGIC_RAW_DSS_SIGNATURE[1]);
baos.write(Registry.MAGIC_RAW_DSS_SIGNATURE[2]);
baos.write(Registry.MAGIC_RAW_DSS_SIGNATURE[3]);
-
// version
baos.write(0x01);
-
// r
byte[] buffer = r.toByteArray();
int length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
// s
buffer = s.toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -154,36 +133,32 @@ public class DSSSignatureRawCodec implements ISignatureCodec
|| k[1] != Registry.MAGIC_RAW_DSS_SIGNATURE[1]
|| k[2] != Registry.MAGIC_RAW_DSS_SIGNATURE[2]
|| k[3] != Registry.MAGIC_RAW_DSS_SIGNATURE[3])
- {
- throw new IllegalArgumentException("magic");
- }
-
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
+ throw new IllegalArgumentException("version");
int i = 5;
int l;
byte[] buffer;
-
// r
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger r = new BigInteger(1, buffer);
-
// s
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger s = new BigInteger(1, buffer);
-
return new BigInteger[] { r, s };
}
}
diff --git a/libjava/classpath/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java b/libjava/classpath/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java
index efe580d..39de01f 100644
--- a/libjava/classpath/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java
+++ b/libjava/classpath/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java
@@ -47,25 +47,21 @@ import java.security.interfaces.RSAKey;
import java.util.Random;
/**
- * k
which is the
- * byte count of an RSA public shared modulus.k
which is the
+ * byte count of an RSA public shared modulus.
+ *
- *
*/
public class EME_PKCS1_V1_5
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private int k;
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -73,9 +69,6 @@ public class EME_PKCS1_V1_5
/** Our default source of randomness. */
private PRNG prng = PRNG.getInstance();
- // Constructor(s)
- // -------------------------------------------------------------------------
-
private EME_PKCS1_V1_5(final int k)
{
super();
@@ -83,15 +76,11 @@ public class EME_PKCS1_V1_5
this.k = k;
}
- // Class methods
- // -------------------------------------------------------------------------
-
public static final EME_PKCS1_V1_5 getInstance(final int k)
{
if (k < 0)
- {
- throw new IllegalArgumentException("k must be a positive integer");
- }
+ throw new IllegalArgumentException("k must be a positive integer");
+
return new EME_PKCS1_V1_5(k);
}
@@ -102,34 +91,29 @@ public class EME_PKCS1_V1_5
return EME_PKCS1_V1_5.getInstance(k);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
- *
- * RSA Cryptography Specifications Version 2.1.
- * Jakob Jonsson and Burt Kaliski.
+ * RSA Cryptography Specifications Version 2.1.
+ * Jakob Jonsson and Burt Kaliski.PS
of length k - mLen -
- * 3
consisting of pseudo-randomly generated nonzero octets. The
- * length of PS
will be at least eight octets.PS
, the message M
,
+ * Generates an octet string PS
of length k - mLen -
+ * 3
consisting of pseudo-randomly generated nonzero octets. The length
+ * of PS
will be at least eight octets.
+ * PS
, the message M
,
* and other padding to form an encoded message EM
of length
- * k
octets as:k
octets as:
*
- * EM = 0x00 || 0x02 || PS || 0x00 || M.
+ * EM = 0x00 || 0x02 || PS || 0x00 || M.
*
- *
- * EM
.
*/
public byte[] encode(final byte[] M)
{
// a. Generate an octet string PS of length k - mLen - 3 consisting
- // of pseudo-randomly generated nonzero octets. The length of PS
- // will be at least eight octets.
+ // of pseudo-randomly generated nonzero octets. The length of PS
+ // will be at least eight octets.
final byte[] PS = new byte[k - M.length - 3];
-
// FIXME. This should be configurable, somehow.
prng.nextBytes(PS);
int i = 0;
@@ -139,17 +123,17 @@ public class EME_PKCS1_V1_5
PS[i] = 1;
}
// b. Concatenate PS, the message M, and other padding to form an
- // encoded message EM of length k octets as
+ // encoded message EM of length k octets as
//
- // EM = 0x00 || 0x02 || PS || 0x00 || M.
+ // EM = 0x00 || 0x02 || PS || 0x00 || M.
return assembleEM(PS, M);
}
/**
- * EM
.
@@ -183,14 +167,13 @@ public class EME_PKCS1_V1_5
{
throw new RuntimeException("encode(): " + String.valueOf(x));
}
-
return assembleEM(PS, M);
}
/**
- * EM
.
@@ -213,33 +196,31 @@ public class EME_PKCS1_V1_5
}
break;
}
-
return assembleEM(PS, M);
}
/**
- * EM
into an octet string
+ * Separate the encoded message EM
into an octet string
* PS
consisting of nonzero octets and a message M
- * as:
- * EM = 0x00 || 0x02 || PS || 0x00 || M.
+ * EM = 0x00 || 0x02 || PS || 0x00 || M.
*
- *
- * EM
does not have hexadecimal value
- * 0x00
, if the second octet of EM
does not have
- * hexadecimal value 0x02
, if there is no octet with hexadecimal
- * value 0x00
to separate PS
from M
,
- * or if the length of PS
is less than 8
octets,
- * output "decryption error" and stop.EM
does not have hexadecimal value
+ * 0x00
, if the second octet of EM
does not
+ * have hexadecimal value 0x02
, if there is no octet with
+ * hexadecimal value 0x00
to separate PS
from
+ * M
, or if the length of PS
is less than
+ * 8
octets, output "decryption error" and stop.
+ *
* @param EM the designated encoded message.
* @return the decoded message M
framed in the designated
- * EM
value.
+ * EM
value.
* @throws IllegalArgumentException if the length of the designated entity
- * EM
is different than k
(the length in bytes of
- * the public shared modulus), or if any of the conditions described above
- * is detected.
+ * EM
is different than k
(the length
+ * in bytes of the public shared modulus), or if any of the
+ * conditions described above is detected.
*/
public byte[] decode(final byte[] EM)
{
@@ -252,46 +233,34 @@ public class EME_PKCS1_V1_5
// the second octet of EM does not have hexadecimal value 0x02, if
// there is no octet with hexadecimal value 0x00 to separate PS from
// M, or if the length of PS is less than 8 octets, output
- // "decryption error" and stop. (See the note below.)
+ // "decryption error" and stop. (See the note below.)
final int emLen = EM.length;
if (emLen != k)
- {
- throw new IllegalArgumentException("decryption error");
- }
+ throw new IllegalArgumentException("decryption error");
if (EM[0] != 0x00)
- {
- throw new IllegalArgumentException("decryption error");
- }
+ throw new IllegalArgumentException("decryption error");
if (EM[1] != 0x02)
- {
- throw new IllegalArgumentException("decryption error");
- }
+ throw new IllegalArgumentException("decryption error");
int i = 2;
for (; i < emLen; i++)
{
if (EM[i] == 0x00)
- {
- break;
- }
+ break;
}
if (i >= emLen || i < 11)
- {
- throw new IllegalArgumentException("decryption error");
- }
+ throw new IllegalArgumentException("decryption error");
i++;
final byte[] result = new byte[emLen - i];
System.arraycopy(EM, i, result, 0, result.length);
return result;
}
- // helper methods ----------------------------------------------------------
-
private byte[] assembleEM(final byte[] PS, final byte[] M)
{
// b. Concatenate PS, the message M, and other padding to form an
- // encoded message EM of length k octets as
+ // encoded message EM of length k octets as
//
- // EM = 0x00 || 0x02 || PS || 0x00 || M.
+ // EM = 0x00 || 0x02 || PS || 0x00 || M.
baos.reset();
baos.write(0x00);
baos.write(0x02);
@@ -300,7 +269,6 @@ public class EME_PKCS1_V1_5
baos.write(M, 0, M.length);
final byte[] result = baos.toByteArray();
baos.reset();
-
return result;
}
}
diff --git a/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java b/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java
index d155fc8..a0c4de1 100644
--- a/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java
+++ b/libjava/classpath/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java
@@ -45,12 +45,12 @@ import gnu.java.security.hash.IMessageDigest;
import java.io.ByteArrayOutputStream;
/**
- *
*
*/
-public class EMSA_PKCS1_V1_5 implements Cloneable
+public class EMSA_PKCS1_V1_5
+ implements Cloneable
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/* Notes.
1. For the six hash functions mentioned in Appendix B.1, the DER encoding
T of the DigestInfo value is equal to the following:
@@ -75,67 +72,46 @@ public class EMSA_PKCS1_V1_5 implements Cloneable
SHA-384: (0x)30 41 30 0d 06 09 60 86 48 01 65 03 04 02 02 05 00 04 30 || H
SHA-512: (0x)30 51 30 0d 06 09 60 86 48 01 65 03 04 02 03 05 00 04 40 || H
*/
- private static final byte[] MD2_PREFIX = { (byte) 0x30, (byte) 0x20,
- (byte) 0x30, (byte) 0x0c,
- (byte) 0x06, (byte) 0x08,
- (byte) 0x2a, (byte) 0x86,
- (byte) 0x48, (byte) 0x86,
- (byte) 0xf7, (byte) 0x0d,
- (byte) 0x02, (byte) 0x02,
- (byte) 0x05, (byte) 0x00,
- (byte) 0x04, (byte) 0x10 };
-
- private static final byte[] MD5_PREFIX = { (byte) 0x30, (byte) 0x20,
- (byte) 0x30, (byte) 0x0c,
- (byte) 0x06, (byte) 0x08,
- (byte) 0x2a, (byte) 0x86,
- (byte) 0x48, (byte) 0x86,
- (byte) 0xf7, (byte) 0x0d,
- (byte) 0x02, (byte) 0x05,
- (byte) 0x05, (byte) 0x00,
- (byte) 0x04, (byte) 0x10 };
-
- private static final byte[] SHA160_PREFIX = { (byte) 0x30, (byte) 0x21,
- (byte) 0x30, (byte) 0x09,
- (byte) 0x06, (byte) 0x05,
- (byte) 0x2b, (byte) 0x0e,
- (byte) 0x03, (byte) 0x02,
- (byte) 0x1a, (byte) 0x05,
- (byte) 0x00, (byte) 0x04,
- (byte) 0x14 };
-
- private static final byte[] SHA256_PREFIX = { (byte) 0x30, (byte) 0x31,
- (byte) 0x30, (byte) 0x0d,
- (byte) 0x06, (byte) 0x09,
- (byte) 0x60, (byte) 0x86,
- (byte) 0x48, (byte) 0x01,
- (byte) 0x65, (byte) 0x03,
- (byte) 0x04, (byte) 0x02,
- (byte) 0x01, (byte) 0x05,
- (byte) 0x00, (byte) 0x04,
- (byte) 0x20 };
-
- private static final byte[] SHA384_PREFIX = { (byte) 0x30, (byte) 0x41,
- (byte) 0x30, (byte) 0x0d,
- (byte) 0x06, (byte) 0x09,
- (byte) 0x60, (byte) 0x86,
- (byte) 0x48, (byte) 0x01,
- (byte) 0x65, (byte) 0x03,
- (byte) 0x04, (byte) 0x02,
- (byte) 0x02, (byte) 0x05,
- (byte) 0x00, (byte) 0x04,
- (byte) 0x30 };
-
- private static final byte[] SHA512_PREFIX = { (byte) 0x30, (byte) 0x51,
- (byte) 0x30, (byte) 0x0d,
- (byte) 0x06, (byte) 0x09,
- (byte) 0x60, (byte) 0x86,
- (byte) 0x48, (byte) 0x01,
- (byte) 0x65, (byte) 0x03,
- (byte) 0x04, (byte) 0x02,
- (byte) 0x03, (byte) 0x05,
- (byte) 0x00, (byte) 0x04,
- (byte) 0x40 };
+ private static final byte[] MD2_PREFIX = {
+ (byte) 0x30, (byte) 0x20, (byte) 0x30, (byte) 0x0c, (byte) 0x06,
+ (byte) 0x08, (byte) 0x2a, (byte) 0x86, (byte) 0x48, (byte) 0x86,
+ (byte) 0xf7, (byte) 0x0d, (byte) 0x02, (byte) 0x02, (byte) 0x05,
+ (byte) 0x00, (byte) 0x04, (byte) 0x10
+ };
+
+ private static final byte[] MD5_PREFIX = {
+ (byte) 0x30, (byte) 0x20, (byte) 0x30, (byte) 0x0c, (byte) 0x06,
+ (byte) 0x08, (byte) 0x2a, (byte) 0x86, (byte) 0x48, (byte) 0x86,
+ (byte) 0xf7, (byte) 0x0d, (byte) 0x02, (byte) 0x05, (byte) 0x05,
+ (byte) 0x00, (byte) 0x04, (byte) 0x10
+ };
+
+ private static final byte[] SHA160_PREFIX = {
+ (byte) 0x30, (byte) 0x21, (byte) 0x30, (byte) 0x09, (byte) 0x06,
+ (byte) 0x05, (byte) 0x2b, (byte) 0x0e, (byte) 0x03, (byte) 0x02,
+ (byte) 0x1a, (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x14
+ };
+
+ private static final byte[] SHA256_PREFIX = {
+ (byte) 0x30, (byte) 0x31, (byte) 0x30, (byte) 0x0d, (byte) 0x06,
+ (byte) 0x09, (byte) 0x60, (byte) 0x86, (byte) 0x48, (byte) 0x01,
+ (byte) 0x65, (byte) 0x03, (byte) 0x04, (byte) 0x02, (byte) 0x01,
+ (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x20
+ };
+
+ private static final byte[] SHA384_PREFIX = {
+ (byte) 0x30, (byte) 0x41, (byte) 0x30, (byte) 0x0d, (byte) 0x06,
+ (byte) 0x09, (byte) 0x60, (byte) 0x86, (byte) 0x48, (byte) 0x01,
+ (byte) 0x65, (byte) 0x03, (byte) 0x04, (byte) 0x02, (byte) 0x02,
+ (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x30
+ };
+
+ private static final byte[] SHA512_PREFIX = {
+ (byte) 0x30, (byte) 0x51, (byte) 0x30, (byte) 0x0d, (byte) 0x06,
+ (byte) 0x09, (byte) 0x60, (byte) 0x86, (byte) 0x48, (byte) 0x01,
+ (byte) 0x65, (byte) 0x03, (byte) 0x04, (byte) 0x02, (byte) 0x03,
+ (byte) 0x05, (byte) 0x00, (byte) 0x04, (byte) 0x40
+ };
/** The underlying hash function to use with this instance. */
private IMessageDigest hash;
@@ -146,11 +122,8 @@ public class EMSA_PKCS1_V1_5 implements Cloneable
/** The DER part of DigestInfo not containing the hash value itself. */
private byte[] prefix;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- *
@@ -58,12 +58,9 @@ import java.io.ByteArrayOutputStream;
* Jakob Jonsson and Burt Kaliski.
- *
*/
-public class EMSA_PSS implements Cloneable
+public class EMSA_PSS
+ implements Cloneable
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "emsa-pss";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
+ private static final Logger log = Logger.getLogger(EMSA_PSS.class.getName());
/** The underlying hash function to use with this instance. */
private IMessageDigest hash;
@@ -96,12 +81,9 @@ public class EMSA_PSS implements Cloneable
/** The output size of the hash function in octets. */
private int hLen;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- *
- * Primitive specification and supporting documentation.
- * Jakob Jonsson and Burt Kaliski.
+ * Primitive specification and supporting documentation.
+ * Jakob Jonsson and Burt Kaliski.M
using a hash function and maps the result to an encoded
* message EM
of a specified length using a mask generation
- * function.8.hLen + 8.sLen + 9
.
+ * 8.hLen + 8.sLen + 9
.
* @param salt the salt to use when encoding the output.
* @return the encoded message EM
, an octet string of length
- * emLen = CEILING(emBits / 8)
.
+ * emLen = CEILING(emBits / 8)
.
* @exception IllegalArgumentException if an exception occurs.
- *
*/
public byte[] encode(byte[] mHash, int emBits, byte[] salt)
{
int sLen = salt.length;
-
// 1. If the length of M is greater than the input limitation for the hash
// function (2**61 - 1 octets for SHA-1) then output "message too long"
// and stop.
// 2. Let mHash = Hash(M), an octet string of length hLen.
if (hLen != mHash.length)
- {
- throw new IllegalArgumentException("wrong hash");
- }
+ throw new IllegalArgumentException("wrong hash");
// 3. If emBits < 8.hLen + 8.sLen + 9, output 'encoding error' and stop.
if (emBits < (8 * hLen + 8 * sLen + 9))
- {
- throw new IllegalArgumentException("encoding error");
- }
+ throw new IllegalArgumentException("encoding error");
int emLen = (emBits + 7) / 8;
// 4. Generate a random octet string salt of length sLen; if sLen = 0,
// then salt is the empty string.
@@ -187,9 +153,8 @@ public class EMSA_PSS implements Cloneable
synchronized (hash)
{
for (i = 0; i < 8; i++)
- {
- hash.update((byte) 0x00);
- }
+ hash.update((byte) 0x00);
+
hash.update(mHash, 0, hLen);
hash.update(salt, 0, sLen);
H = hash.digest();
@@ -202,16 +167,14 @@ public class EMSA_PSS implements Cloneable
System.arraycopy(salt, 0, DB, emLen - sLen - hLen - 1, sLen);
// 9. Let dbMask = MGF(H, emLen - hLen - 1).
byte[] dbMask = MGF(H, emLen - hLen - 1);
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- debug("dbMask (encode): " + Util.toString(dbMask));
- debug("DB (encode): " + Util.toString(DB));
+ log.fine("dbMask (encode): " + Util.toString(dbMask));
+ log.fine("DB (encode): " + Util.toString(DB));
}
// 10. Let maskedDB = DB XOR dbMask.
for (i = 0; i < DB.length; i++)
- {
- DB[i] = (byte) (DB[i] ^ dbMask[i]);
- }
+ DB[i] = (byte)(DB[i] ^ dbMask[i]);
// 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in
// maskedDB to zero.
DB[0] &= (0xFF >>> (8 * emLen - emBits));
@@ -226,14 +189,14 @@ public class EMSA_PSS implements Cloneable
}
/**
- * EM
and compares it to the hash of
- * M
.EM
and compares it to the hash of
+ * M
.
+ *
* @param mHash the byte sequence resulting from applying the message digest
- * algorithm Hash to the message M.
+ * algorithm Hash to the message M.
* @param EM the encoded message, an octet string of length
- * emLen = CEILING(emBits/8).
+ *
emLen = CEILING(emBits/8).
* @param emBits the maximal bit length of the integer OS2IP(EM), at least
*
8.hLen + 8.sLen + 9
.
* @param sLen the length, in octets, of the expected salt.
@@ -244,60 +207,50 @@ public class EMSA_PSS implements Cloneable
*/
public boolean decode(byte[] mHash, byte[] EM, int emBits, int sLen)
{
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- debug("mHash: " + Util.toString(mHash));
- debug("EM: " + Util.toString(EM));
- debug("emBits: " + String.valueOf(emBits));
- debug("sLen: " + String.valueOf(sLen));
+ log.fine("mHash: " + Util.toString(mHash));
+ log.fine("EM: " + Util.toString(EM));
+ log.fine("emBits: " + String.valueOf(emBits));
+ log.fine("sLen: " + String.valueOf(sLen));
}
if (sLen < 0)
- {
- throw new IllegalArgumentException("sLen");
- }
-
+ throw new IllegalArgumentException("sLen");
// 1. If the length of M is greater than the input limitation for the hash
- // function (2**61 ? 1 octets for SHA-1) then output 'inconsistent' and
- // stop.
+ // function (2**61 ? 1 octets for SHA-1) then output 'inconsistent' and
+ // stop.
// 2. Let mHash = Hash(M), an octet string of length hLen.
if (hLen != mHash.length)
{
- if (DEBUG && debuglevel > 8)
- {
- debug("hLen != mHash.length; hLen: " + String.valueOf(hLen));
- }
+ if (Configuration.DEBUG)
+ log.fine("hLen != mHash.length; hLen: " + String.valueOf(hLen));
throw new IllegalArgumentException("wrong hash");
}
// 3. If emBits < 8.hLen + 8.sLen + 9, output 'decoding error' and stop.
if (emBits < (8 * hLen + 8 * sLen + 9))
{
- if (DEBUG && debuglevel > 8)
- {
- debug("emBits < (8hLen + 8sLen + 9); sLen: " + String.valueOf(sLen));
- }
+ if (Configuration.DEBUG)
+ log.fine("emBits < (8hLen + 8sLen + 9); sLen: "
+ + String.valueOf(sLen));
throw new IllegalArgumentException("decoding error");
}
int emLen = (emBits + 7) / 8;
// 4. If the rightmost octet of EM does not have hexadecimal value bc,
- // output 'inconsistent' and stop.
+ // output 'inconsistent' and stop.
if ((EM[EM.length - 1] & 0xFF) != 0xBC)
{
- if (DEBUG && debuglevel > 8)
- {
- debug("EM does not end with 0xBC");
- }
+ if (Configuration.DEBUG)
+ log.fine("EM does not end with 0xBC");
return false;
}
// 5. Let maskedDB be the leftmost emLen ? hLen ? 1 octets of EM, and let
- // H be the next hLen octets.
+ // H be the next hLen octets.
// 6. If the leftmost 8.emLen ? emBits bits of the leftmost octet in
- // maskedDB are not all equal to zero, output 'inconsistent' and stop.
+ // maskedDB are not all equal to zero, output 'inconsistent' and stop.
if ((EM[0] & (0xFF << (8 - (8 * emLen - emBits)))) != 0)
{
- if (DEBUG && debuglevel > 8)
- {
- debug("Leftmost 8emLen - emBits bits of EM are not 0s");
- }
+ if (Configuration.DEBUG)
+ log.fine("Leftmost 8emLen - emBits bits of EM are not 0s");
return false;
}
byte[] DB = new byte[emLen - hLen - 1];
@@ -309,56 +262,48 @@ public class EMSA_PSS implements Cloneable
// 8. Let DB = maskedDB XOR dbMask.
int i;
for (i = 0; i < DB.length; i++)
- {
- DB[i] = (byte) (DB[i] ^ dbMask[i]);
- }
+ DB[i] = (byte)(DB[i] ^ dbMask[i]);
// 9. Set the leftmost 8.emLen ? emBits bits of DB to zero.
DB[0] &= (0xFF >>> (8 * emLen - emBits));
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- debug("dbMask (decode): " + Util.toString(dbMask));
- debug("DB (decode): " + Util.toString(DB));
+ log.fine("dbMask (decode): " + Util.toString(dbMask));
+ log.fine("DB (decode): " + Util.toString(DB));
}
// 10. If the emLen -hLen -sLen -2 leftmost octets of DB are not zero or
- // if the octet at position emLen -hLen -sLen -1 is not equal to 0x01,
- // output 'inconsistent' and stop.
+ // if the octet at position emLen -hLen -sLen -1 is not equal to 0x01,
+ // output 'inconsistent' and stop.
// IMPORTANT (rsn): this is an error in the specs, the index of the 0x01
- // byte should be emLen -hLen -sLen -2 and not -1! authors have been
- // advised
+ // byte should be emLen -hLen -sLen -2 and not -1! authors have been advised
for (i = 0; i < (emLen - hLen - sLen - 2); i++)
{
if (DB[i] != 0)
{
- if (DEBUG && debuglevel > 8)
- {
- debug("DB[" + String.valueOf(i) + "] != 0x00");
- }
+ if (Configuration.DEBUG)
+ log.fine("DB[" + String.valueOf(i) + "] != 0x00");
return false;
}
}
if (DB[i] != 0x01)
{ // i == emLen -hLen -sLen -2
- if (DEBUG && debuglevel > 8)
- {
- debug("DB's byte at position (emLen -hLen -sLen -2); i.e. "
- + String.valueOf(i) + " is not 0x01");
- }
+ if (Configuration.DEBUG)
+ log.fine("DB's byte at position (emLen -hLen -sLen -2); i.e. "
+ + String.valueOf(i) + " is not 0x01");
return false;
}
// 11. Let salt be the last sLen octets of DB.
byte[] salt = new byte[sLen];
System.arraycopy(DB, DB.length - sLen, salt, 0, sLen);
// 12. Let M0 = 00 00 00 00 00 00 00 00 || mHash || salt;
- // M0 is an octet string of length 8 + hLen + sLen with eight initial
- // zero octets.
+ // M0 is an octet string of length 8 + hLen + sLen with eight initial
+ // zero octets.
// 13. Let H0 = Hash(M0), an octet string of length hLen.
byte[] H0;
synchronized (hash)
{
for (i = 0; i < 8; i++)
- {
- hash.update((byte) 0x00);
- }
+ hash.update((byte) 0x00);
+
hash.update(mHash, 0, hLen);
hash.update(salt, 0, sLen);
H0 = hash.digest();
@@ -367,34 +312,30 @@ public class EMSA_PSS implements Cloneable
return Arrays.equals(H, H0);
}
- // helper methods ----------------------------------------------------------
-
/**
- *
- *
*/
public class RSA
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final BigInteger ZERO = BigInteger.ZERO;
private static final BigInteger ONE = BigInteger.ONE;
@@ -81,37 +76,28 @@ public class RSA
/** Our default source of randomness. */
private static final PRNG prng = PRNG.getInstance();
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial private constructor to enforce Singleton pattern. */
private RSA()
{
super();
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Signature and verification methods --------------------------------------
-
/**
- *
- * Primitive specification and supporting documentation.
- * Jakob Jonsson and Burt Kaliski.
- * RSA Cryptography Specifications Version 2.1.
- * Jakob Jonsson and Burt Kaliski.
- * D. Boneh and D. Brumley.
+ * Primitive specification and supporting documentation.
+ * Jakob Jonsson and Burt Kaliski.
+ * RSA Cryptography Specifications Version 2.1.
+ * Jakob Jonsson and Burt Kaliski.
+ * D. Boneh and D. Brumley.0
and n - 1
, where n
is the RSA
- * modulus.
+ * 0
and n - 1
, where n
+ * is the RSA modulus.
* @return the signature representative, an integer between
- * 0
and n - 1
, where n
is the RSA
- * modulus.
+ * 0
and n - 1
, where n
+ * is the RSA modulus.
* @throws ClassCastException if K
is not an RSA one.
* @throws IllegalArgumentException if m
(the message
- * representative) is out of range.
+ * representative) is out of range.
*/
public static final BigInteger sign(final PrivateKey K, final BigInteger m)
{
@@ -121,27 +107,27 @@ public class RSA
}
catch (IllegalArgumentException x)
{
- throw new IllegalArgumentException(
- "message representative out of range");
+ throw new IllegalArgumentException("message representative out of range");
}
}
/**
- * 0
and n - 1
, where n
is the RSA
- * modulus.
+ * 0
and n - 1
, where n
+ * is the RSA modulus.
* @return a message representative: an integer between 0
- * and n - 1
, where n
is the RSA modulus.
+ * and n - 1
, where n
is the RSA
+ * modulus.
* @throws ClassCastException if K
is not an RSA one.
* @throws IllegalArgumentException if s
(the signature
- * representative) is out of range.
+ * representative) is out of range.
*/
public static final BigInteger verify(final PublicKey K, final BigInteger s)
{
@@ -151,25 +137,24 @@ public class RSA
}
catch (IllegalArgumentException x)
{
- throw new IllegalArgumentException(
- "signature representative out of range");
+ throw new IllegalArgumentException("signature representative out of range");
}
}
- // Encryption and decryption methods ---------------------------------------
-
/**
- * RSAEP
algorithm.RSAEP
algorithm.
+ *
* @param K the recipient's RSA public key.
* @param m the message representative as an MPI.
* @return the resulting MPI --an MPI between 0
and
- * n - 1
(n
being the public shared modulus)-- that
- * will eventually be padded with an appropriate framing/padding scheme.
+ * n - 1
(n
being the public shared
+ * modulus)-- that will eventually be padded with an appropriate
+ * framing/padding scheme.
* @throws ClassCastException if K
is not an RSA one.
* @throws IllegalArgumentException if m
, the message
- * representative is not between 0
and n - 1
- * (n
being the public shared modulus).
+ * representative is not between 0
and
+ * n - 1
(n
being the public shared
+ * modulus).
*/
public static final BigInteger encrypt(final PublicKey K, final BigInteger m)
{
@@ -179,22 +164,23 @@ public class RSA
}
catch (IllegalArgumentException x)
{
- throw new IllegalArgumentException(
- "message representative out of range");
+ throw new IllegalArgumentException("message representative out of range");
}
}
/**
- * RSADP
algorithm.RSADP
algorithm.
+ *
* @param K the recipient's RSA private key.
* @param c the ciphertext representative as an MPI.
* @return the message representative, an MPI between 0
and
- * n - 1
(n
being the shared public modulus).
+ * n - 1
(n
being the shared public
+ * modulus).
* @throws ClassCastException if K
is not an RSA one.
* @throws IllegalArgumentException if c
, the ciphertext
- * representative is not between 0
and n - 1
- * (n
being the shared public modulus).
+ * representative is not between 0
and
+ * n - 1
(n
being the shared public
+ * modulus).
*/
public static final BigInteger decrypt(final PrivateKey K, final BigInteger c)
{
@@ -204,22 +190,19 @@ public class RSA
}
catch (IllegalArgumentException x)
{
- throw new IllegalArgumentException(
- "ciphertext representative out of range");
+ throw new IllegalArgumentException("ciphertext representative out of range");
}
}
- // Conversion methods ------------------------------------------------------
-
/**
- * s
into an
- * octet sequence of length k
.s
into an
+ * octet sequence of length k
.
+ *
* @param s the multi-precision integer to convert.
* @param k the length of the output.
* @return the result of the transform.
* @exception IllegalArgumentException if the length in octets of meaningful
- * bytes of s
is greater than k
.
+ * bytes of s
is greater than k
.
*/
public static final byte[] I2OSP(final BigInteger s, final int k)
{
@@ -236,9 +219,7 @@ public class RSA
for (int i = 0; i < limit; i++)
{
if (result[i] != 0x00)
- {
- throw new IllegalArgumentException("integer too large");
- }
+ throw new IllegalArgumentException("integer too large");
}
final byte[] newResult = new byte[k];
System.arraycopy(result, limit, newResult, 0, k);
@@ -247,17 +228,13 @@ public class RSA
return result;
}
- // helper methods ----------------------------------------------------------
-
private static final BigInteger RSAEP(final RSAPublicKey K, final BigInteger m)
{
// 1. If the representative m is not between 0 and n - 1, output
- // "representative out of range" and stop.
+ // "representative out of range" and stop.
final BigInteger n = K.getModulus();
if (m.compareTo(ZERO) < 0 || m.compareTo(n.subtract(ONE)) > 0)
- {
- throw new IllegalArgumentException();
- }
+ throw new IllegalArgumentException();
// 2. Let c = m^e mod n.
final BigInteger e = K.getPublicExponent();
final BigInteger result = m.modPow(e, n);
@@ -268,16 +245,13 @@ public class RSA
private static final BigInteger RSADP(final RSAPrivateKey K, BigInteger c)
{
// 1. If the representative c is not between 0 and n - 1, output
- // "representative out of range" and stop.
+ // "representative out of range" and stop.
final BigInteger n = K.getModulus();
if (c.compareTo(ZERO) < 0 || c.compareTo(n.subtract(ONE)) > 0)
- {
- throw new IllegalArgumentException();
- }
-
+ throw new IllegalArgumentException();
// 2. The representative m is computed as follows.
BigInteger result;
- if (!(K instanceof RSAPrivateCrtKey))
+ if (! (K instanceof RSAPrivateCrtKey))
{
// a. If the first form (n, d) of K is used, let m = c^d mod n.
final BigInteger d = K.getPrivateExponent();
@@ -303,38 +277,32 @@ public class RSA
final BigInteger x = r.modPow(e, n).multiply(c).mod(n);
c = x;
}
-
// b. If the second form (p, q, dP, dQ, qInv) and (r_i, d_i, t_i)
- // of K is used, proceed as follows:
+ // of K is used, proceed as follows:
final BigInteger p = ((RSAPrivateCrtKey) K).getPrimeP();
final BigInteger q = ((RSAPrivateCrtKey) K).getPrimeQ();
final BigInteger dP = ((RSAPrivateCrtKey) K).getPrimeExponentP();
final BigInteger dQ = ((RSAPrivateCrtKey) K).getPrimeExponentQ();
final BigInteger qInv = ((RSAPrivateCrtKey) K).getCrtCoefficient();
-
- // i. Let m_1 = c^dP mod p and m_2 = c^dQ mod q.
+ // i. Let m_1 = c^dP mod p and m_2 = c^dQ mod q.
final BigInteger m_1 = c.modPow(dP, p);
final BigInteger m_2 = c.modPow(dQ, q);
- // ii. If u > 2, let m_i = c^(d_i) mod r_i, i = 3, ..., u.
- // iii. Let h = (m_1 - m_2) * qInv mod p.
+ // ii. If u > 2, let m_i = c^(d_i) mod r_i, i = 3, ..., u.
+ // iii. Let h = (m_1 - m_2) * qInv mod p.
final BigInteger h = m_1.subtract(m_2).multiply(qInv).mod(p);
- // iv. Let m = m_2 + q * h.
+ // iv. Let m = m_2 + q * h.
result = m_2.add(q.multiply(h));
-
- if (rsaBlinding)
- { // post-decryption
- result = result.multiply(r.modInverse(n)).mod(n);
- }
+ if (rsaBlinding) // post-decryption
+ result = result.multiply(r.modInverse(n)).mod(n);
}
-
// 3. Output m
return result;
}
/**
- * 8b
,
- * where b
is in the range [32..64]
.8b
,
+ * where b
is in the range [32..64]
.
+ *
* @return a random MPI whose length in bytes is between 32 and 64 inclusive.
*/
private static final BigInteger newR(final BigInteger N)
diff --git a/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java b/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java
index e64d30b..76460c0 100644
--- a/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java
+++ b/libjava/classpath/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java
@@ -51,35 +51,29 @@ import java.security.interfaces.RSAPublicKey;
import java.util.Arrays;
/**
- *
- *
*/
-public class RSAPKCS1V1_5Signature extends BaseSignature
+public class RSAPKCS1V1_5Signature
+ extends BaseSignature
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** The underlying EMSA-PKCS1-v1.5 instance for this object. */
private EMSA_PKCS1_V1_5 pkcs1;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Default 0-arguments constructor. Uses SHA-1 as the default hash.
*/
@@ -89,9 +83,9 @@ public class RSAPKCS1V1_5Signature extends BaseSignature
}
/**
- *
- * Primitive specification and supporting documentation.
- * Jakob Jonsson and Burt Kaliski.
- * RSA Cryptography Specifications Version 2.1.
- * Jakob Jonsson and Burt Kaliski.
+ * Primitive specification and supporting documentation.
+ * Jakob Jonsson and Burt Kaliski.
+ * RSA Cryptography Specifications Version 2.1.
+ * Jakob Jonsson and Burt Kaliski.
- *
*/
-public class RSAPSSSignature extends BaseSignature
+public class RSAPSSSignature
+ extends BaseSignature
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "rsa-pss";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 1;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
+ private static final Logger log = Logger.getLogger(RSAPSSSignature.class.getName());
/** The underlying EMSA-PSS instance for this object. */
private EMSA_PSS pss;
@@ -99,9 +83,6 @@ public class RSAPSSSignature extends BaseSignature
/** The desired length in octets of the EMSA-PSS salt. */
private int sLen;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Default 0-arguments constructor. Uses SHA-1 as the default hash and a
* 0-octet salt.
@@ -112,10 +93,9 @@ public class RSAPSSSignature extends BaseSignature
}
/**
- *
- * Primitive specification and supporting documentation.
- * Jakob Jonsson and Burt Kaliski.
+ * Primitive specification and supporting documentation.
+ * Jakob Jonsson and Burt Kaliski.s
to a signature
- * S
of length k
octets; i.e.
- * S = I2OSP(s, k)
, where k = CEILING(modBits/8)
.
- *
- * @param s the signature representative.
- * @param k the length of the output.
- * @return the signature as an octet sequence.
- * @exception IllegalArgumentException if the length in octets of meaningful
- * bytes of s
is greater than k
, implying that
- * s
is not less than the RSA modulus.
- */
- // private Object encodeSignature(BigInteger s, int k) {
- // if (DEBUG && debuglevel > 8) {
- // debug("s.bitLength(): "+String.valueOf(s.bitLength()));
- // debug("k: "+String.valueOf(k));
- // }
- // byte[] result = s.toByteArray();
- // if (DEBUG && debuglevel > 8) {
- // debug("s: "+Util.toString(result));
- // debug("s (bytes): "+String.valueOf(result.length));
- // }
- // if (result.length < k) {
- // byte[] newResult = new byte[k];
- // System.arraycopy(result, 0, newResult, k-result.length, result.length);
- // result = newResult;
- // } else if (result.length > k) { // leftmost extra bytes should all be 0
- // int limit = result.length - k;
- // for (int i = 0; i < limit; i++) {
- // if (result[i] != 0x00) {
- // throw new IllegalArgumentException("integer too large");
- // }
- // }
- // byte[] newResult = new byte[k];
- // System.arraycopy(result, limit, newResult, 0, k);
- // result = newResult;
- // }
- // return result;
- // }
- /**
- * Returns the output of a previously generated signature object as an octet
- * sequence.S
.
- */
- // private byte[] decodeSignature(Object signature) {
- // return (byte[]) signature;
- // }
}
diff --git a/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java b/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java
index 2be7916..b5e059c 100644
--- a/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java
+++ b/libjava/classpath/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java
@@ -44,53 +44,41 @@ import gnu.java.security.sig.ISignatureCodec;
import java.io.ByteArrayOutputStream;
/**
- *
- *
- *
+ *
* @param signature the signature to encode, consisting of the output of the
- * sign()
method of a {@link RSAPSSSignature} instance --a byte
- * array.
+ * sign()
method of a {@link RSAPSSSignature} instance
+ * --a byte array.
* @return the Raw format encoding of the designated signature.
* @exception IllegalArgumentException if the designated signature is not an
- * RSA-PSS one.
+ * RSA-PSS one.
*/
public byte[] encodeSignature(Object signature)
{
@@ -101,28 +89,23 @@ public class RSAPSSSignatureRawCodec implements ISignatureCodec
}
catch (Exception x)
{
- throw new IllegalArgumentException("key");
+ throw new IllegalArgumentException("signature");
}
-
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[0]);
baos.write(Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[1]);
baos.write(Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[2]);
baos.write(Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[3]);
-
// version
baos.write(0x01);
-
// signature bytes
int length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
baos.write((length >>> 8) & 0xFF);
baos.write(length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -133,25 +116,19 @@ public class RSAPSSSignatureRawCodec implements ISignatureCodec
|| k[1] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[1]
|| k[2] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[2]
|| k[3] != Registry.MAGIC_RAW_RSA_PSS_SIGNATURE[3])
- {
- throw new IllegalArgumentException("magic");
- }
-
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
-
+ throw new IllegalArgumentException("version");
int i = 5;
int l;
-
// signature bytes
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
byte[] result = new byte[l];
System.arraycopy(k, i, result, 0, l);
-
return result;
}
}
diff --git a/libjava/classpath/gnu/java/security/util/Base64.java b/libjava/classpath/gnu/java/security/util/Base64.java
index f9998c3..9b2ae12 100644
--- a/libjava/classpath/gnu/java/security/util/Base64.java
+++ b/libjava/classpath/gnu/java/security/util/Base64.java
@@ -38,8 +38,10 @@ exception statement from your version. */
package gnu.java.security.util;
-import java.io.PrintWriter;
+import gnu.java.security.Configuration;
+
import java.io.UnsupportedEncodingException;
+import java.util.logging.Logger;
/**
* Most of this implementation is from Robert Harder's public domain Base64
@@ -47,25 +49,7 @@ import java.io.UnsupportedEncodingException;
*/
public class Base64
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "Base64";
-
- private static final boolean DEBUG = true;
-
- private static final int debuglevel = 9;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
+ private static final Logger log = Logger.getLogger(Base64.class.getName());
/** Maximum line length (76) of Base64 output. */
private static final int MAX_LINE_LENGTH = 76;
@@ -81,79 +65,58 @@ public class Base64
private static final byte EQUALS_SIGN_ENC = -1; // equals sign in encoding
/** The 64 valid Base64 values. */
- private static final byte[] ALPHABET = { (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) '/' };
+ private static final byte[] ALPHABET = {
+ (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) '/'
+ };
/**
* Translates a Base64 value to either its 6-bit reconstruction value or a
* negative number indicating some other meaning.
*/
- private static final byte[] DECODABET = { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
- -5, -5, // Whitespace: Tab and Linefeed
- -9, -9, // Decimal 11 - 12
- -5, // Whitespace: Carriage Return
- -9, -9, -9, -9, -9, -9, -9, -9, -9,
- -9, -9, -9, -9, // Decimal 14 - 26
- -9, -9, -9, -9, -9, // Decimal 27 - 31
- -5, // Whitespace: Space
- -9, -9, -9, -9, -9, -9, -9, -9, -9,
- -9, // Decimal 33 - 42
- 62, // Plus sign at decimal 43
- -9, -9, -9, // Decimal 44 - 46
- 63, // Slash at decimal 47
- 52, 53, 54, 55, 56, 57, 58, 59, 60,
- 61, // Numbers zero through nine
- -9, -9, -9, // Decimal 58 - 60
- -1, // Equals sign at decimal 61
- -9, -9, -9, // Decimal 62 - 64
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
- 11, 12, 13, // Letters 'A' through 'N'
- 14, 15, 16, 17, 18, 19, 20, 21, 22,
- 23, 24, 25, // Letters 'O' through 'Z'
- -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
- 26, 27, 28, 29, 30, 31, 32, 33, 34,
- 35, 36, 37, 38, // Letters 'a' through 'm'
- 39, 40, 41, 42, 43, 44, 45, 46, 47,
- 48, 49, 50, 51, // Letters 'n' through 'z'
- -9, -9, -9, -9 // Decimal 123 - 126
+ private static final byte[] DECODABET = {
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
+ -5, -5, // Whitespace: Tab and Linefeed
+ -9, -9, // Decimal 11 - 12
+ -5, // Whitespace: Carriage Return
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
+ -9, -9, -9, -9, -9, // Decimal 27 - 31
+ -5, // Whitespace: Space
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
+ 62, // Plus sign at decimal 43
+ -9, -9, -9, // Decimal 44 - 46
+ 63, // Slash at decimal 47
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
+ -9, -9, -9, // Decimal 58 - 60
+ -1, // Equals sign at decimal 61
+ -9, -9, -9, // Decimal 62 - 64
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
+ -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
+ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
+ -9, -9, -9, -9 // Decimal 123 - 126
};
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial private ctor to enfore Singleton pattern. */
private Base64()
{
super();
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
* Encodes a byte array into Base64 notation. Equivalent to calling
* encode(source, 0, source.length)
.
- *
+ *
* @param src the data to convert.
*/
public static final String encode(final byte[] src)
@@ -163,7 +126,7 @@ public class Base64
/**
* Encodes a byte array into Base64 notation.
- *
+ *
* @param src the data to convert.
* @param off offset in array where conversion should begin.
* @param len length of data to convert.
@@ -176,7 +139,7 @@ public class Base64
final byte[] outBuff = new byte[len43 // Main 4:3
+ ((len % 3) > 0 ? 4 : 0) // Account for padding
+ (breakLines ? (len43 / MAX_LINE_LENGTH)
- : 0)]; // New lines
+ : 0)]; // New lines
int d = 0;
int e = 0;
final int len2 = len - 2;
@@ -192,13 +155,11 @@ public class Base64
lineLength = 0;
}
}
-
- if (d < len)
- { // padding needed
+ if (d < len) // padding needed
+ {
encode3to4(src, d + off, len - d, outBuff, e);
e += 4;
}
-
return new String(outBuff, 0, e);
}
@@ -255,31 +216,26 @@ public class Base64
} // end if: quartet built
} // end if: equals sign or better
}
- else
- {
- throw new IllegalArgumentException("Illegal BASE-64 character at #"
- + i + ": " + src[i]
- + "(decimal)");
- }
+ throw new IllegalArgumentException("Illegal BASE-64 character at #"
+ + i + ": " + src[i] + "(decimal)");
}
-
final byte[] result = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, result, 0, outBuffPosn);
return result;
}
/**
- * src
and writes
- * the resulting four Base64 bytes to dest
. The source and
+ * Encodes up to three bytes of the array src
and writes the
+ * resulting four Base64 bytes to dest
. The source and
* destination arrays can be manipulated anywhere along their length by
- * specifying sOffset
and dOffset
.sOffset
and dOffset
.
+ * sOffset + 3
for the src
array or
* dOffset + 4
for the dest
array. The actual
* number of significant bytes in the input array is given by
- * numBytes
.numBytes
.
+ *
* @param src the array to convert.
* @param sOffset the index where conversion begins.
* @param numBytes the number of significant bytes in your array.
@@ -302,25 +258,25 @@ public class Base64
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
- final int inBuff = (numBytes > 0 ? ((src[sOffset] << 24) >>> 8) : 0)
+ final int inBuff = (numBytes > 0 ? ((src[sOffset] << 24) >>> 8) : 0)
| (numBytes > 1 ? ((src[sOffset + 1] << 24) >>> 16) : 0)
| (numBytes > 2 ? ((src[sOffset + 2] << 24) >>> 24) : 0);
switch (numBytes)
{
case 3:
- dest[dOffset] = ALPHABET[(inBuff >>> 18)];
+ dest[dOffset ] = ALPHABET[(inBuff >>> 18)];
dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F];
- dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F];
- dest[dOffset + 3] = ALPHABET[(inBuff) & 0x3F];
+ dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F];
+ dest[dOffset + 3] = ALPHABET[(inBuff) & 0x3F];
break;
case 2:
- dest[dOffset] = ALPHABET[(inBuff >>> 18)];
+ dest[dOffset ] = ALPHABET[(inBuff >>> 18)];
dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F];
- dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F];
+ dest[dOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3F];
dest[dOffset + 3] = EQUALS_SIGN;
break;
case 1:
- dest[dOffset] = ALPHABET[(inBuff >>> 18)];
+ dest[dOffset ] = ALPHABET[(inBuff >>> 18)];
dest[dOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3F];
dest[dOffset + 2] = EQUALS_SIGN;
dest[dOffset + 3] = EQUALS_SIGN;
@@ -330,19 +286,18 @@ public class Base64
}
/**
- * src
and writes the
- * resulting bytes (up to three of them) to dest
.sOffset
and dOffset
.
- * sOffset + 4
for the src
array or
+ * Decodes four bytes from array src
and writes the resulting
+ * bytes (up to three of them) to dest
.
+ * sOffset
and dOffset
.
+ * sOffset + 4
for the src
array or
* dOffset + 3
for the dest
array. This method
* returns the actual number of bytes that were converted from the Base64
- * encoding.destroy()
.
- *
- * destroy()
.
+ * delay + System.currentTimeMillis()
is negative.
+ * delay + System.currentTimeMillis()
is negative.
*/
protected ExpirableObject(final long delay)
{
@@ -107,14 +100,11 @@ public abstract class ExpirableObject implements Destroyable
EXPIRER.schedule(destroyer, delay);
}
- // Instance methods.
- // -------------------------------------------------------------------------
-
/**
- * Destroys this object. This method calls {@link doDestroy}, then, if
- * no exception is thrown, cancels the task that would destroy this object
- * when the timeout is reached.
- *
+ * Destroys this object. This method calls {@link #doDestroy}, then, if no
+ * exception is thrown, cancels the task that would destroy this object when
+ * the timeout is reached.
+ *
* @throws DestroyFailedException If this operation fails.
*/
public final void destroy() throws DestroyFailedException
@@ -126,42 +116,30 @@ public abstract class ExpirableObject implements Destroyable
/**
* Subclasses must implement this method instead of the {@link
* Destroyable#destroy()} method.
- *
+ *
* @throws DestroyFailedException If this operation fails.
*/
protected abstract void doDestroy() throws DestroyFailedException;
- // Inner classes.
- // -------------------------------------------------------------------------
-
/**
* The task that destroys the target when the timeout elapses.
*/
- private final class Destroyer extends TimerTask
+ private final class Destroyer
+ extends TimerTask
{
-
- // Fields.
- // -----------------------------------------------------------------------
-
private final ExpirableObject target;
- // Constructor.
- // -----------------------------------------------------------------------
-
Destroyer(final ExpirableObject target)
{
super();
this.target = target;
}
- // Instance methods.
- // -----------------------------------------------------------------------
-
public void run()
{
try
{
- if (!target.isDestroyed())
+ if (! target.isDestroyed())
target.doDestroy();
}
catch (DestroyFailedException dfe)
diff --git a/libjava/classpath/gnu/java/security/util/IntegerUtil.java b/libjava/classpath/gnu/java/security/util/IntegerUtil.java
new file mode 100644
index 0000000..f071308
--- /dev/null
+++ b/libjava/classpath/gnu/java/security/util/IntegerUtil.java
@@ -0,0 +1,109 @@
+/* IntegerUtil.java -- JDK 5 Integer methods with 1.4 API
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.security.util;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Utility class which offers Integer related methods found in RI's version 5
+ * but written with RI's 1.4 API.
+ */
+public abstract class IntegerUtil
+{
+ /** Maximum size of our cache of constructed Integers. */
+ private static final int CACHE_SIZE = 100;
+ /** LRU (Least Recently Used) cache, of the last accessed 100 Integers. */
+ private static final Map cache = new LinkedHashMap(CACHE_SIZE + 1, 0.75F, true)
+ {
+ public boolean removeEldestEntry(Map.Entry entry)
+ {
+ return size() > CACHE_SIZE;
+ }
+ };
+
+ /** Trivial private constructor to enforce Singleton usage. */
+ private IntegerUtil()
+ {
+ super();
+ }
+
+ /**
+ * Similar to {@link Integer#valueOf(String)} except it caches the result in
+ * a local LRU cache of 100 elements, organized by access order.
+ * valueOf(int)
method found in {@link Integer} of
+ * the RI's version 1.5 using a local LRU cache of 100 elements, organized by
+ * access order.
+ * buffer
with random data
* generated by the underlying delegate.
*
- * @param buffer
- * the place holder of random bytes generated by the underlying
+ * @param buffer the place holder of random bytes generated by the underlying
* delegate. On output, the contents of buffer
are
* replaced with pseudo-random data, iff the buffer
* size is not zero.
diff --git a/libjava/classpath/gnu/java/security/util/Prime2.java b/libjava/classpath/gnu/java/security/util/Prime2.java
deleted file mode 100644
index 6e46f5f..0000000
--- a/libjava/classpath/gnu/java/security/util/Prime2.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/* Prime2.java --
- Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
-
-This file is a part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2 of the License, or (at
-your option) any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; if not, write to the Free Software
-Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
-USA
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package gnu.java.security.util;
-
-import java.io.PrintWriter;
-import java.lang.ref.WeakReference;
-import java.math.BigInteger;
-import java.util.Map;
-import java.util.WeakHashMap;
-
-/**
- * true
if at least one small prime, among the first
- * 1000 ones, was found to divide the designated number. Retuens false
- * otherwise.true
if at least one small prime was found to divide
- * the designated number.
- */
- public static boolean hasSmallPrimeDivisor(BigInteger w)
- {
- BigInteger prime;
- for (int i = 0; i < SMALL_PRIME_COUNT; i++)
- {
- prime = SMALL_PRIME[i];
- if (w.mod(prime).equals(ZERO))
- {
- if (DEBUG && debuglevel > 4)
- {
- debug(prime.toString(16) + " | " + w.toString(16) + "...");
- }
- return true;
- }
- }
- if (DEBUG && debuglevel > 4)
- {
- debug(w.toString(16) + " has no small prime divisors...");
- }
- return false;
- }
-
- /**
- * bn == 1 mod 8
and 2
is a quartic residue, i.e.
- * bn
is of the form a^2 + (8*b)^2
.) The precise
- * series of tricks used here is not documented anywhere, so here's an
- * explanation. Euler's criterion states that if p
is prime
- * then a^((p-1)/2)
is congruent to Jacobi(a,p)
,
- * modulo p
. Jacobi(a, p)
is a function which is
- * +1
if a is a square modulo p
, and -1
- * if it is not. For a = 2
, this is particularly simple. It's
- * +1
if p == +/-1 (mod 8)
, and -1
if
- * m == +/-3 (mod 8)
. If p == 3 (mod 4)
, then all
- * a strong test does is compute 2^((p-1)/2)
. and see if it's
- * +1
or -1
. (Euler's criterion says which
- * it should be.) If p == 5 (mod 8)
, then 2^((p-1)/2)
- * is -1
, so the initial step in a strong test, looking at
- * 2^((p-1)/4)
, is wasted --you're not going to find a
- * +/-1
before then if it is prime, and it shouldn't
- * have either of those values if it isn't. So don't bother.p == 1 (mod 8)
. In this case, we
- * expect 2^((p-1)/2) == 1 (mod p)
, so we expect that the
- * square root of this, 2^((p-1)/4)
, will be +/-1 (mod p)
- *
. Evaluating this saves us a modular squaring 1/4 of the time. If
- * it's -1
, a strong pseudoprimality test would call p
- * prime as well. Only if the result is +1
, indicating that
- * 2
is not only a quadratic residue, but a quartic one as well,
- * does a strong pseudoprimality test verify more things than this test does.
- * Good enough.2^((p-1)/8)
- * if there was a cheap way to determine if 2
were expected to
- * be a quartic residue or not. Dirichlet proved that 2
is a
- * quadratic residue iff p
is of the form a^2 + (8*b^2)
.
- * All primes == 1 (mod 4)
can be expressed as a^2 +
- * (2*b)^2
, but I see no cheap way to evaluate this condition."true
iff the designated number passes Euler criterion
- * as implemented by Colin Plumb in his bnlib version 1.1.
- */
- public static boolean passEulerCriterion(final BigInteger bn)
- {
- BigInteger bn_minus_one = bn.subtract(ONE);
- BigInteger e = bn_minus_one;
- // l is the 3 least-significant bits of e
- int l = e.and(BigInteger.valueOf(7L)).intValue();
- int j = 1; // Where to start in prime array for strong prime tests
- BigInteger a;
- int k;
-
- if (l != 0)
- {
- e = e.shiftRight(1);
- a = TWO.modPow(e, bn);
- if (l == 6) // bn == 7 mod 8, expect +1
- {
- if (a.bitLength() != 1)
- {
- debugBI("Fails Euler criterion #1", bn);
- return false; // Not prime
- }
- k = 1;
- }
- else // bn == 3 or 5 mod 8, expect -1 == bn-1
- {
- a = a.add(ONE);
- if (a.compareTo(bn) != 0)
- {
- debugBI("Fails Euler criterion #2", bn);
- return false; // Not prime
- }
- k = 1;
- if ((l & 4) != 0) // bn == 5 mod 8, make odd for strong tests
- {
- e = e.shiftRight(1);
- k = 2;
- }
- }
- }
- else // bn == 1 mod 8, expect 2^((bn-1)/4) == +/-1 mod bn
- {
- e = e.shiftRight(2);
- a = TWO.modPow(e, bn);
- if (a.bitLength() == 1)
- j = 0; // Re-do strong prime test to base 2
- else
- {
- a = a.add(ONE);
- if (a.compareTo(bn) != 0)
- {
- debugBI("Fails Euler criterion #3", bn);
- return false; // Not prime
- }
- }
- // bnMakeOdd(n) = d * 2^s. Replaces n with d and returns s.
- k = e.getLowestSetBit();
- e = e.shiftRight(k);
- k += 2;
- }
- // It's prime! Now go on to confirmation tests
-
- // Now, e = (bn-1)/2^k is odd. k >= 1, and has a given value with
- // probability 2^-k, so its expected value is 2. j = 1 in the usual case
- // when the previous test was as good as a strong prime test, but 1/8 of
- // the time, j = 0 because the strong prime test to the base 2 needs to
- // be re-done.
- for (int i = j; i < 7; i++) // try only the first 7 primes
- {
- a = SMALL_PRIME[i];
- a = a.modPow(e, bn);
- if (a.bitLength() == 1)
- continue; // Passed this test
-
- l = k;
- while (true)
- {
-// a = a.add(ONE);
-// if (a.compareTo(w) == 0) { // Was result bn-1?
- if (a.compareTo(bn_minus_one) == 0) // Was result bn-1?
- break; // Prime
-
- if (--l == 0) // Reached end, not -1? luck?
- {
- debugBI("Fails Euler criterion #4", bn);
- return false; // Failed, not prime
- }
- // This portion is executed, on average, once
-// a = a.subtract(ONE); // Put a back where it was
- a = a.modPow(TWO, bn);
- if (a.bitLength() == 1)
- {
- debugBI("Fails Euler criterion #5", bn);
- return false; // Failed, not prime
- }
- }
- // It worked (to the base primes[i])
- }
- debugBI("Passes Euler criterion", bn);
- return true;
- }
-
- public static boolean isProbablePrime(BigInteger w)
- {
- return isProbablePrime(w, DEFAULT_CERTAINTY);
- }
-
- /**
- * Wrapper around {@link BigInteger#isProbablePrime(int)} with few pre-checks.
- *
- * @param w the integer to test.
- * @param certainty the certainty with which to compute the test.
- */
- public static boolean isProbablePrime(BigInteger w, int certainty)
- {
- // Nonnumbers are not prime.
- if (w == null)
- return false;
-
- // eliminate trivial cases when w == 0 or 1
- if (w.equals(ZERO) || w.equals(ONE))
- return false;
-
- // Test if w is a known small prime.
- for (int i = 0; i < SMALL_PRIME_COUNT; i++)
- if (w.equals(SMALL_PRIME[i]))
- {
- if (DEBUG && debuglevel > 4)
- debug(w.toString(16) + " is a small prime");
- return true;
- }
-
- // Check if it's already a known prime
- WeakReference obj = (WeakReference) knownPrimes.get(w);
- if (obj != null && w.equals(obj.get()))
- {
- if (DEBUG && debuglevel > 4)
- debug("found in known primes");
- return true;
- }
-
- // trial division with first 1000 primes
- if (hasSmallPrimeDivisor(w))
- {
- if (DEBUG && debuglevel > 4)
- debug(w.toString(16) + " has a small prime divisor. Rejected...");
- return false;
- }
-
-// Euler's criterion.
-// if (passEulerCriterion(w)) {
-// if (DEBUG && debuglevel > 4) {
-// debug(w.toString(16)+" passes Euler's criterion...");
-// }
-// } else {
-// if (DEBUG && debuglevel > 4) {
-// debug(w.toString(16)+" fails Euler's criterion. Rejected...");
-// }
-// return false;
-// }
-//
-// if (DEBUG && debuglevel > 4)
-// {
-// debug(w.toString(16) + " is probable prime. Accepted...");
-// }
-
- boolean result = w.isProbablePrime(certainty);
- if (result && certainty > 0) // store it in the known primes weak hash-map
- knownPrimes.put(w, new WeakReference(w));
-
- return result;
- }
-
- // helper methods -----------------------------------------------------------
-
- private static final void debugBI(String msg, BigInteger bn)
- {
- if (DEBUG && debuglevel > 4)
- debug("*** " + msg + ": 0x" + bn.toString(16));
- }
-}
diff --git a/libjava/classpath/gnu/java/security/util/Sequence.java b/libjava/classpath/gnu/java/security/util/Sequence.java
index 5edc794..5e3a64e 100644
--- a/libjava/classpath/gnu/java/security/util/Sequence.java
+++ b/libjava/classpath/gnu/java/security/util/Sequence.java
@@ -44,24 +44,18 @@ import java.util.LinkedList;
/**
* A monotonic sequence of integers in the finite field 232.
*/
-public final class Sequence extends AbstractList
+public final class Sequence
+ extends AbstractList
{
-
- // Field.
- // ------------------------------------------------------------------------
-
private final Integer[] sequence;
- // Constructor.
- // ------------------------------------------------------------------------
-
/**
- * Create a sequence of integers from 0 to end, with an increment
- * of 1. If end is less than 0, then the sequence will wrap around
- * through all positive integers then negative integers until the end
- * value is reached. Naturally, this will result in an enormous object,
- * so don't do this.
- *
+ * Create a sequence of integers from 0 to end, with an increment of
+ * 1. If end is less than 0, then the sequence will wrap around
+ * through all positive integers then negative integers until the end value is
+ * reached. Naturally, this will result in an enormous object, so don't do
+ * this.
+ *
* @param end The ending value.
*/
public Sequence(int end)
@@ -71,10 +65,10 @@ public final class Sequence extends AbstractList
/**
* Create a sequence of integers from start to end, with an
- * increment of 1. If end is less than start, then the sequence
- * will wrap around until the end value is reached. Naturally, this will
- * result in an enormous object, so don't do this.
- *
+ * increment of 1. If end is less than start, then the
+ * sequence will wrap around until the end value is reached. Naturally, this
+ * will result in an enormous object, so don't do this.
+ *
* @param start The starting value.
* @param end The ending value.
*/
@@ -88,13 +82,13 @@ public final class Sequence extends AbstractList
* increment of span. If end is less than start, then
* the sequence will wrap around until the end value is reached. Naturally,
* this will result in an enormous object, so don't do this.
- *
- *
- * toString(ba, 0, ba.length);
+ * toString(ba, 0, ba.length);
*
- *
+ *
* @param ba the byte array to convert.
- * @return a string of hexadecimal characters (two for each byte)
- * representing the designated input byte array.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte array.
*/
public static String toString(byte[] ba)
{
@@ -89,17 +79,17 @@ public class Util
}
/**
- * offset
and consisting of length
bytes. Each byte
- * is converted to 2 hex symbols; zero(es) included.offset
and consisting of length
bytes. Each
+ * byte is converted to 2 hex symbols; zero(es) included.
+ *
* @param ba the byte array to convert.
* @param offset the index from which to start considering the bytes to
- * convert.
+ * convert.
* @param length the count of bytes, starting from the designated offset to
- * convert.
- * @return a string of hexadecimal characters (two for each byte)
- * representing the designated input byte sub-array.
+ * convert.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte sub-array.
*/
public static final String toString(byte[] ba, int offset, int length)
{
@@ -108,26 +98,24 @@ public class Util
{
k = ba[offset + i++];
buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F];
- buf[j++] = HEX_DIGITS[k & 0x0F];
+ buf[j++] = HEX_DIGITS[ k & 0x0F];
}
return new String(buf);
}
/**
- *
- * toReversedString(ba, 0, ba.length);
+ * toReversedString(ba, 0, ba.length);
*
- *
+ *
* @param ba the byte array to convert.
- * @return a string of hexadecimal characters (two for each byte)
- * representing the designated input byte array.
+ * @return a string of hexadecimal characters (two for each byte) representing
+ * the designated input byte array.
*/
public static String toReversedString(byte[] ba)
{
@@ -135,20 +123,20 @@ public class Util
}
/**
- * offset
and consisting of length
bytes. Each byte
- * is converted to 2 hex symbols; zero(es) included.offset
and consisting of length
bytes. Each
+ * byte is converted to 2 hex symbols; zero(es) included.
+ * 0
to 15
corresponding
- * to the designated hexadecimal digit.0
to 15
corresponding
+ * to the designated hexadecimal digit.
+ *
* @param c a hexadecimal ASCII symbol.
*/
public static int fromDigit(char c)
{
if (c >= '0' && c <= '9')
- {
- return c - '0';
- }
+ return c - '0';
else if (c >= 'A' && c <= 'F')
- {
- return c - 'A' + 10;
- }
+ return c - 'A' + 10;
else if (c >= 'a' && c <= 'f')
- {
- return c - 'a' + 10;
- }
+ return c - 'a' + 10;
else
throw new IllegalArgumentException("Invalid hexadecimal digit: " + c);
}
/**
- * n
.n
.
+ *
* @param n the unsigned integer to convert.
* @return a hexadecimal string 8-character long.
*/
@@ -253,8 +233,8 @@ public class Util
}
/**
- * n
.n
.
+ *
* @param n the unsigned long to convert.
* @return a hexadecimal string 16-character long.
*/
@@ -287,18 +267,18 @@ public class Util
char[] b = new char[16];
for (int i = 15; i >= 0; i--)
{
- b[i] = HEX_DIGITS[(int) (n & 0x0FL)];
+ b[i] = HEX_DIGITS[(int)(n & 0x0FL)];
n >>>= 4;
}
return new String(b);
}
/**
- * toString()
method except that the Unicode
+ * Similar to the toString()
method except that the Unicode
* escape character is inserted before every pair of bytes. Useful to
* externalise byte arrays that will be constructed later from such strings;
- * eg. s-box values.toString()
method except that the Unicode
+ * Similar to the toString()
method except that the Unicode
* escape character is inserted before every pair of bytes. Useful to
* externalise byte arrays that will be constructed later from such strings;
- * eg. s-box values.toString()
method except that the Unicode
+ * Similar to the toString()
method except that the Unicode
* escape character is inserted before every pair of bytes. Useful to
* externalise integer arrays that will be constructed later from such
- * strings; eg. s-box values.m
is prepended to the start of each
- * line.offset
and length
are omitted, the whole
+ * line.
+ * offset
and length
are omitted, the whole
* array is used. If m
is omitted, nothing is prepended to each
- * line.n
.n
.
+ *
* @param n the byte value to convert.
* @return a string of 2 hex characters representing the input.
*/
@@ -481,15 +442,15 @@ public class Util
}
/**
- * str
.
- * @throws NumberFormatException if str
is null
, or
- * str
contains an illegal Base-64 character.
+ * @throws NumberFormatException if str
is null
,
+ * or str
contains an illegal Base-64 character.
* @see #toBase64(byte[])
*/
public static final byte[] fromBase64(String str)
{
int len = str.length();
if (len == 0)
- {
- throw new NumberFormatException("Empty string");
- }
+ throw new NumberFormatException("Empty string");
byte[] a = new byte[len + 1];
int i, j;
for (i = 0; i < len; i++)
- {
- try
- {
- a[i] = (byte) BASE64_CHARS.indexOf(str.charAt(i));
- }
- catch (ArrayIndexOutOfBoundsException x)
- {
- throw new NumberFormatException("Illegal character at #" + i);
- }
- }
+ try
+ {
+ a[i] = (byte) BASE64_CHARS.indexOf(str.charAt(i));
+ }
+ catch (ArrayIndexOutOfBoundsException x)
+ {
+ throw new NumberFormatException("Illegal character at #" + i);
+ }
i = len - 1;
j = len;
try
@@ -601,42 +554,31 @@ public class Util
{
a[j] = a[i];
if (--i < 0)
- {
- break;
- }
+ break;
a[j] |= (a[i] & 0x03) << 6;
j--;
- a[j] = (byte) ((a[i] & 0x3C) >>> 2);
+ a[j] = (byte)((a[i] & 0x3C) >>> 2);
if (--i < 0)
- {
- break;
- }
+ break;
a[j] |= (a[i] & 0x0F) << 4;
j--;
- a[j] = (byte) ((a[i] & 0x30) >>> 4);
+ a[j] = (byte)((a[i] & 0x30) >>> 4);
if (--i < 0)
- {
- break;
- }
+ break;
a[j] |= (a[i] << 2);
j--;
a[j] = 0;
if (--i < 0)
- {
- break;
- }
+ break;
}
}
catch (Exception ignored)
{
}
-
try
{ // ignore leading 0-bytes
while (a[j] == 0)
- {
- j++;
- }
+ j++;
}
catch (Exception x)
{
@@ -650,36 +592,31 @@ public class Util
// BigInteger utilities ----------------------------------------------------
/**
- * "/system"
directory of GConf for the current user, while User
+ * Root is "/apps/java"
. These defaults can be modified by
+ * defining two system properties:
+ *
+ * User Root:
+ *
+ *
+ *
+ * gnu.java.util.prefs.gconf.user_root
+ *
+ *
+ *
+ *
+ * and System Root:
+ *
+ *
+ *
+ * gnu.java.util.prefs.gconf.system_root
+ *
+ *
+ *
+ *
+ * @author Mario Torre isUser
is true it will
+ * be user node otherwise it will be a system node.
+ */
+ public GConfBasedPreferences(boolean isUser)
+ {
+ this(null, "", isUser);
+ }
+
+ /**
+ * Creates a new preference node given a parent node and a name, which has to
+ * be relative to its parent. When isUser
is true it will be user
+ * node otherwise it will be a system node.
+ *
+ * @param parent The parent node of this newly created node.
+ * @param name A name relative to the parent node.
+ * @param isUser Set to true
initializes this node to be
+ * a user node, false
initialize it to be a system node.
+ */
+ public GConfBasedPreferences(AbstractPreferences parent, String name,
+ boolean isUser)
+ {
+ super(parent, name);
+ this.isUser = isUser;
+
+ // stores the fully qualified name of this node
+ String absolutePath = this.absolutePath();
+ if (absolutePath != null && absolutePath.endsWith("/"))
+ {
+ absolutePath = absolutePath.substring(0, absolutePath.length() - 1);
+ }
+
+ this.node = this.getRealRoot(isUser) + absolutePath;
+
+ boolean nodeExist = backend.nodeExist(this.node);
+
+ this.newNode = !nodeExist;
+ backend.startWatchingNode(this.node);
+ }
+
+ /**
+ * Returns a child node with the given name.
+ * If the child node does not exists, it will be created.
+ *
+ * @param name The name of the requested node.
+ * @return A new reference to the node, creating the node if it is necessary.
+ */
+ protected AbstractPreferences childSpi(String name)
+ {
+ // we don't check anything here, if the node is a new node this will be
+ // detected in the constructor, so we simply return a new reference to
+ // the requested node.
+ return new GConfBasedPreferences(this, name, this.isUser);
+ }
+
+ /**
+ * Returns an array of names of the children of this preference node.
+ * If the current node does not have children, the returned array will be
+ * of size
0 (that is, not null
).
+ *
+ * @return A String
array of names of children of the current
+ * node.
+ * @throws BackingStoreException if this operation cannot be completed.
+ */
+ protected String[] childrenNamesSpi() throws BackingStoreException
+ {
+ List nodeList = backend.getChildrenNodes(this.node);
+ String[] nodes = new String[nodeList.size()];
+ nodeList.toArray(nodes);
+
+ return nodes;
+ }
+
+ /**
+ * Suggest a flush to the backend. Actually, this is only a suggestion as
+ * GConf handles this for us asynchronously. More over, both sync and flush
+ * have the same meaning in this class, so calling sync has exactly the same
+ * effect.
+ *
+ * @see #sync
+ * @throws BackingStoreException if this operation cannot be completed.
+ */
+ public void flush() throws BackingStoreException
+ {
+ backend.suggestSync();
+ }
+
+ /**
+ * Request a flush.
+ *
+ * @see #flush
+ * @throws BackingStoreException if this operation cannot be completed.
+ */
+ protected void flushSpi() throws BackingStoreException
+ {
+ this.flush();
+ }
+
+ /**
+ * Returns all of the key in this preference node.
+ * If the current node does not have preferences, the returned array will be
+ * of size zero.
+ *
+ * @return A String
array of keys stored under the current
+ * node.
+ * @throws BackingStoreException if this operation cannot be completed.
+ */
+ protected String[] keysSpi() throws BackingStoreException
+ {
+ List keyList = backend.getKeys(this.node);
+ String[] keys = new String[keyList.size()];
+ keyList.toArray(keys);
+
+ return keys;
+ }
+
+ /**
+ * Does a recursive postorder traversal of the preference tree, starting from
+ * the given directory invalidating every preference found in the node.
+ *
+ * @param directory The name of the starting directory (node)
+ */
+ private void postorderRemove(String directory)
+ {
+ try
+ {
+ // gets the listing of directories in this node
+ List dirs = backend.getChildrenNodes(directory);
+
+ if (dirs.size() != 0)
+ {
+ String currentDir = null;
+
+ for (Iterator itr = dirs.iterator(); itr.hasNext();)
+ {
+ currentDir = (String) itr.next();
+
+ // recursive search inside this directory
+ postorderRemove(currentDir);
+ }
+ }
+
+ // remove all the keys associated to this directory
+ List entries = backend.getKeys(directory);
+
+ if (entries.size() != 0)
+ {
+ String key = null;
+
+ for (Iterator keys = entries.iterator(); keys.hasNext();)
+ {
+ key = (String) keys.next();
+ this.removeSpi(key);
+ }
+ }
+ }
+ catch (BackingStoreException ex)
+ {
+ /* ignore */
+ }
+ }
+
+ /**
+ * Stores the given key-value pair into this preference node.
+ *
+ * @param key The key of this preference.
+ * @param value The value of this preference.
+ */
+ protected void putSpi(String key, String value)
+ {
+ backend.setString(this.getGConfKey(key), value);
+ }
+
+ /**
+ * Removes this preference node, including all its children.
+ * Also removes the preferences associated.
+ */
+ protected void removeNodeSpi() throws BackingStoreException
+ {
+ this.postorderRemove(this.node);
+ this.flush();
+ }
+
+ /**
+ * Removes the given key from this preference node.
+ * If the key does not exist, no operation is performed.
+ *
+ * @param key The key to remove.
+ */
+ protected void removeSpi(String key)
+ {
+ backend.unset(this.getGConfKey(key));
+ }
+
+ /**
+ * Suggest a sync to the backend. Actually, this is only a suggestion as GConf
+ * handles this for us asynchronously. More over, both sync and flush have the
+ * same meaning in this class, so calling flush has exactly the same effect.
+ *
+ * @see #flush
+ * @throws BackingStoreException if this operation cannot be completed due to
+ * a failure in the backing store, or inability to communicate with
+ * it.
+ */
+ public void sync() throws BackingStoreException
+ {
+ this.flush();
+ }
+
+ /**
+ * Request a sync.
+ *
+ * @see #sync
+ * @throws BackingStoreException if this operation cannot be completed due to
+ * a failure in the backing store, or inability to communicate with
+ * it.
+ */
+ protected void syncSpi() throws BackingStoreException
+ {
+ this.sync();
+ }
+
+ /**
+ * Returns the value of the given key.
+ * If the keys does not have a value, or there is an error in the backing
+ * store, null
is returned instead.
+ *
+ * @param key The key to retrieve.
+ * @return The value associated with the given key.
+ */
+ protected String getSpi(String key)
+ {
+ return backend.getKey(this.getGConfKey(key));
+ }
+
+ /**
+ * Returns true
if this preference node is a user node,
+ * false
if is a system preference node.
+ *
+ * @return true
if this preference node is a user node,
+ * false
if is a system preference node.
+ */
+ public boolean isUserNode()
+ {
+ return this.isUser;
+ }
+
+ /*
+ * PRIVATE METHODS
+ */
+
+ /**
+ * Builds a GConf key string suitable for operations on the backend.
+ *
+ * @param key The key to convert into a valid GConf key.
+ * @return A valid Gconf key.
+ */
+ private String getGConfKey(String key)
+ {
+ String nodeName = "";
+
+ if (this.node.endsWith("/"))
+ {
+ nodeName = this.node + key;
+ }
+ else
+ {
+ nodeName = this.node + "/" + key;
+ }
+
+ return nodeName;
+ }
+
+ /**
+ * Builds the root node to use for this preference.
+ *
+ * @param isUser Defines if this node is a user (true
) or system
+ * (false
) node.
+ * @return The real root of this preference tree.
+ */
+ private String getRealRoot(boolean isUser)
+ {
+ // not sure about this, we should have already these permissions...
+ SecurityManager security = System.getSecurityManager();
+
+ if (security != null)
+ {
+ security.checkPermission(PERMISSION);
+ }
+
+ String root = null;
+
+ if (isUser)
+ {
+ root = System.getProperty("gnu.java.util.prefs.gconf.user_root",
+ DEFAULT_USER_ROOT);
+ }
+ else
+ {
+ root = System.getProperty("gnu.java.util.prefs.gconf.system_root",
+ DEFAULT_SYSTEM_ROOT);
+ }
+
+ return root;
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/prefs/gconf/GConfNativePeer.java b/libjava/classpath/gnu/java/util/prefs/gconf/GConfNativePeer.java
new file mode 100644
index 0000000..f1cb627
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/prefs/gconf/GConfNativePeer.java
@@ -0,0 +1,298 @@
+/* GConfNativePeer.java -- GConf based preference peer for native methods
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+ This file is part of GNU Classpath.
+
+ GNU Classpath is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ GNU Classpath is distributed in the hope that it will be useful, but
+ WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GNU Classpath; see the file COPYING. If not, write to the
+ Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+ 02110-1301 USA.
+
+ Linking this library statically or dynamically with other modules is
+ making a combined work based on this library. Thus, the terms and
+ conditions of the GNU General Public License cover the whole
+ combination.
+
+ As a special exception, the copyright holders of this library give you
+ permission to link this library with independent modules to produce an
+ executable, regardless of the license terms of these independent
+ modules, and to copy and distribute the resulting executable under
+ terms of your choice, provided that you also meet, for each linked
+ independent module, the terms and conditions of the license of that
+ module. An independent module is a module which is not derived from
+ or based on this library. If you modify this library, you may extend
+ this exception to your version of the library, but you are not
+ obligated to do so. If you do not wish to do so, delete this
+ exception statement from your version. */
+
+
+package gnu.java.util.prefs.gconf;
+
+import java.util.List;
+import java.util.prefs.BackingStoreException;
+
+/**
+ * Native peer for GConf based preference backend.
+ *
+ * @author Mario Torre node
exists in theGConf database.
+ * Returns true
or false
.
+ *
+ * @param node the node to check.
+ */
+ public boolean nodeExist(String node)
+ {
+ return gconf_client_dir_exists(node);
+ }
+
+ /**
+ * Add the node node
to the list of nodes the GConf will watch.
+ * An event is raised everytime this node is changed. You can add a node
+ * multiple times.
+ *
+ * @param node the node to track.
+ */
+ public void startWatchingNode(String node)
+ {
+ gconf_client_add_dir(node);
+ }
+
+ /**
+ * Remove the node node
to the list of nodes the GConf is
+ * watching. Note that if a node has been added multiple times, you must
+ * remove it the same number of times before the remove takes effect.
+ *
+ * @param node the node you don't want to track anymore.
+ */
+ public void stopWatchingNode(String node)
+ {
+ gconf_client_remove_dir(node);
+ }
+
+ /**
+ * Change the value of key to val. Automatically creates the key if it didn't
+ * exist before (ie it was unset or it only had a default value).
+ * Key names must be valid GConf key names, that is, there can be more
+ * restrictions than for normal Preference Backend.
+ *
+ * @param key the key to alter (or add).
+ * @param value the new value for this key.
+ * @return true if the key was updated, false otherwise.
+ */
+ public boolean setString(String key, String value)
+ {
+ return gconf_client_set_string(key, value);
+ }
+
+ /**
+ * Unsets the value of key; if key is already unset, has no effect. Depending
+ * on the GConf daemon, unsetting a key may have the side effect to remove it
+ * completely form the database.
+ *
+ * @param key the key to unset.
+ * @return true on success, false if the key was not updated.
+ */
+ public boolean unset(String key)
+ {
+ return gconf_client_unset(key);
+ }
+
+ /**
+ * Gets the value of a configuration key.
+ *
+ * @param key the configuration key.
+ * @return the values of this key, null if the key is not valid.
+ */
+ public String getKey(String key)
+ {
+ return gconf_client_get_string(key);
+ }
+
+ /**
+ * Lists the key in the given node. Does not list subnodes. Keys names are the
+ * stripped names (name relative to the current node) of the keys stored in
+ * this node.
+ *
+ * @param node the node where keys are stored.
+ * @return a java.util.List of keys. If there are no keys in the given node, a
+ * list of size 0 is returned.
+ */
+ public List getKeys(String node) throws BackingStoreException
+ {
+ return gconf_client_gconf_client_all_keys(node);
+ }
+
+ /**
+ * Lists the subnodes in node
. The returned list contains
+ * allocated strings. Each string is the name relative tho the given node.
+ *
+ * @param node the node to get subnodes from. If there are no subnodes in the
+ * given node, a list of size 0 is returned.
+ */
+ public List getChildrenNodes(String node) throws BackingStoreException
+ {
+ return gconf_client_gconf_client_all_nodes(node);
+ }
+
+ /**
+ * Suggest to the backend GConf daemon to synch with the database.
+ */
+ public void suggestSync() throws BackingStoreException
+ {
+ gconf_client_suggest_sync();
+ }
+
+ protected void finalize() throws Throwable
+ {
+ try
+ {
+ synchronized (semaphore)
+ {
+ finalize_class();
+ }
+ }
+ finally
+ {
+ super.finalize();
+ }
+ }
+
+ /* ***** native methods ***** */
+
+ /*
+ * Basicly, these are one to one mappings to GConfClient functions.
+ * GConfClient instances are handled by the native layer, and are hidden from
+ * the main java class.
+ */
+
+ /**
+ * Initialize the GConf native peer and enable the object cache.
+ * It is meant to be used by the static initializer.
+ */
+ native static final private void init_id_cache();
+
+ /**
+ * Initialize the GConf native peer. This is meant to be used by the
+ * class constructor.
+ */
+ native static final private void init_class();
+
+ /**
+ * Class finalizer.
+ */
+ native static final private void finalize_class();
+
+ /**
+ * Queries the GConf database to see if the given node exists, returning
+ * true if the node exist, false otherwise.
+ *
+ * @param node the node to query for existence.
+ * @return true if the node exist, false otherwise.
+ */
+ native static final protected boolean gconf_client_dir_exists(String node);
+
+ /**
+ * Adds the given node to the list of nodes that GConf watches for
+ * changes.
+ *
+ * @param node the node to watch for changes.
+ */
+ native static final protected void gconf_client_add_dir(String node);
+
+ /**
+ * Removes the given node from the list of nodes that GConf watches for
+ * changes.
+ *
+ * @param node the node to remove from from the list of watched nodes.
+ */
+ native static final protected void gconf_client_remove_dir(String node);
+
+ /**
+ * Sets the given key/value pair into the GConf database.
+ * The key must be a valid GConf key.
+ *
+ * @param key the key to store in the GConf database
+ * @param value the value to associate to the given key.
+ * @return true if the change has effect, false otherwise.
+ */
+ native static final protected boolean gconf_client_set_string(String key,
+ String value);
+
+ /**
+ * Returns the key associated to the given key. Null is returned if the
+ * key is not valid.
+ *
+ * @param key the key to return the value of.
+ * @return The value associated to the given key, or null.
+ */
+ native static final protected String gconf_client_get_string(String key);
+
+ /**
+ * Usets the given key, removing the key from the database.
+ *
+ * @param key the key to remove.
+ * @return true if the operation success, false otherwise.
+ */
+ native static final protected boolean gconf_client_unset(String key);
+
+ /**
+ * Suggest to the GConf native peer a sync with the database.
+ *
+ */
+ native static final protected void gconf_client_suggest_sync();
+
+ /**
+ * Returns a list of all nodes under the given node.
+ *
+ * @param node the source node.
+ * @return A list of nodes under the given source node.
+ */
+ native
+ static final protected List gconf_client_gconf_client_all_nodes(String node);
+
+ /**
+ * Returns a list of all keys stored in the given node.
+ *
+ * @param node the source node.
+ * @return A list of all keys stored in the given node.
+ */
+ native
+ static final protected List gconf_client_gconf_client_all_keys(String node);
+
+ static
+ {
+ System.loadLibrary("gconfpeer");
+ init_id_cache();
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/BacktrackStack.java b/libjava/classpath/gnu/java/util/regex/BacktrackStack.java
new file mode 100644
index 0000000..d711945
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/BacktrackStack.java
@@ -0,0 +1,112 @@
+/* gnu/regexp/BacktrackStack.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.util.regex;
+
+/**
+ * An instance of this class represents a stack
+ * used for backtracking.
+ *
+ * @author Ito Kazumitsu
+ */
+final class BacktrackStack {
+
+ /** A set of data to be used for backtracking. */
+ static class Backtrack {
+ /** REToken to which to go back */
+ REToken token;
+ /** CharIndexed on which matches are being searched for. */
+ CharIndexed input;
+ /** REMatch to be used by the REToken token. */
+ REMatch match;
+ /** Some parameter used by the token's backtrack method. */
+ Object param;
+ Backtrack(REToken token, CharIndexed input, REMatch match, Object param) {
+ this.token = token;
+ this.input = input;
+ // REMatch may change before backtracking is needed. So we
+ // keep a clone of it.
+ this.match = (REMatch) match.clone();
+ this.param = param;
+ }
+ }
+
+ Backtrack[] stack;
+ private int size;
+ private int capacity;
+ private static final int INITIAL_CAPACITY = 32;
+ private static final int CAPACITY_INCREMENT = 16;
+
+ BacktrackStack() {
+ stack = new Backtrack[INITIAL_CAPACITY];
+ size = 0;
+ capacity = INITIAL_CAPACITY;
+ }
+
+ boolean empty() {
+ return size == 0;
+ }
+
+ Backtrack peek() {
+ return stack[size - 1];
+ }
+
+ Backtrack pop() {
+ Backtrack bt = stack[--size];
+ stack[size] = null;
+ return bt;
+ }
+
+ void clear() {
+ for (int i = 0; i < size; i++) {
+ stack[i] = null;
+ }
+ size = 0;
+ }
+
+ void push(Backtrack bt) {
+ if (size >= capacity) {
+ capacity += CAPACITY_INCREMENT;
+ Backtrack[] newStack = new Backtrack[capacity];
+ System.arraycopy(stack, 0, newStack, 0, size);
+ stack = newStack;
+ }
+ stack[size++] = bt;
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/util/regex/CharIndexed.java b/libjava/classpath/gnu/java/util/regex/CharIndexed.java
new file mode 100644
index 0000000..6cd857e
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/CharIndexed.java
@@ -0,0 +1,116 @@
+/* gnu/regexp/CharIndexed.java
+ Copyright (C) 1998-2001, 2004, 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+
+/**
+ * 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 Wes Biggs
+ */
+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();
+
+ /**
+ * Returns another CharIndexed containing length characters to the left
+ * of the given index. The given length is an expected maximum and
+ * the returned CharIndexed may not necessarily contain so many characters.
+ */
+ CharIndexed lookBehind(int index, int length);
+
+ /**
+ * Returns the effective length of this CharIndexed
+ */
+ int length();
+
+ /**
+ * Sets the REMatch last found on this input.
+ */
+ void setLastMatch(REMatch match);
+
+ /**
+ * Returns the REMatch last found on this input.
+ */
+ REMatch getLastMatch();
+
+ /**
+ * Returns the anchor.
+ */
+ int getAnchor();
+
+ /**
+ * Sets the anchor.
+ */
+ void setAnchor(int anchor);
+}
diff --git a/libjava/classpath/gnu/java/util/regex/CharIndexedCharArray.java b/libjava/classpath/gnu/java/util/regex/CharIndexedCharArray.java
new file mode 100644
index 0000000..6f74c99
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/CharIndexedCharArray.java
@@ -0,0 +1,46 @@
+/* gnu/regexp/CharIndexedCharArray.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+import java.nio.CharBuffer;
+
+class CharIndexedCharArray extends CharIndexedCharSequence {
+
+ CharIndexedCharArray(char[] str, int index) {
+ super(CharBuffer.wrap(str), index);
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/CharIndexedCharSequence.java b/libjava/classpath/gnu/java/util/regex/CharIndexedCharSequence.java
new file mode 100644
index 0000000..2eb753b
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/CharIndexedCharSequence.java
@@ -0,0 +1,82 @@
+/* gnu/regexp/CharIndexedCharSequence.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+import java.io.Serializable;
+
+class CharIndexedCharSequence implements CharIndexed, Serializable {
+ private CharSequence s;
+ private int anchor;
+ private int len;
+
+ CharIndexedCharSequence(CharSequence s, int index) {
+ this.s = s;
+ 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);
+ }
+
+ public CharIndexed lookBehind(int index, int length) {
+ if (length > (anchor + index)) length = anchor + index;
+ return new CharIndexedCharSequence(s, anchor + index - length);
+ }
+
+ public int length() {
+ return len - anchor;
+ }
+
+ private REMatch lastMatch;
+ public void setLastMatch(REMatch match) {
+ lastMatch = (REMatch)match.clone();
+ lastMatch.anchor = anchor;
+ }
+ public REMatch getLastMatch() { return lastMatch; }
+ public int getAnchor() { return anchor; }
+ public void setAnchor(int anchor) { this.anchor = anchor; }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/CharIndexedInputStream.java b/libjava/classpath/gnu/java/util/regex/CharIndexedInputStream.java
new file mode 100644
index 0000000..77cd1ab
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/CharIndexedInputStream.java
@@ -0,0 +1,181 @@
+/* gnu/regexp/CharIndexedInputStream.java
+ Copyright (C) 1998-2001, 2004, 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+// 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);
+ }
+
+ public CharIndexed lookBehind(int index, int length) {
+ throw new UnsupportedOperationException(
+ "difficult to look behind for an input stream");
+ }
+
+ public int length() {
+ throw new UnsupportedOperationException(
+ "difficult to tell the length for an input stream");
+ }
+
+ public void setLastMatch(REMatch match) {
+ throw new UnsupportedOperationException(
+ "difficult to support setLastMatch for an input stream");
+ }
+
+ public REMatch getLastMatch() {
+ throw new UnsupportedOperationException(
+ "difficult to support getLastMatch for an input stream");
+ }
+
+ public int getAnchor() {
+ throw new UnsupportedOperationException(
+ "difficult to support getAnchor for an input stream");
+ }
+
+ public void setAnchor(int anchor) {
+ throw new UnsupportedOperationException(
+ "difficult to support setAnchor for an input stream");
+ }
+
+
+}
+
diff --git a/libjava/classpath/gnu/java/util/regex/CharIndexedString.java b/libjava/classpath/gnu/java/util/regex/CharIndexedString.java
new file mode 100644
index 0000000..fab6d78
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/CharIndexedString.java
@@ -0,0 +1,44 @@
+/* gnu/regexp/CharIndexedString.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+
+class CharIndexedString extends CharIndexedCharSequence {
+ CharIndexedString(String str, int index) {
+ super(str, index);
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/CharIndexedStringBuffer.java b/libjava/classpath/gnu/java/util/regex/CharIndexedStringBuffer.java
new file mode 100644
index 0000000..10005b6
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/CharIndexedStringBuffer.java
@@ -0,0 +1,45 @@
+/* gnu/regexp/CharIndexedStringBuffer.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+
+class CharIndexedStringBuffer extends CharIndexedCharSequence {
+
+ CharIndexedStringBuffer(StringBuffer str, int index) {
+ super(str, index);
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/RE.java b/libjava/classpath/gnu/java/util/regex/RE.java
new file mode 100644
index 0000000..1aab3b7
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/RE.java
@@ -0,0 +1,2128 @@
+/* gnu/regexp/RE.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+import java.io.InputStream;
+import java.io.Serializable;
+import java.util.Locale;
+import java.util.PropertyResourceBundle;
+import java.util.ResourceBundle;
+import java.util.Stack;
+import java.util.Vector;
+
+/**
+ * RE provides the user interface for compiling and matching regular
+ * expressions.
+ * RESyntax.RE_SYNTAX_PERL5
is used).
+ * isMatch
: returns true if the input text in its
+ * entirety matches the regular expression pattern.
+ * getMatch
: returns the first match found in the
+ * input text, or null if no match is found.
+ * getAllMatches
: returns an array of all
+ * non-overlapping matches found in the input text. If no matches are
+ * found, the array is zero-length.
+ * substitute
: substitute the first occurence of the
+ * pattern in the input text with a replacement string (which may
+ * include metacharacters $0-$9, see REMatch.substituteInto).
+ * substituteAll
: same as above, but repeat for each
+ * match before returning.
+ * getMatchEnumeration
: 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 getAllMatches
.
+ *
+ * String s = "food bar fool";
+ */
+ public static final int REG_NOTBOL = 0x10;
+
+ /**
+ * 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 = 0x20;
+
+ /**
+ * 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 = 0x40;
+
+ /**
+ * 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 = 0x80;
+
+ /**
+ * Execution flag.
+ * Try to match the whole input string. An implicit match-end operator
+ * is added to this regexp.
+ */
+ public static final int REG_TRY_ENTIRE_MATCH = 0x0100;
+
+ /**
+ * Execution flag.
+ * The substitute and substituteAll methods will treat the
+ * character '\' in the replacement as an escape to a literal
+ * character. In this case "\n", "\$", "\\", "\x40" and "\012"
+ * will become "n", "$", "\", "x40" and "012" respectively.
+ * This flag has no effect if REG_NO_INTERPOLATE is set on.
+ */
+ public static final int REG_REPLACE_USE_BACKSLASHESCAPE = 0x0200;
+
+ /**
+ * Compilation flag. Allow whitespace and comments in pattern.
+ * This is equivalent to the "/x" operator in Perl.
+ */
+ public static final int REG_X_COMMENTS = 0x0400;
+
+ /**
+ * Compilation flag. If set, REG_ICASE is effective only for US-ASCII.
+ */
+ public static final int REG_ICASE_USASCII = 0x0800;
+
+ /** Returns a string representing the version of the gnu.regexp package. */
+ public static final String version() {
+ return VERSION;
+ }
+
+ // Retrieves a message from the ResourceBundle
+ static final String getLocalizedMessage(String key) {
+ 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, int maxLength) {
+ super(subIndex);
+ firstToken = first;
+ lastToken = last;
+ numSubs = subs;
+ minimumLength = minLength;
+ maximumLength = maxLength;
+ 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);
+ boolean insensUSASCII = ((cflags & REG_ICASE_USASCII) > 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;
+ boolean quot = false;
+
+ // Saved syntax and flags.
+ RESyntax savedSyntax = null;
+ int savedCflags = 0;
+ boolean flagsSaved = false;
+
+ while (index < pLength) {
+ // read the next character unit (including backslash escapes)
+ index = getCharUnit(pattern,index,unit,quot);
+
+ if (unit.bk)
+ if (unit.ch == 'Q') {
+ quot = true;
+ continue;
+ } else if (unit.ch == 'E') {
+ quot = false;
+ continue;
+ }
+ if (quot)
+ unit.bk = false;
+
+ if (((cflags & REG_X_COMMENTS) > 0) && (!unit.bk) && (!quot)) {
+ if (Character.isWhitespace(unit.ch)) {
+ continue;
+ }
+ if (unit.ch == '#') {
+ for (int i = index; i < pLength; i++) {
+ if (pattern[i] == '\n') {
+ index = i + 1;
+ continue;
+ }
+ else if (pattern[i] == '\r') {
+ if (i + 1 < pLength && pattern[i + 1] == '\n') {
+ index = i + 2;
+ }
+ else {
+ index = i + 1;
+ }
+ continue;
+ }
+ }
+ index = pLength;
+ continue;
+ }
+ }
+
+ // 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 || quot)))
+ || (syntax.get(RESyntax.RE_NEWLINE_ALT) && (unit.ch == '\n') && !(unit.bk || quot)) )
+ && !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, maximumLength);
+ minimumLength = 0;
+ maximumLength = 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?
+ //
+ // This method used to check "repeat.empty.token" to avoid such regexp
+ // as "(a*){2,}", but now "repeat.empty.token" is allowed.
+
+ else if ((unit.ch == '{') && syntax.get(RESyntax.RE_INTERVALS) && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ (unit.bk || quot))) {
+ 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);
+ index = newIndex;
+ currentToken = setRepeated(currentToken,minMax.first,minMax.second,index);
+ }
+ else {
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,unit.ch,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+ }
+
+ // LIST OPERATOR:
+ // [...] | [^...]
+
+ else if ((unit.ch == '[') && !(unit.bk || quot)) {
+ // Create a new RETokenOneOf
+ ParseCharClassResult result = parseCharClass(
+ subIndex, pattern, index, pLength, cflags, syntax, 0);
+ addToken(currentToken);
+ currentToken = result.token;
+ index = result.index;
+ }
+
+ // SUBEXPRESSIONS
+ // (...) | \(...\) depending on RE_NO_BK_PARENS
+
+ else if ((unit.ch == '(') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) {
+ boolean pure = false;
+ boolean comment = false;
+ boolean lookAhead = false;
+ boolean lookBehind = false;
+ boolean independent = false;
+ boolean negativelh = false;
+ boolean negativelb = 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 '<':
+ // We assume that if the syntax supports look-ahead,
+ // it also supports look-behind.
+ if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
+ index++;
+ switch (pattern[index +1]) {
+ case '!':
+ pure = true;
+ negativelb = true;
+ lookBehind = true;
+ index += 2;
+ break;
+ case '=':
+ pure = true;
+ lookBehind = true;
+ index += 2;
+ }
+ }
+ break;
+ case '>':
+ // We assume that if the syntax supports look-ahead,
+ // it also supports independent group.
+ if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
+ pure = true;
+ independent = true;
+ index += 2;
+ }
+ break;
+ case 'i':
+ case 'd':
+ case 'm':
+ case 's':
+ case 'u':
+ case 'x':
+ case '-':
+ if (!syntax.get(RESyntax.RE_EMBEDDED_FLAGS)) break;
+ // Set or reset syntax flags.
+ int flagIndex = index + 1;
+ int endFlag = -1;
+ RESyntax newSyntax = new RESyntax(syntax);
+ int newCflags = cflags;
+ boolean negate = false;
+ while (flagIndex < pLength && endFlag < 0) {
+ switch(pattern[flagIndex]) {
+ case 'i':
+ if (negate)
+ newCflags &= ~REG_ICASE;
+ else
+ newCflags |= REG_ICASE;
+ flagIndex++;
+ break;
+ case 'd':
+ if (negate)
+ newSyntax.setLineSeparator(RESyntax.DEFAULT_LINE_SEPARATOR);
+ else
+ newSyntax.setLineSeparator("\n");
+ flagIndex++;
+ break;
+ case 'm':
+ if (negate)
+ newCflags &= ~REG_MULTILINE;
+ else
+ newCflags |= REG_MULTILINE;
+ flagIndex++;
+ break;
+ case 's':
+ if (negate)
+ newCflags &= ~REG_DOT_NEWLINE;
+ else
+ newCflags |= REG_DOT_NEWLINE;
+ flagIndex++;
+ break;
+ case 'u':
+ if (negate)
+ newCflags |= REG_ICASE_USASCII;
+ else
+ newCflags &= ~REG_ICASE_USASCII;
+ flagIndex++;
+ break;
+ case 'x':
+ if (negate)
+ newCflags &= ~REG_X_COMMENTS;
+ else
+ newCflags |= REG_X_COMMENTS;
+ flagIndex++;
+ break;
+ case '-':
+ negate = true;
+ flagIndex++;
+ break;
+ case ':':
+ case ')':
+ endFlag = pattern[flagIndex];
+ break;
+ default:
+ throw new REException(getLocalizedMessage("repeat.no.token"), REException.REG_BADRPT, index);
+ }
+ }
+ if (endFlag == ')') {
+ syntax = newSyntax;
+ cflags = newCflags;
+ insens = ((cflags & REG_ICASE) > 0);
+ insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+ // This can be treated as though it were a comment.
+ comment = true;
+ index = flagIndex - 1;
+ break;
+ }
+ if (endFlag == ':') {
+ savedSyntax = syntax;
+ savedCflags = cflags;
+ flagsSaved = true;
+ syntax = newSyntax;
+ cflags = newCflags;
+ insens = ((cflags & REG_ICASE) > 0);
+ insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+ index = flagIndex -1;
+ // Fall through to the next case.
+ }
+ else {
+ throw new REException(getLocalizedMessage("unmatched.paren"), REException.REG_ESUBREG,index);
+ }
+ 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,false)) > 0)
+ && !(nested == 0 && (unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) ) {
+ if ((endIndex = nextIndex) >= pLength)
+ throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
+ else if ((unit.ch == '[') && !(unit.bk || quot)) {
+ // I hate to do something similar to the LIST OPERATOR matters
+ // above, but ...
+ int listIndex = nextIndex;
+ if (listIndex < pLength && pattern[listIndex] == '^') listIndex++;
+ if (listIndex < pLength && pattern[listIndex] == ']') listIndex++;
+ int listEndIndex = -1;
+ int listNest = 0;
+ while (listIndex < pLength && listEndIndex < 0) {
+ switch(pattern[listIndex++]) {
+ case '\\':
+ listIndex++;
+ break;
+ case '[':
+ // Sun's API document says that regexp like "[a-d[m-p]]"
+ // is legal. Even something like "[[[^]]]]" is accepted.
+ listNest++;
+ if (listIndex < pLength && pattern[listIndex] == '^') listIndex++;
+ if (listIndex < pLength && pattern[listIndex] == ']') listIndex++;
+ break;
+ case ']':
+ if (listNest == 0)
+ listEndIndex = listIndex;
+ listNest--;
+ break;
+ }
+ }
+ if (listEndIndex >= 0) {
+ nextIndex = listEndIndex;
+ if ((endIndex = nextIndex) >= pLength)
+ throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
+ else
+ continue;
+ }
+ throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
+ }
+ else if (unit.ch == '(' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))
+ nested++;
+ else if (unit.ch == ')' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))
+ 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 || lookBehind || independent) ?
+ 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);
+ }
+ else if (lookBehind) {
+ currentToken = new RETokenLookBehind(currentToken,negativelb);
+ }
+ else if (independent) {
+ currentToken = new RETokenIndependent(currentToken);
+ }
+
+ index = nextIndex;
+ if (flagsSaved) {
+ syntax = savedSyntax;
+ cflags = savedCflags;
+ insens = ((cflags & REG_ICASE) > 0);
+ insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+ flagsSaved = false;
+ }
+ } // 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 || quot)))) {
+ throw new REException(getLocalizedMessage("unmatched.paren"),REException.REG_EPAREN,index);
+ }
+
+ // START OF LINE OPERATOR
+ // ^
+
+ else if ((unit.ch == '^') && !(unit.bk || quot)) {
+ addToken(currentToken);
+ currentToken = null;
+ RETokenStart token = null;
+ if ((cflags & REG_MULTILINE) > 0) {
+ String sep = syntax.getLineSeparator();
+ if (sep == null) {
+ token = new RETokenStart(subIndex, null, true);
+ }
+ else {
+ token = new RETokenStart(subIndex, sep);
+ }
+ }
+ else {
+ token = new RETokenStart(subIndex, null);
+ }
+ addToken(token);
+ }
+
+ // END OF LINE OPERATOR
+ // $
+
+ else if ((unit.ch == '$') && !(unit.bk || quot)) {
+ addToken(currentToken);
+ currentToken = null;
+ RETokenEnd token = null;
+ if ((cflags & REG_MULTILINE) > 0) {
+ String sep = syntax.getLineSeparator();
+ if (sep == null) {
+ token = new RETokenEnd(subIndex, null, true);
+ }
+ else {
+ token = new RETokenEnd(subIndex, sep);
+ }
+ }
+ else {
+ token = new RETokenEnd(subIndex, null);
+ }
+ addToken(token);
+ }
+
+ // MATCH-ANY-CHARACTER OPERATOR (except possibly newline and null)
+ // .
+
+ else if ((unit.ch == '.') && !(unit.bk || quot)) {
+ 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
+ // *
+ //
+ // This method used to check "repeat.empty.token" to avoid such regexp
+ // as "(a*)*", but now "repeat.empty.token" is allowed.
+
+ else if ((unit.ch == '*') && !(unit.bk || quot)) {
+ 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);
+ currentToken = setRepeated(currentToken,0,Integer.MAX_VALUE,index);
+ }
+
+ // ONE-OR-MORE REPEAT OPERATOR / POSSESSIVE MATCHING OPERATOR
+ // + | \+ depending on RE_BK_PLUS_QM
+ // not available if RE_LIMITED_OPS is set
+ //
+ // This method used to check "repeat.empty.token" to avoid such regexp
+ // as "(a*)+", but now "repeat.empty.token" is allowed.
+
+ else if ((unit.ch == '+') && !syntax.get(RESyntax.RE_LIMITED_OPS) && (!syntax.get(RESyntax.RE_BK_PLUS_QM) ^ (unit.bk || quot))) {
+ if (currentToken == null)
+ throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
+
+ // Check for possessive matching on RETokenRepeated
+ if (currentToken instanceof RETokenRepeated) {
+ RETokenRepeated tokenRep = (RETokenRepeated)currentToken;
+ if (syntax.get(RESyntax.RE_POSSESSIVE_OPS) && !tokenRep.isPossessive() && !tokenRep.isStingy())
+ tokenRep.makePossessive();
+ 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,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 || quot))) {
+ if (currentToken == null) throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
+
+ // Check for stingy matching on RETokenRepeated
+ if (currentToken instanceof RETokenRepeated) {
+ RETokenRepeated tokenRep = (RETokenRepeated)currentToken;
+ if (syntax.get(RESyntax.RE_STINGY_OPS) && !tokenRep.isStingy() && !tokenRep.isPossessive())
+ tokenRep.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);
+ }
+
+ // OCTAL CHARACTER
+ // \0377
+
+ else if (unit.bk && (unit.ch == '0') && syntax.get(RESyntax.RE_OCTAL_CHAR)) {
+ CharExpression ce = getCharExpression(pattern, index - 2, pLength, syntax);
+ if (ce == null)
+ throw new REException("invalid octal character", REException.REG_ESCAPE, index);
+ index = index - 2 + ce.len;
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,ce.ch,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // BACKREFERENCE OPERATOR
+ // \1 \2 ... \9 and \10 \11 \12 ...
+ // not available if RE_NO_BK_REFS is set
+ // Perl recognizes \10, \11, and so on only if enough number of
+ // parentheses have opened before it, otherwise they are treated
+ // as aliases of \010, \011, ... (octal characters). In case of
+ // Sun's JDK, octal character expression must always begin with \0.
+ // We will do as JDK does. But FIXME, take a look at "(a)(b)\29".
+ // JDK treats \2 as a back reference to the 2nd group because
+ // there are only two groups. But in our poor implementation,
+ // we cannot help but treat \29 as a back reference to the 29th group.
+
+ else if (unit.bk && Character.isDigit(unit.ch) && !syntax.get(RESyntax.RE_NO_BK_REFS)) {
+ addToken(currentToken);
+ int numBegin = index - 1;
+ int numEnd = pLength;
+ for (int i = index; i < pLength; i++) {
+ if (! Character.isDigit(pattern[i])) {
+ numEnd = i;
+ break;
+ }
+ }
+ int num = parseInt(pattern, numBegin, numEnd-numBegin, 10);
+
+ currentToken = new RETokenBackRef(subIndex,num,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ index = numEnd;
+ }
+
+ // 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);
+ if (insensUSASCII) currentToken.unicodeAware = 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);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // 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);
+ if (insensUSASCII) currentToken.unicodeAware = 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);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // 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);
+ if (insensUSASCII) currentToken.unicodeAware = 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);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // END OF STRING OPERATOR
+ // \Z, \z
+
+ // FIXME: \Z and \z are different in that if the input string
+ // ends with a line terminator, \Z matches the position before
+ // the final terminator. This special behavior of \Z is yet
+ // to be implemented.
+
+ else if (unit.bk && (unit.ch == 'Z' || unit.ch == 'z') &&
+ syntax.get(RESyntax.RE_STRING_ANCHORS)) {
+ addToken(currentToken);
+ currentToken = new RETokenEnd(subIndex,null);
+ }
+
+ // HEX CHARACTER, UNICODE CHARACTER
+ // \x1B, \u1234
+
+ else if ((unit.bk && (unit.ch == 'x') && syntax.get(RESyntax.RE_HEX_CHAR)) ||
+ (unit.bk && (unit.ch == 'u') && syntax.get(RESyntax.RE_UNICODE_CHAR))) {
+ CharExpression ce = getCharExpression(pattern, index - 2, pLength, syntax);
+ if (ce == null)
+ throw new REException("invalid hex character", REException.REG_ESCAPE, index);
+ index = index - 2 + ce.len;
+ addToken(currentToken);
+ currentToken = new RETokenChar(subIndex,ce.ch,insens);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // NAMED PROPERTY
+ // \p{prop}, \P{prop}
+
+ else if ((unit.bk && (unit.ch == 'p') && syntax.get(RESyntax.RE_NAMED_PROPERTY)) ||
+ (unit.bk && (unit.ch == 'P') && syntax.get(RESyntax.RE_NAMED_PROPERTY))) {
+ NamedProperty np = getNamedProperty(pattern, index - 2, pLength);
+ if (np == null)
+ throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
+ index = index - 2 + np.len;
+ addToken(currentToken);
+ currentToken = getRETokenNamedProperty(subIndex,np,insens,index);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+
+ // END OF PREVIOUS MATCH
+ // \G
+
+ else if (unit.bk && (unit.ch == 'G') &&
+ syntax.get(RESyntax.RE_STRING_ANCHORS)) {
+ addToken(currentToken);
+ currentToken = new RETokenEndOfPreviousMatch(subIndex);
+ }
+
+ // 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);
+ if (insensUSASCII) currentToken.unicodeAware = false;
+ }
+ } // end while
+
+ // Add final buffered token and an EndSub marker
+ addToken(currentToken);
+
+ if (branches != null) {
+ branches.addElement(new RE(firstToken,lastToken,numSubs,subIndex,minimumLength, maximumLength));
+ branches.trimToSize(); // compact the Vector
+ minimumLength = 0;
+ maximumLength = 0;
+ firstToken = lastToken = null;
+ addToken(new RETokenOneOf(subIndex,branches,false));
+ }
+ else addToken(new RETokenEndSub(subIndex));
+
+ }
+
+ private static class ParseCharClassResult {
+ RETokenOneOf token;
+ int index;
+ boolean returnAtAndOperator = false;
+ }
+
+ /**
+ * Parse [...] or [^...] and make an RETokenOneOf instance.
+ * @param subIndex subIndex to be given to the created RETokenOneOf instance.
+ * @param pattern Input array of characters to be parsed.
+ * @param index Index pointing to the character next to the beginning '['.
+ * @param pLength Limit of the input array.
+ * @param cflags Compilation flags used to parse the pattern.
+ * @param pflags Flags that affect the behavior of this method.
+ * @param syntax Syntax used to parse the pattern.
+ */
+ private static ParseCharClassResult parseCharClass(int subIndex,
+ char[] pattern, int index,
+ int pLength, int cflags, RESyntax syntax, int pflags)
+ throws REException {
+
+ boolean insens = ((cflags & REG_ICASE) > 0);
+ boolean insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
+ Vector options = new Vector();
+ Vector addition = new Vector();
+ boolean additionAndAppeared = false;
+ final int RETURN_AT_AND = 0x01;
+ boolean returnAtAndOperator = ((pflags & RETURN_AT_AND) != 0);
+ boolean negative = false;
+ char ch;
+
+ char lastChar = 0;
+ boolean lastCharIsSet = false;
+ 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; lastCharIsSet = true;
+ if (++index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
+ }
+
+ while ((ch = pattern[index++]) != ']') {
+ if ((ch == '-') && (lastCharIsSet)) {
+ if (index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
+ if ((ch = pattern[index]) == ']') {
+ RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ lastChar = '-';
+ } else {
+ if ((ch == '\\') && syntax.get(RESyntax.RE_BACKSLASH_ESCAPE_IN_LISTS)) {
+ CharExpression ce = getCharExpression(pattern, index, pLength, syntax);
+ if (ce == null)
+ throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
+ ch = ce.ch;
+ index = index + ce.len - 1;
+ }
+ RETokenRange t = new RETokenRange(subIndex,lastChar,ch,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ lastChar = 0; lastCharIsSet = false;
+ 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;
+ boolean asciiEscIsSet = false;
+ NamedProperty np = null;
+ 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;
+ }
+ }
+ if (("pP".indexOf(pattern[index]) != -1) && syntax.get(RESyntax.RE_NAMED_PROPERTY)) {
+ np = getNamedProperty(pattern, index - 1, pLength);
+ if (np == null)
+ throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
+ index = index - 1 + np.len - 1;
+ }
+ else {
+ CharExpression ce = getCharExpression(pattern, index - 1, pLength, syntax);
+ if (ce == null)
+ throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
+ asciiEsc = ce.ch; asciiEscIsSet = true;
+ index = index - 1 + ce.len - 1;
+ }
+ if (lastCharIsSet) {
+ RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ }
+
+ if (posixID != -1) {
+ RETokenPOSIX t = new RETokenPOSIX(subIndex,posixID,insens,negate);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ } else if (np != null) {
+ RETokenNamedProperty t = getRETokenNamedProperty(subIndex,np,insens,index);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ } else if (asciiEscIsSet) {
+ lastChar = asciiEsc; lastCharIsSet = true;
+ } else {
+ lastChar = pattern[index]; lastCharIsSet = true;
+ }
+ ++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) {
+ RETokenPOSIX t = new RETokenPOSIX(subIndex,posixId,insens,false);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ }
+ } else if ((ch == '[') && (syntax.get(RESyntax.RE_NESTED_CHARCLASS))) {
+ ParseCharClassResult result = parseCharClass(
+ subIndex, pattern, index, pLength, cflags, syntax, 0);
+ addition.addElement(result.token);
+ addition.addElement("|");
+ index = result.index;
+ } else if ((ch == '&') &&
+ (syntax.get(RESyntax.RE_NESTED_CHARCLASS)) &&
+ (index < pLength) && (pattern[index] == '&')) {
+ if (returnAtAndOperator) {
+ ParseCharClassResult result = new ParseCharClassResult();
+ options.trimToSize();
+ if (additionAndAppeared) addition.addElement("&");
+ if (addition.size() == 0) addition = null;
+ result.token = new RETokenOneOf(subIndex,
+ options, addition, negative);
+ result.index = index - 1;
+ result.returnAtAndOperator = true;
+ return result;
+ }
+ // The precedence of the operator "&&" is the lowest.
+ // So we postpone adding "&" until other elements
+ // are added. And we insert Boolean.FALSE at the
+ // beginning of the list of tokens following "&&".
+ // So, "&&[a-b][k-m]" will be stored in the Vecter
+ // addition in this order:
+ // Boolean.FALSE, [a-b], "|", [k-m], "|", "&"
+ if (additionAndAppeared) addition.addElement("&");
+ addition.addElement(Boolean.FALSE);
+ additionAndAppeared = true;
+
+ // The part on which "&&" operates may be either
+ // (1) explicitly enclosed by []
+ // or
+ // (2) not enclosed by [] and terminated by the
+ // next "&&" or the end of the character list.
+ // Let the preceding else if block do the case (1).
+ // We must do something in case of (2).
+ if ((index + 1 < pLength) && (pattern[index + 1] != '[')) {
+ ParseCharClassResult result = parseCharClass(
+ subIndex, pattern, index+1, pLength, cflags, syntax,
+ RETURN_AT_AND);
+ addition.addElement(result.token);
+ addition.addElement("|");
+ // If the method returned at the next "&&", it is OK.
+ // Otherwise we have eaten the mark of the end of this
+ // character list "]". In this case we must give back
+ // the end mark.
+ index = (result.returnAtAndOperator ?
+ result.index: result.index - 1);
+ }
+ } else {
+ if (lastCharIsSet) {
+ RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ }
+ lastChar = ch; lastCharIsSet = true;
+ }
+ 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 (lastCharIsSet) {
+ RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
+ if (insensUSASCII) t.unicodeAware = false;
+ options.addElement(t);
+ }
+
+ ParseCharClassResult result = new ParseCharClassResult();
+ // Create a new RETokenOneOf
+ options.trimToSize();
+ if (additionAndAppeared) addition.addElement("&");
+ if (addition.size() == 0) addition = null;
+ result.token = new RETokenOneOf(subIndex,options, addition, negative);
+ result.index = index;
+ return result;
+ }
+
+ private static int getCharUnit(char[] input, int index, CharUnit unit, boolean quot) throws REException {
+ unit.ch = input[index++];
+ unit.bk = (unit.ch == '\\'
+ && (!quot || index >= input.length || input[index] == 'E'));
+ if (unit.bk)
+ if (index < input.length)
+ unit.ch = input[index++];
+ else throw new REException(getLocalizedMessage("ends.with.backslash"),REException.REG_ESCAPE,index);
+ return index;
+ }
+
+ private static int parseInt(char[] input, int pos, int len, int radix) {
+ int ret = 0;
+ for (int i = pos; i < pos + len; i++) {
+ ret = ret * radix + Character.digit(input[i], radix);
+ }
+ return ret;
+ }
+
+ /**
+ * This class represents various expressions for a character.
+ * "a" : 'a' itself.
+ * "\0123" : Octal char 0123
+ * "\x1b" : Hex char 0x1b
+ * "\u1234" : Unicode char \u1234
+ */
+ private static class CharExpression {
+ /** character represented by this expression */
+ char ch;
+ /** String expression */
+ String expr;
+ /** length of this expression */
+ int len;
+ public String toString() { return expr; }
+ }
+
+ private static CharExpression getCharExpression(char[] input, int pos, int lim,
+ RESyntax syntax) {
+ CharExpression ce = new CharExpression();
+ char c = input[pos];
+ if (c == '\\') {
+ if (pos + 1 >= lim) return null;
+ c = input[pos + 1];
+ switch(c) {
+ case 't':
+ ce.ch = '\t';
+ ce.len = 2;
+ break;
+ case 'n':
+ ce.ch = '\n';
+ ce.len = 2;
+ break;
+ case 'r':
+ ce.ch = '\r';
+ ce.len = 2;
+ break;
+ case 'x':
+ case 'u':
+ if ((c == 'x' && syntax.get(RESyntax.RE_HEX_CHAR)) ||
+ (c == 'u' && syntax.get(RESyntax.RE_UNICODE_CHAR))) {
+ int l = 0;
+ int expectedLength = (c == 'x' ? 2 : 4);
+ for (int i = pos + 2; i < pos + 2 + expectedLength; i++) {
+ if (i >= lim) break;
+ if (!((input[i] >= '0' && input[i] <= '9') ||
+ (input[i] >= 'A' && input[i] <= 'F') ||
+ (input[i] >= 'a' && input[i] <= 'f')))
+ break;
+ l++;
+ }
+ if (l != expectedLength) return null;
+ ce.ch = (char)(parseInt(input, pos + 2, l, 16));
+ ce.len = l + 2;
+ }
+ else {
+ ce.ch = c;
+ ce.len = 2;
+ }
+ break;
+ case '0':
+ if (syntax.get(RESyntax.RE_OCTAL_CHAR)) {
+ int l = 0;
+ for (int i = pos + 2; i < pos + 2 + 3; i++) {
+ if (i >= lim) break;
+ if (input[i] < '0' || input[i] > '7') break;
+ l++;
+ }
+ if (l == 3 && input[pos + 2] > '3') l--;
+ if (l <= 0) return null;
+ ce.ch = (char)(parseInt(input, pos + 2, l, 8));
+ ce.len = l + 2;
+ }
+ else {
+ ce.ch = c;
+ ce.len = 2;
+ }
+ break;
+ default:
+ ce.ch = c;
+ ce.len = 2;
+ break;
+ }
+ }
+ else {
+ ce.ch = input[pos];
+ ce.len = 1;
+ }
+ ce.expr = new String(input, pos, ce.len);
+ return ce;
+ }
+
+ /**
+ * This class represents a substring in a pattern string expressing
+ * a named property.
+ * "\pA" : Property named "A"
+ * "\p{prop}" : Property named "prop"
+ * "\PA" : Property named "A" (Negated)
+ * "\P{prop}" : Property named "prop" (Negated)
+ */
+ private static class NamedProperty {
+ /** Property name */
+ String name;
+ /** Negated or not */
+ boolean negate;
+ /** length of this expression */
+ int len;
+ }
+
+ private static NamedProperty getNamedProperty(char[] input, int pos, int lim) {
+ NamedProperty np = new NamedProperty();
+ char c = input[pos];
+ if (c == '\\') {
+ if (++pos >= lim) return null;
+ c = input[pos++];
+ switch(c) {
+ case 'p':
+ np.negate = false;
+ break;
+ case 'P':
+ np.negate = true;
+ break;
+ default:
+ return null;
+ }
+ c = input[pos++];
+ if (c == '{') {
+ int p = -1;
+ for (int i = pos; i < lim; i++) {
+ if (input[i] == '}') {
+ p = i;
+ break;
+ }
+ }
+ if (p < 0) return null;
+ int len = p - pos;
+ np.name = new String(input, pos, len);
+ np.len = len + 4;
+ }
+ else {
+ np.name = new String(input, pos - 1, 1);
+ np.len = 3;
+ }
+ return np;
+ }
+ else return null;
+ }
+
+ private static RETokenNamedProperty getRETokenNamedProperty(
+ int subIndex, NamedProperty np, boolean insens, int index)
+ throws REException {
+ try {
+ return new RETokenNamedProperty(subIndex, np.name, insens, np.negate);
+ }
+ catch (REException e) {
+ REException ree;
+ ree = new REException(e.getMessage(), REException.REG_ESCAPE, index);
+ ree.initCause(e);
+ throw ree;
+ }
+ }
+
+ /**
+ * 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)) {
+ if (m != null) {
+ if (input.charAt(m.index) == CharIndexed.OUT_OF_BOUNDS) {
+ return true;
+ }
+ }
+ }
+ 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;
+ }
+
+ public int getMaximumLength() {
+ return maximumLength;
+ }
+
+ /**
+ * 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.start1[subIndex] = mymatch.index;
+
+ return firstToken.match(input, mymatch);
+ }
+
+ REMatch findMatch(CharIndexed input, REMatch mymatch) {
+ if (mymatch.backtrackStack == null)
+ mymatch.backtrackStack = new BacktrackStack();
+ boolean b = match(input, mymatch);
+ if (b) {
+ return mymatch;
+ }
+ return null;
+ }
+
+ /**
+ * 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) {
+ boolean tryEntireMatch = ((eflags & REG_TRY_ENTIRE_MATCH) != 0);
+ RE re = (tryEntireMatch ? (RE) this.clone() : this);
+ if (tryEntireMatch) {
+ re.chain(new RETokenEnd(0, null));
+ }
+ // 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 (re.match(input, mymatch)) {
+ REMatch best = mymatch;
+ // We assume that the match that coms first is the best.
+ // And the following "The longer, the better" rule has
+ // been commented out. The longest is not neccesarily
+ // the best. For example, "a" out of "aaa" is the best
+ // match for /a+?/.
+ /*
+ // Find best match of them all to observe leftmost longest
+ while ((mymatch = mymatch.next) != null) {
+ if (mymatch.index > best.index) {
+ best = mymatch;
+ }
+ }
+ */
+ best.end[0] = best.index;
+ best.finish(input);
+ input.setLastMatch(best);
+ return best;
+ }
+ }
+ 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));
+
+ // Special handling at end of input for e.g. "$"
+ if (minimumLength == 0) {
+ if (match(input, mymatch)) {
+ mymatch.finish(input);
+ return mymatch;
+ }
+ }
+
+ 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(getReplacement(replace, m, eflags));
+ 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(getReplacement(replace, m, eflags));
+ 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();
+ }
+
+ public static String getReplacement(String replace, REMatch m, int eflags) {
+ if ((eflags & REG_NO_INTERPOLATE) > 0)
+ return replace;
+ else {
+ if ((eflags & REG_REPLACE_USE_BACKSLASHESCAPE) > 0) {
+ StringBuffer sb = new StringBuffer();
+ int l = replace.length();
+ for (int i = 0; i < l; i++) {
+ char c = replace.charAt(i);
+ switch(c) {
+ case '\\':
+ i++;
+ // Let StringIndexOutOfBoundsException be thrown.
+ sb.append(replace.charAt(i));
+ break;
+ case '$':
+ int i1 = i + 1;
+ while (i1 < replace.length() &&
+ Character.isDigit(replace.charAt(i1))) i1++;
+ sb.append(m.substituteInto(replace.substring(i, i1)));
+ i = i1 - 1;
+ break;
+ default:
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+ else
+ return m.substituteInto(replace);
+ }
+ }
+
+ /* Helper function for constructor */
+ private void addToken(REToken next) {
+ if (next == null) return;
+ minimumLength += next.getMinimumLength();
+ int nmax = next.getMaximumLength();
+ if (nmax < Integer.MAX_VALUE && maximumLength < Integer.MAX_VALUE)
+ maximumLength += nmax;
+ else
+ maximumLength = Integer.MAX_VALUE;
+
+ 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,false);
+ 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,false)) != 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("(?#startRE subIndex=" + subIndex + ")");
+ if (subIndex == 0)
+ os.append("?:");
+ if (firstToken != null)
+ firstToken.dumpAll(os);
+ if (subIndex == 0)
+ os.append(")");
+ os.append("(?#endRE subIndex=" + subIndex + ")");
+ }
+
+ // Cast input appropriately or throw exception
+ // This method was originally a private method, but has been made
+ // public because java.util.regex.Matcher uses this.
+ public static CharIndexed makeCharIndexed(Object input, int index) {
+ // The case where input is already a CharIndexed is supposed
+ // be the most likely because this is the case with
+ // java.util.regex.Matcher.
+ // We could let a String or a CharSequence fall through
+ // to final input, but since it'a very likely input type,
+ // we check it first.
+ if (input instanceof CharIndexed) {
+ CharIndexed ci = (CharIndexed) input;
+ ci.setAnchor(index);
+ return ci;
+ }
+ else if (input instanceof CharSequence)
+ return new CharIndexedCharSequence((CharSequence) input,index);
+ else 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
+ return new CharIndexedString(input.toString(), index);
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/REException.java b/libjava/classpath/gnu/java/util/regex/REException.java
new file mode 100644
index 0000000..4104fbc
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/REException.java
@@ -0,0 +1,182 @@
+/* gnu/regexp/REException.java
+ Copyright (C) 1998-2001, 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+
+import java.text.MessageFormat;
+
+/**
+ * This is the regular expression exception class. An exception of this type
+ * defines the three attributes:
+ *
+ * RE exp = new RE("^foo.");
+ * REMatch m0 = exp.getMatch(s);
+ * REMatch m1 = exp.getMatch(s.substring(8));
+ * REMatch m2 = exp.getMatch(s.substring(8),0,RE.REG_NOTBOL);
+ * REMatch m3 = exp.getMatch(s,8);
+ * REMatch m4 = exp.getMatch(s,8,RE.REG_ANCHORINDEX);
+ *
+ * // m0.toString(): "food"
+ * // m1.toString(): "fool"
+ * // m2.toString(): null
+ * // m3.toString(): null
+ * // m4.toString(): "fool"
+ *
+ *
+ *
+ * @author Wes Biggs
+ */
+
+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. Not implemented.
+ */
+ 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. Not implemented.
+ */
+ public static final int REG_EEND = 9;
+
+ /**
+ * Error flag.
+ * Invalid escape sequence. Not implemented.
+ */
+ 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. Not implemented.
+ */
+ public static final int REG_ESIZE = 12;
+
+ /**
+ * Error flag.
+ * The regex routines ran out of memory. Not implemented.
+ */
+ 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();
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/REFilterInputStream.java b/libjava/classpath/gnu/java/util/regex/REFilterInputStream.java
new file mode 100644
index 0000000..abe8630
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/REFilterInputStream.java
@@ -0,0 +1,140 @@
+/* gnu/regexp/REFilterInputStream.java
+ Copyright (C) 1998-2001, 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.util.regex;
+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 Wes Biggs
+ * @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);
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/REMatch.java b/libjava/classpath/gnu/java/util/regex/REMatch.java
new file mode 100644
index 0000000..3ff5ad7
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/REMatch.java
@@ -0,0 +1,324 @@
+/* gnu/regexp/REMatch.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.util.regex;
+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 Wes Biggs
+ */
+public final class REMatch implements Serializable, Cloneable {
+ private String matchedText;
+ private CharIndexed matchedCharIndexed;
+
+ // 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
+ // start1[i] is set when the i-th subexp starts. And start1[i] is copied
+ // to start[i] when the i-th subexp ends. So start[i] keeps the previously
+ // assigned value while the i-th subexp is being processed. This makes
+ // backreference to the i-th subexp within the i-th subexp possible.
+ int[] start; // start positions (relative to offset) for each (sub)exp.
+ int[] start1; // start positions (relative to offset) for each (sub)exp.
+ int[] end; // end positions for the same
+ // start[i] == -1 or end[i] == -1 means that the start/end position is void.
+ // start[i] == p or end[i] == p where p < 0 and p != -1 means that
+ // the actual start/end position is (p+1). Start/end positions may
+ // become negative when the subexpression is in a RETokenLookBehind.
+ boolean empty; // empty string matched. This flag is used only within
+ // RETokenRepeated.
+
+ BacktrackStack backtrackStack;
+
+ public Object clone() {
+ try {
+ REMatch copy = (REMatch) super.clone();
+
+ copy.start = (int[]) start.clone();
+ copy.start1 = (int[]) start1.clone();
+ copy.end = (int[]) end.clone();
+
+ return copy;
+ } catch (CloneNotSupportedException e) {
+ throw new Error(); // doesn't happen
+ }
+ }
+
+ void assignFrom(REMatch other) {
+ start = other.start;
+ start1 = other.start1;
+ end = other.end;
+ index = other.index;
+ backtrackStack = other.backtrackStack;
+ }
+
+ REMatch(int subs, int anchor, int eflags) {
+ start = new int[subs+1];
+ start1 = 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();
+ matchedCharIndexed = text;
+ 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;
+ }
+ }
+ backtrackStack = null;
+ }
+
+ /** 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] = start1[i] = end[i] = -1;
+ }
+ backtrackStack = null;
+ }
+
+ /**
+ * Returns the string matching the pattern. This makes it convenient
+ * to write code like the following:
+ *
+ * REMatch myMatch = myExpression.getMatch(myString);
+ */
+ 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:
+ *
+ *
+ * if (myMatch != null) System.out.println("Regexp found: "+myMatch);
+ * REMatch myMatch = myExpression.getMatch(myString);
+ * String theMatch = myString.substring(myMatch.getStartIndex(),
+ * myMatch.getEndIndex());
+ * toString()
+ * 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) || sub < 0)
+ throw new IndexOutOfBoundsException("No group " + sub);
+ if (start[sub] == -1) return null;
+ if (start[sub] >= 0 && end[sub] <= matchedText.length())
+ return (matchedText.substring(start[sub],end[sub]));
+ else {
+ // This case occurs with RETokenLookAhead or RETokenLookBehind.
+ StringBuffer sb = new StringBuffer();
+ int s = start[sub];
+ int e = end[sub];
+ if (s < 0) s += 1;
+ if (e < 0) e += 1;
+ for (int i = start[0] + s; i < start[0] + e; i++)
+ sb.append(matchedCharIndexed.charAt(i));
+ return sb.toString();
+ }
+ }
+
+ /**
+ * Returns the index within the input string used to generate this match
+ * where subexpression number sub begins, or -1
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 :
+ (x >= 0) ? offset + x : offset + x + 1;
+ }
+
+ /**
+ * Returns the index within the input string used to generate this match
+ * where subexpression number sub begins, or -1
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 :
+ (x >= 0) ? offset + x : offset + x + 1;
+ }
+
+ /**
+ * Returns the index within the input string used to generate this match
+ * where subexpression number sub ends, or -1
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 :
+ (x >= 0) ? offset + x : offset + x + 1;
+ }
+
+ /**
+ * Returns the index within the input string used to generate this match
+ * where subexpression number sub ends, or -1
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 :
+ (x >= 0) ? offset + x : offset + x + 1;
+ }
+
+ /**
+ * Substitute the results of this match to create a new string.
+ * This is patterned after PERL, so the tokens to watch out for are
+ * $0
through $9
. $0
matches
+ * the full substring matched; $n
matches
+ * subexpression number n.
+ * $10, $11, ...
may match the 10th, 11th, ... subexpressions
+ * if such subexpressions exist.
+ *
+ * @param input A string consisting of literals and $n
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);
+ int pos1 = pos + 1;
+ while (pos1 < input.length() &&
+ Character.isDigit(input.charAt(pos1))) {
+ int val1 = val*10 + Character.digit(input.charAt(pos1),10);
+ if (val1 >= start.length) break;
+ pos1++;
+ val = val1;
+ }
+ pos = pos1 - 1;
+
+ 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();
+ }
+
+/* The following are used for debugging purpose
+ static String d(REMatch m) {
+ if (m == null) return "null";
+ else return "[" + m.index + "]";
+ }
+
+ String substringUptoIndex(CharIndexed input) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < index; i++) {
+ sb.append(input.charAt(i));
+ }
+ return sb.toString();
+ }
+*/
+
+}
diff --git a/libjava/classpath/gnu/java/util/regex/REMatchEnumeration.java b/libjava/classpath/gnu/java/util/regex/REMatchEnumeration.java
new file mode 100644
index 0000000..bc700be
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/REMatchEnumeration.java
@@ -0,0 +1,135 @@
+/* gnu/regexp/REMatchEnumeration.java
+ Copyright (C) 1998-2001, 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+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 getMatchEnumeration()
methods on an instance of
+ * RE.
+ *
+ * getAllMatches()
methods on RE. However, using an
+ * enumeration can help speed performance when the entire text does
+ * not need to be searched immediately.
+ *
+ * getMatch()
(see the
+ * description of that method for an explanation of why). Enumeration
+ * also saves a lot of overhead required when calling
+ * getMatch()
multiple times.
+ *
+ * @author Wes Biggs
+ */
+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();
+ }
+}
+
diff --git a/libjava/classpath/gnu/java/util/regex/RESyntax.java b/libjava/classpath/gnu/java/util/regex/RESyntax.java
new file mode 100644
index 0000000..b66b32f
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/RESyntax.java
@@ -0,0 +1,563 @@
+/* gnu/regexp/RESyntax.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.util.regex;
+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 Wes Biggs
+ */
+
+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.
+ * Not implemented.
+ */
+ public static final int RE_CONTEXT_INDEP_ANCHORS = 3;
+
+ /**
+ * Syntax bit. Repetition operators are only special in valid positions.
+ * Not implemented.
+ */
+ 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.
+ * Not implemented.
+ */
+ 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. Not implemented.
+ */
+ 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. Not implemented.
+ */
+ 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;
+
+ /**
+ * Syntax bit. Possessive matching is allowed (++, *+, ?+, {x,y}+).
+ */
+ public static final int RE_POSSESSIVE_OPS = 25;
+
+ /**
+ * Syntax bit. Allow embedded flags, (?is-x), as in Perl5.
+ */
+ public static final int RE_EMBEDDED_FLAGS = 26;
+
+ /**
+ * Syntax bit. Allow octal char (\0377), as in Perl5.
+ */
+ public static final int RE_OCTAL_CHAR = 27;
+
+ /**
+ * Syntax bit. Allow hex char (\x1b), as in Perl5.
+ */
+ public static final int RE_HEX_CHAR = 28;
+
+ /**
+ * Syntax bit. Allow Unicode char (\u1234), as in Java 1.4.
+ */
+ public static final int RE_UNICODE_CHAR = 29;
+
+ /**
+ * Syntax bit. Allow named property (\p{P}, \P{p}), as in Perl5.
+ */
+ public static final int RE_NAMED_PROPERTY = 30;
+
+ /**
+ * Syntax bit. Allow nested characterclass ([a-z&&[^p-r]]), as in Java 1.4.
+ */
+ public static final int RE_NESTED_CHARCLASS = 31;
+
+ private static final int BIT_TOTAL = 32;
+
+ /**
+ * 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;
+
+ /**
+ * Predefined syntax.
+ * Emulates regular expression support in Java 1.4's java.util.regex
+ * package.
+ */
+ public static final RESyntax RE_SYNTAX_JAVA_1_4;
+
+ 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) // (?#)
+ .set(RE_EMBEDDED_FLAGS) // (?imsx-imsx)
+ .set(RE_OCTAL_CHAR) // \0377
+ .set(RE_HEX_CHAR) // \x1b
+ .set(RE_NAMED_PROPERTY) // \p{prop}, \P{prop}
+ .makeFinal();
+
+ RE_SYNTAX_PERL5_S = new RESyntax(RE_SYNTAX_PERL5)
+ .set(RE_DOT_NEWLINE)
+ .makeFinal();
+
+ RE_SYNTAX_JAVA_1_4 = new RESyntax(RE_SYNTAX_PERL5)
+ // XXX
+ .set(RE_POSSESSIVE_OPS) // *+,?+,++,{}+
+ .set(RE_UNICODE_CHAR) // \u1234
+ .set(RE_NESTED_CHARCLASS) // [a-z&&[^p-r]]
+ .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;
+ }
+}
diff --git a/libjava/classpath/gnu/java/util/regex/REToken.java b/libjava/classpath/gnu/java/util/regex/REToken.java
new file mode 100644
index 0000000..155c018
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/REToken.java
@@ -0,0 +1,189 @@
+/* gnu/regexp/REToken.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.util.regex;
+import java.io.Serializable;
+
+abstract class REToken implements Serializable, Cloneable {
+
+ protected REToken next = null;
+ protected REToken uncle = null;
+ protected int subIndex;
+ protected boolean unicodeAware = true;
+
+ public Object clone() {
+ try {
+ REToken copy = (REToken) super.clone();
+ return copy;
+ } catch (CloneNotSupportedException e) {
+ throw new Error(); // doesn't happen
+ }
+ }
+
+ protected REToken(int subIndex) {
+ this.subIndex = subIndex;
+ }
+
+ int getMinimumLength() {
+ return 0;
+ }
+
+ int getMaximumLength() {
+ return Integer.MAX_VALUE;
+ }
+
+ void setUncle(REToken anUncle) {
+ uncle = anUncle;
+ }
+
+ /** Returns true if the match succeeded, false if it failed. */
+ boolean match(CharIndexed input, REMatch mymatch) {
+ REMatch m = matchThis(input, mymatch);
+ if (m == null) return false;
+ if (next(input, m)) {
+ mymatch.assignFrom(m);
+ return true;
+ }
+ return false;
+ }
+
+ /** Returns true if the match succeeded, false if it failed.
+ * The matching is done against this REToken only. Chained
+ * tokens are not checked.
+ * This method is used to define the default match method.
+ * Simple subclasses of REToken, for example, such that
+ * matches only one character, should implement this method.
+ * Then the default match method will work. But complicated
+ * subclasses of REToken, which needs a special match method,
+ * do not have to implement this method.
+ */
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ throw new UnsupportedOperationException(
+ "This REToken does not have a matchThis method");
+ }
+
+ /** Returns true if the rest of the tokens match, false if they fail. */
+ protected boolean next(CharIndexed input, REMatch mymatch) {
+ REToken nextToken = getNext();
+ if (nextToken == null) return true;
+ return nextToken.match(input, mymatch);
+ }
+
+ /** Returns the next REToken chained to this REToken. */
+ REToken getNext() {
+ return (next != null ? next : uncle);
+ }
+
+ /** Finds a match at the position specified by the given REMatch.
+ * If necessary, adds a BacktrackStack.Backtrack object to backtrackStack
+ * of the REmatch found this time so that another possible match
+ * may be found when backtrack is called.
+ * By default, nothing is added to the backtrackStack.
+ * @param CharIndexed input Input character sequence.
+ * @param mymatch Position at which a match should be found
+ * @return REMatch object if a match was found, null otherwise.
+ */
+ REMatch findMatch(CharIndexed input, REMatch mymatch) {
+ boolean b = match(input, mymatch);
+ if (b) return mymatch;
+ return null;
+ }
+
+ boolean returnsFixedLengthMatches() {
+ return false;
+ }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ throw new UnsupportedOperationException(
+ "This token does not support findFixedLengthMatches");
+ }
+
+ /**
+ * Backtrack to another possibility.
+ * Ordinary REToken cannot do anything if this method is called.
+ */
+ REMatch backtrack(CharIndexed input, REMatch mymatch, Object param) {
+ throw new IllegalStateException("This token cannot be backtracked to");
+ }
+
+ 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);
+ }
+
+ public String toString() {
+ StringBuffer os = new StringBuffer();
+ dump(os);
+ return os.toString();
+ }
+
+ /**
+ * Converts the character argument to lowercase.
+ * @param ch the character to be converted.
+ * @param unicodeAware If true, use java.lang.Character#toLowerCase;
+ * otherwise, only US-ASCII charactes can be converted.
+ * @return the lowercase equivalent of the character, if any;
+ * otherwise, the character itself.
+ */
+ public static char toLowerCase(char ch, boolean unicodeAware) {
+ if (unicodeAware) return Character.toLowerCase(ch);
+ if (ch >= 'A' && ch <= 'Z') return (char)(ch + 'a' - 'A');
+ return ch;
+ }
+
+ /**
+ * Converts the character argument to uppercase.
+ * @param ch the character to be converted.
+ * @param unicodeAware If true, use java.lang.Character#toUpperCase;
+ * otherwise, only US-ASCII charactes can be converted.
+ * @return the uppercase equivalent of the character, if any;
+ * otherwise, the character itself.
+ */
+ public static char toUpperCase(char ch, boolean unicodeAware) {
+ if (unicodeAware) return Character.toUpperCase(ch);
+ if (ch >= 'a' && ch <= 'z') return (char)(ch + 'A' - 'a');
+ return ch;
+ }
+
+}
diff --git a/libjava/classpath/gnu/java/util/regex/RETokenAny.java b/libjava/classpath/gnu/java/util/regex/RETokenAny.java
new file mode 100644
index 0000000..b99a547
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/RETokenAny.java
@@ -0,0 +1,99 @@
+/* gnu/regexp/RETokenAny.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.util.regex;
+
+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;
+ }
+
+ int getMaximumLength() {
+ return 1;
+ }
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ char ch = input.charAt(mymatch.index);
+ boolean retval = matchOneChar(ch);
+ if (retval) {
+ ++mymatch.index;
+ return mymatch;
+ }
+ return null;
+ }
+
+ boolean matchOneChar(char ch) {
+ if ((ch == CharIndexed.OUT_OF_BOUNDS)
+ || (!newline && (ch == '\n'))
+ || (matchNull && (ch == 0))) {
+ return false;
+ }
+ return true;
+ }
+
+ boolean returnsFixedLengthMatches() { return true; }
+
+ int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
+ int index = mymatch.index;
+ int numRepeats = 0;
+ while (true) {
+ if (numRepeats >= max) break;
+ char ch = input.charAt(index++);
+ if (! matchOneChar(ch)) break;
+ numRepeats++;
+ }
+ return numRepeats;
+ }
+
+ void dump(StringBuffer os) {
+ os.append('.');
+ }
+}
+
diff --git a/libjava/classpath/gnu/java/util/regex/RETokenBackRef.java b/libjava/classpath/gnu/java/util/regex/RETokenBackRef.java
new file mode 100644
index 0000000..3a912f9
--- /dev/null
+++ b/libjava/classpath/gnu/java/util/regex/RETokenBackRef.java
@@ -0,0 +1,86 @@
+/* gnu/regexp/RETokenBackRef.java
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.java.util.regex;
+
+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?
+
+ REMatch matchThis(CharIndexed input, REMatch mymatch) {
+ if (num >= mymatch.start.length) return null;
+ if (num >= mymatch.end.length) return null;
+ int b,e;
+ b = mymatch.start[num];
+ e = mymatch.end[num];
+ if ((b==-1)||(e==-1)) return null; // this shouldn't happen, but...
+ if (b < 0) b += 1;
+ if (e < 0) e += 1;
+ for (int i=b; iAssembly
is a construction consisting of a chain of
+ * An Assembly
is a construction consisting of a chain of
* {@link Transformer} elements; each wired in pre- or post- transformation
* mode. This chain is terminated by one LoopbackTransformer
- * element.Assembly
are delegated to the head
- * of the {@link Transformer} chain of the Assembly
.Assembly
are delegated to the head of
+ * the {@link Transformer} chain of the Assembly
.
+ *
* @see Transformer
*/
public class Assembly
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String DIRECTION = "gnu.crypto.assembly.assembly.direction";
/** Flag that tells if the instance is initialised or not; and if yes how. */
@@ -66,9 +62,6 @@ public class Assembly
/** The first Transformer in the chain. */
private Transformer head;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Trivial constructor that sets the chain to a
* LoopbackTransformer
.
@@ -81,21 +74,15 @@ public class Assembly
head = new LoopbackTransformer();
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
* Adds the designated {@link Transformer} and signals that it should operate
* in pre-processing mode; i.e. it should apply its internal transformation
* algorithm on the input data stream, before it passes that stream to
* the next element in the chain.
- *
+ *
* @param t the {@link Transformer} to add at the head of the current chain.
- * @throws IllegalArgumentException if the designated {@link Transformer}
- * has a non-null tail; i.e. it is already an element of a chain.
+ * @throws IllegalArgumentException if the designated {@link Transformer} has
+ * a non-null tail; i.e. it is already an element of a chain.
*/
public void addPreTransformer(Transformer t)
{
@@ -107,10 +94,10 @@ public class Assembly
* in post-processing mode; i.e. it should apply its internal transformation
* algorithm on the input data stream, after it passes that stream to
* the next element in the chain.
- *
+ *
* @param t the {@link Transformer} to add at the head of the current chain.
- * @throws IllegalArgumentException if the designated {@link Transformer}
- * has a non-null tail; i.e. it is already an element of a chain.
+ * @throws IllegalArgumentException if the designated {@link Transformer} has
+ * a non-null tail; i.e. it is already an element of a chain.
*/
public void addPostTransformer(Transformer t)
{
@@ -120,22 +107,18 @@ public class Assembly
/**
* Initialises the Assembly
for operation with specific
* characteristics.
- *
+ *
* @param attributes a set of name-value pairs that describes the desired
- * future behaviour of this instance.
+ * future behaviour of this instance.
* @throws IllegalStateException if the instance is already initialised.
*/
public void init(Map attributes) throws TransformerException
{
if (wired != null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
Direction flow = (Direction) attributes.get(DIRECTION);
if (flow == null)
- {
- flow = Direction.FORWARD;
- }
+ flow = Direction.FORWARD;
attributes.put(Transformer.DIRECTION, flow);
head.init(attributes);
wired = flow;
@@ -155,12 +138,12 @@ public class Assembly
* Convenience method that calls the method with same name and three
* arguments, using a byte array of length 1
whose contents are
* the designated byte.
- *
+ *
* @param b the byte to process.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #update(byte[], int, int)
*/
public byte[] update(byte b) throws TransformerException
@@ -172,12 +155,12 @@ public class Assembly
* Convenience method that calls the method with same name and three
* arguments. All bytes in in
, starting from index position
* 0
are considered.
- *
+ *
* @param in the input data bytes.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #update(byte[], int, int)
*/
public byte[] update(byte[] in) throws TransformerException
@@ -187,34 +170,32 @@ public class Assembly
/**
* Processes a designated number of bytes from a given byte array.
- *
+ *
* @param in the input data bytes.
* @param offset index of in
from which to start considering
- * data.
+ * data.
* @param length the count of bytes to process.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
*/
public byte[] update(byte[] in, int offset, int length)
throws TransformerException
{
if (wired == null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
return head.update(in, offset, length);
}
/**
- * Convenience method that calls the method with same name and three
- * arguments using a 0-long byte array.
- *
+ * Convenience method that calls the method with same name and three arguments
+ * using a 0-long byte array.
+ *
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #lastUpdate(byte[], int, int)
*/
public byte[] lastUpdate() throws TransformerException
@@ -226,12 +207,12 @@ public class Assembly
* Convenience method that calls the method with same name and three
* arguments, using a byte array of length 1
whose contents are
* the designated byte.
- *
+ *
* @param b the byte to process.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #lastUpdate(byte[], int, int)
*/
public byte[] lastUpdate(byte b) throws TransformerException
@@ -243,12 +224,12 @@ public class Assembly
* Convenience method that calls the method with same name and three
* arguments. All bytes in in
, starting from index position
* 0
are considered.
- *
+ *
* @param in the input data bytes.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #lastUpdate(byte[], int, int)
*/
public byte[] lastUpdate(byte[] in) throws TransformerException
@@ -257,39 +238,33 @@ public class Assembly
}
/**
- * Processes a designated number of bytes from a given byte array and
- * signals, at the same time, that this is the last push operation for
- * this Assembly
.
- *
+ * Processes a designated number of bytes from a given byte array and signals,
+ * at the same time, that this is the last push operation for this
+ * Assembly
.
+ *
* @param in the input data bytes.
* @param offset index of in
from which to start considering
- * data.
+ * data.
* @param length the count of bytes to process.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
- * @throws TransformerException if a transformation-related exception
- * occurs during the operation.
+ * @throws TransformerException if a transformation-related exception occurs
+ * during the operation.
*/
public byte[] lastUpdate(byte[] in, int offset, int length)
throws TransformerException
{
if (wired == null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
byte[] result = head.lastUpdate(in, offset, length);
reset();
return result;
}
- // helper methods ----------------------------------------------------------
-
private void wireTransformer(Transformer t, Operation mode)
{
if (t.tail != null)
- {
- throw new IllegalArgumentException();
- }
+ throw new IllegalArgumentException();
t.setMode(mode);
t.tail = head;
head = t;
diff --git a/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java b/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java
index 678a7e7..f790956 100644
--- a/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java
+++ b/libjava/classpath/gnu/javax/crypto/assembly/Cascade.java
@@ -49,36 +49,31 @@ import java.util.Map;
import java.util.Set;
/**
- * i
is input to stage i + 1
; and the output
- * of the last stage is the Cascade's ciphertext output.Cascade
have k-bit
+ * of stage i
is input to stage i + 1
; and the
+ * output of the last stage is the Cascade's ciphertext output.
+ * Cascade
have k-bit
* keys, and the stage inputs and outputs are all n-bit quantities. The stage
* ciphers may differ (general cascade of ciphers), or all be identical (cascade
- * of identical ciphers).
- *
*/
public class Cascade
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String DIRECTION = "gnu.crypto.assembly.cascade.direction";
/** The map of Stages chained in this cascade. */
@@ -93,9 +88,6 @@ public class Cascade
/** The curently set block-size for this instance. */
protected int blockSize;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public Cascade()
{
super();
@@ -106,12 +98,9 @@ public class Cascade
blockSize = 0;
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
* Returns the Least Common Multiple of two integers.
- *
+ *
* @param a the first integer.
* @param b the second integer.
* @return the LCM of
- * CRC Press, Inc. ISBN 0-8493-8523-7, 1997
- * Menezes, A., van Oorschot, P. and S. Vanstone.
+ * CRC Press, Inc. ISBN 0-8493-8523-7, 1997
+ * Menezes, A., van Oorschot, P. and S. Vanstone.abs(a)
and abs(b)
.
@@ -123,18 +112,15 @@ public class Cascade
return A.multiply(B).divide(A.gcd(B)).abs().intValue();
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
* Adds to the end of the current chain, a designated {@link Stage}.
- *
+ *
* @param stage the {@link Stage} to append to the chain.
* @return a unique identifier for this stage, within this cascade.
* @throws IllegalStateException if the instance is already initialised.
- * @throws IllegalArgumentException if the designated stage is already in
- * the chain, or it has incompatible characteristics with the current
- * elements already in the chain.
+ * @throws IllegalArgumentException if the designated stage is already in the
+ * chain, or it has incompatible characteristics with the current
+ * elements already in the chain.
*/
public Object append(Stage stage) throws IllegalArgumentException
{
@@ -143,13 +129,13 @@ public class Cascade
/**
* Adds to the begining of the current chain, a designated {@link Stage}.
- *
+ *
* @param stage the {@link Stage} to prepend to the chain.
* @return a unique identifier for this stage, within this cascade.
* @throws IllegalStateException if the instance is already initialised.
- * @throws IllegalArgumentException if the designated stage is already in
- * the chain, or it has incompatible characteristics with the current
- * elements already in the chain.
+ * @throws IllegalArgumentException if the designated stage is already in the
+ * chain, or it has incompatible characteristics with the current
+ * elements already in the chain.
*/
public Object prepend(Stage stage) throws IllegalArgumentException
{
@@ -159,62 +145,49 @@ public class Cascade
/**
* Inserts a {@link Stage} into the current chain, at the specified index
* (zero-based) position.
- *
+ *
* @param stage the {@link Stage} to insert into the chain.
* @return a unique identifier for this stage, within this cascade.
- * @throws IllegalArgumentException if the designated stage is already in
- * the chain, or it has incompatible characteristics with the current
- * elements already in the chain.
+ * @throws IllegalArgumentException if the designated stage is already in the
+ * chain, or it has incompatible characteristics with the current
+ * elements already in the chain.
* @throws IllegalStateException if the instance is already initialised.
* @throws IndexOutOfBoundsException if index
is less than
- * 0
or greater than the current size of this cascade.
+ * 0
or greater than the current size of this
+ * cascade.
*/
public Object insert(int index, Stage stage) throws IllegalArgumentException,
IndexOutOfBoundsException
{
if (stages.containsValue(stage))
- {
- throw new IllegalArgumentException();
- }
+ throw new IllegalArgumentException();
if (wired != null || stage == null)
- {
- throw new IllegalStateException();
- }
-
+ throw new IllegalStateException();
if (index < 0 || index > size())
- {
- throw new IndexOutOfBoundsException();
- }
-
+ throw new IndexOutOfBoundsException();
// check that there is a non-empty set of common block-sizes
Set set = stage.blockSizes();
if (stages.isEmpty())
{
if (set.isEmpty())
- {
- throw new IllegalArgumentException("1st stage with no block sizes");
- }
+ throw new IllegalArgumentException("1st stage with no block sizes");
}
else
{
Set common = this.blockSizes();
common.retainAll(set);
if (common.isEmpty())
- {
- throw new IllegalArgumentException("no common block sizes found");
- }
+ throw new IllegalArgumentException("no common block sizes found");
}
-
Object result = new Object();
stageKeys.add(index, result);
stages.put(result, stage);
-
return result;
}
/**
* Returns the current number of stages in this chain.
- *
+ *
* @return the current count of stages in this chain.
*/
public int size()
@@ -226,18 +199,16 @@ public class Cascade
* Returns an {@link Iterator} over the stages contained in this instance.
* Each element of this iterator is a concrete implementation of a {@link
* Stage}.
- *
+ *
* @return an {@link Iterator} over the stages contained in this instance.
- * Each element of the returned iterator is a concrete instance of a {@link
- * Stage}.
+ * Each element of the returned iterator is a concrete instance of a
+ * {@link Stage}.
*/
public Iterator stages()
{
LinkedList result = new LinkedList();
for (Iterator it = stageKeys.listIterator(); it.hasNext();)
- {
- result.addLast(stages.get(it.next()));
- }
+ result.addLast(stages.get(it.next()));
return result.listIterator();
}
@@ -245,9 +216,9 @@ public class Cascade
* Returns the {@link Set} of supported block sizes for this
* Cascade
that are common to all of its chained stages. Each
* element in the returned {@link Set} is an instance of {@link Integer}.
- *
- * @return a {@link Set} of supported block sizes common to all the stages
- * of the chain.
+ *
+ * @return a {@link Set} of supported block sizes common to all the stages of
+ * the chain.
*/
public Set blockSizes()
{
@@ -255,42 +226,33 @@ public class Cascade
for (Iterator it = stages.values().iterator(); it.hasNext();)
{
Stage aStage = (Stage) it.next();
- if (result == null)
- { // first time
- result = new HashSet(aStage.blockSizes());
- }
+ if (result == null) // first time
+ result = new HashSet(aStage.blockSizes());
else
- {
- result.retainAll(aStage.blockSizes());
- }
+ result.retainAll(aStage.blockSizes());
}
return result == null ? Collections.EMPTY_SET : result;
}
/**
* Initialises the chain for operation with specific characteristics.
- *
+ *
* @param attributes a set of name-value pairs that describes the desired
- * future behaviour of this instance.
+ * future behaviour of this instance.
* @throws IllegalStateException if the chain, or any of its stages, is
- * already initialised.
+ * already initialised.
* @throws InvalidKeyException if the intialisation data provided with the
- * stage is incorrect or causes an invalid key to be generated.
+ * stage is incorrect or causes an invalid key to be generated.
* @see Direction#FORWARD
* @see Direction#REVERSED
*/
public void init(Map attributes) throws InvalidKeyException
{
if (wired != null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
Direction flow = (Direction) attributes.get(DIRECTION);
if (flow == null)
- {
- flow = Direction.FORWARD;
- }
-
+ flow = Direction.FORWARD;
int optimalSize = 0;
for (Iterator it = stageKeys.listIterator(); it.hasNext();)
{
@@ -300,30 +262,25 @@ public class Cascade
Stage stage = (Stage) stages.get(id);
stage.init(attr);
optimalSize = optimalSize == 0 ? stage.currentBlockSize()
- : lcm(optimalSize,
- stage.currentBlockSize());
- }
-
- if (flow == Direction.REVERSED)
- { // reverse order
- Collections.reverse(stageKeys);
+ : lcm(optimalSize,
+ stage.currentBlockSize());
}
+ if (flow == Direction.REVERSED) // reverse order
+ Collections.reverse(stageKeys);
wired = flow;
blockSize = optimalSize;
}
/**
* Returns the currently set block size for the chain.
- *
+ *
* @return the current block size for the chain.
* @throws IllegalStateException if the instance is not initialised.
*/
public int currentBlockSize()
{
if (wired == null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
return blockSize;
}
@@ -334,25 +291,21 @@ public class Cascade
public void reset()
{
for (Iterator it = stageKeys.listIterator(); it.hasNext();)
- {
- ((Stage) stages.get(it.next())).reset();
- }
- if (wired == Direction.REVERSED)
- { // reverse it back
- Collections.reverse(stageKeys);
- }
+ ((Stage) stages.get(it.next())).reset();
+ if (wired == Direction.REVERSED) // reverse it back
+ Collections.reverse(stageKeys);
wired = null;
blockSize = 0;
}
/**
* Processes exactly one block of plaintext (if initialised in the
- * {@link Direction#FORWARD} state) or ciphertext (if initialised in the
- * {@link Direction#REVERSED} state).
- *
+ * {@link Direction#FORWARD} state) or ciphertext (if initialised in
+ * the {@link Direction#REVERSED} state).
+ *
* @param in the plaintext.
* @param inOffset index of in
from which to start considering
- * data.
+ * data.
* @param out the ciphertext.
* @param outOffset index of out
from which to store result.
* @throws IllegalStateException if the instance is not initialised.
@@ -360,23 +313,17 @@ public class Cascade
public void update(byte[] in, int inOffset, byte[] out, int outOffset)
{
if (wired == null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
int stageBlockSize, j, i = stages.size();
for (Iterator it = stageKeys.listIterator(); it.hasNext();)
{
Stage stage = (Stage) stages.get(it.next());
stageBlockSize = stage.currentBlockSize();
for (j = 0; j < blockSize; j += stageBlockSize)
- {
- stage.update(in, inOffset + j, out, outOffset + j);
- }
+ stage.update(in, inOffset + j, out, outOffset + j);
i--;
if (i > 0)
- {
- System.arraycopy(out, outOffset, in, inOffset, blockSize);
- }
+ System.arraycopy(out, outOffset, in, inOffset, blockSize);
}
}
@@ -385,18 +332,16 @@ public class Cascade
* encryption / decryption test(s) for all supported block and key sizes of
* underlying block cipher(s) wrapped by Mode leafs. The test also includes
* one (1) variable key Known Answer Test (KAT) for each block cipher.
- *
+ *
* @return true
if the implementation passes simple
- * correctness tests. Returns false
otherwise.
+ * correctness tests. Returns false
otherwise.
*/
public boolean selfTest()
{
for (Iterator it = stageKeys.listIterator(); it.hasNext();)
{
- if (!((Stage) stages.get(it.next())).selfTest())
- {
- return false;
- }
+ if (! ((Stage) stages.get(it.next())).selfTest())
+ return false;
}
return true;
}
diff --git a/libjava/classpath/gnu/javax/crypto/assembly/CascadeStage.java b/libjava/classpath/gnu/javax/crypto/assembly/CascadeStage.java
index 81629f5..b86f42e 100644
--- a/libjava/classpath/gnu/javax/crypto/assembly/CascadeStage.java
+++ b/libjava/classpath/gnu/javax/crypto/assembly/CascadeStage.java
@@ -44,19 +44,13 @@ import java.util.Map;
import java.util.Set;
/**
- *
- *
*/
public final class Direction
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final Direction FORWARD = new Direction(1);
public static final Direction REVERSED = new Direction(2);
private int value;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
private Direction(int value)
{
super();
@@ -72,17 +66,11 @@ public final class Direction
this.value = value;
}
- // Class methods
- // -------------------------------------------------------------------------
-
public static final Direction reverse(Direction d)
{
return (d.equals(FORWARD) ? REVERSED : FORWARD);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
public String toString()
{
return (this == FORWARD ? "forward" : "reversed");
diff --git a/libjava/classpath/gnu/javax/crypto/assembly/LoopbackTransformer.java b/libjava/classpath/gnu/javax/crypto/assembly/LoopbackTransformer.java
index 3c0bdfa..bba1da7 100644
--- a/libjava/classpath/gnu/javax/crypto/assembly/LoopbackTransformer.java
+++ b/libjava/classpath/gnu/javax/crypto/assembly/LoopbackTransformer.java
@@ -44,27 +44,15 @@ import java.util.Map;
* A trivial {@link Transformer} to allow closing a chain in an {@link Assembly}.
* This class is not visible outside this package.
*/
-final class LoopbackTransformer extends Transformer
+final class LoopbackTransformer
+ extends Transformer
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
- /** Trivial protected constructor. */
+ /** Trivial package-private constructor. */
LoopbackTransformer()
{
super();
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
public void init(Map attributes) throws TransformerException
{
}
@@ -84,8 +72,6 @@ final class LoopbackTransformer extends Transformer
return lastUpdateDelegate();
}
- // abstract methods to be implemented by concrete subclasses ---------------
-
void initDelegate(Map attributes) throws TransformerException
{
}
diff --git a/libjava/classpath/gnu/javax/crypto/assembly/ModeStage.java b/libjava/classpath/gnu/javax/crypto/assembly/ModeStage.java
index 1143348..253ab4a 100644
--- a/libjava/classpath/gnu/javax/crypto/assembly/ModeStage.java
+++ b/libjava/classpath/gnu/javax/crypto/assembly/ModeStage.java
@@ -48,25 +48,19 @@ import java.util.Map;
import java.util.Set;
/**
- *
- *
*/
public final class Operation
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final Operation PRE_PROCESSING = new Operation(1);
public static final Operation POST_PROCESSING = new Operation(2);
private int value;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
private Operation(int value)
{
super();
@@ -74,12 +66,6 @@ public final class Operation
this.value = value;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
public String toString()
{
return (this == PRE_PROCESSING ? "pre-processing" : "post-processing");
diff --git a/libjava/classpath/gnu/javax/crypto/assembly/PaddingTransformer.java b/libjava/classpath/gnu/javax/crypto/assembly/PaddingTransformer.java
index c63f92e..c11f4fe 100644
--- a/libjava/classpath/gnu/javax/crypto/assembly/PaddingTransformer.java
+++ b/libjava/classpath/gnu/javax/crypto/assembly/PaddingTransformer.java
@@ -44,26 +44,20 @@ import gnu.javax.crypto.pad.WrongPaddingException;
import java.util.Map;
/**
- *
- * FORWARD FORWARD
- * +------+ +-------+
- * | | | |
- * | +--in --+ | +--in --+
- * ---+ | Stage | | | Stage | +---
- * +--out--+ | +--out--+ |
- * | | | |
- * +-------+ +------+
+ * FORWARD FORWARD
+ * +------+ +-------+
+ * | | | |
+ * | +--in --+ | +--in --+
+ * ---+ | Stage | | | Stage | +---
+ * +--out--+ | +--out--+ |
+ * | | | |
+ * +-------+ +------+
*
- *
- * FORWARD REVERSED
- * +------+ +------+
- * | | | |
- * | +--in --+ +--in --+ |
- * ---+ | Stage | | Stage | +---
- * +--out--+ +--out--+
- * | |
- * +---------------+
+ * FORWARD REVERSED
+ * +------+ +------+
+ * | | | |
+ * | +--in --+ +--in --+ |
+ * ---+ | Stage | | Stage | +---
+ * +--out--+ +--out--+
+ * | |
+ * +---------------+
*
- *
+ *
* @see ModeStage
* @see CascadeStage
*/
public abstract class Stage
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String DIRECTION = "gnu.crypto.assembly.stage.direction";
protected Direction forward;
protected Direction wired;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
protected Stage(Direction forwardDirection)
{
super();
@@ -106,9 +103,6 @@ public abstract class Stage
this.wired = null;
}
- // Class methods
- // -------------------------------------------------------------------------
-
public static final Stage getInstance(IMode mode, Direction forwardDirection)
{
return new ModeStage(mode, forwardDirection);
@@ -120,32 +114,27 @@ public abstract class Stage
return new CascadeStage(cascade, forwardDirection);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
* Returns the {@link Set} of supported block sizes for this
* Stage
. Each element in the returned {@link Set} is an
* instance of {@link Integer}.
- *
+ *
* @return a {@link Set} of supported block sizes.
*/
public abstract Set blockSizes();
/**
* Initialises the stage for operation with specific characteristics.
- *
+ *
* @param attributes a set of name-value pairs that describes the desired
- * future behaviour of this instance.
+ * future behaviour of this instance.
* @throws IllegalStateException if the instance is already initialised.
* @throws InvalidKeyException if the key data is invalid.
*/
public void init(Map attributes) throws InvalidKeyException
{
if (wired != null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
Direction flow = (Direction) attributes.get(DIRECTION);
if (flow == null)
{
@@ -158,7 +147,7 @@ public abstract class Stage
/**
* Returns the currently set block size for the stage.
- *
+ *
* @return the current block size for this stage.
* @throws IllegalStateException if the instance is not initialised.
*/
@@ -178,10 +167,10 @@ public abstract class Stage
* Processes exactly one block of plaintext (if initialised in the
* {@link Direction#FORWARD} state) or ciphertext (if initialised in
* the {@link Direction#REVERSED} state).
- *
+ *
* @param in the plaintext.
* @param inOffset index of in
from which to start considering
- * data.
+ * data.
* @param out the ciphertext.
* @param outOffset index of out
from which to store result.
* @throws IllegalStateException if the instance is not initialised.
@@ -189,9 +178,7 @@ public abstract class Stage
public void update(byte[] in, int inOffset, byte[] out, int outOffset)
{
if (wired == null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
updateDelegate(in, inOffset, out, outOffset);
}
@@ -200,14 +187,12 @@ public abstract class Stage
* encryption / decryption test(s) for all supported block and key sizes of
* underlying block cipher(s) wrapped by Mode leafs. The test also includes
* one (1) variable key Known Answer Test (KAT) for each block cipher.
- *
+ *
* @return true
if the implementation passes simple
- * correctness tests. Returns false
otherwise.
+ * correctness tests. Returns false
otherwise.
*/
public abstract boolean selfTest();
- // abstract methods to be implemented by concrete subclasses ---------------
-
abstract void initDelegate(Map attributes) throws InvalidKeyException;
abstract void resetDelegate();
diff --git a/libjava/classpath/gnu/javax/crypto/assembly/Transformer.java b/libjava/classpath/gnu/javax/crypto/assembly/Transformer.java
index 80430dc..58a991b 100644
--- a/libjava/classpath/gnu/javax/crypto/assembly/Transformer.java
+++ b/libjava/classpath/gnu/javax/crypto/assembly/Transformer.java
@@ -44,50 +44,44 @@ import java.io.ByteArrayOutputStream;
import java.util.Map;
/**
- * Transformer
is an abstract representation of a two-way
+ * A Transformer
is an abstract representation of a two-way
* transformation that can be chained together with other instances of
* this type. Examples of such transformations in this library are:
- * {@link Cascade} cipher, {@link gnu.crypto.pad.IPad} algorithm, and a
+ * {@link Cascade} cipher, {@link gnu.javax.crypto.pad.IPad} algorithm, and a
* ZLib-based deflater/inflater algorithm. A special implementation of a
- * Transformer
to close a chain is also provided.Transformer
is characterised by the followings:Transformer
to close a chain is also provided.
+ * Transformer
is characterised by the followings:
*
- *
- *
- * Transformer
can be used as
- * either in pre-processing or a post-processing modes.LoopbackTransformer
-- is used to
- * close the chain.Transformer
--one we're interested in--
- * has internal buffers. The distinction between a casual push (update)
- * operation and the last one allows to correctly flush any intermediate
- * bytes that may exist in those buffers.Transformer
can be used as
+ * either in pre-processing or a post-processing modes.LoopbackTransformer
-- is used
+ * to close the chain.Transformer
--one we're interested in--
+ * has internal buffers. The distinction between a casual push (update)
+ * operation and the last one allows to correctly flush any intermediate bytes
+ * that may exist in those buffers.Transformer
instances together, a
+ * Transformer
instances together, a
* minimal-output-size in bytes is necessary. The trivial case of a
* value of 1
for such attribute practically means that no output
* buffering, from the previous element, is needed --which is independant of
- * buffering the input if the Transformer
implementation itself is
- * block-based.Transformer
implementation itself
+ * is block-based.
+ *
* @see CascadeTransformer
* @see PaddingTransformer
* @see DeflateTransformer
*/
public abstract class Transformer
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String DIRECTION = "gnu.crypto.assembly.transformer.direction";
- // public static final String MODE = "gnu.crypto.assembly.transformer.mode";
-
protected Direction wired;
protected Operation mode;
@@ -98,9 +92,6 @@ public abstract class Transformer
protected ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(2048);
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial protected constructor. */
protected Transformer()
{
@@ -109,9 +100,6 @@ public abstract class Transformer
this.wired = null;
}
- // Class methods
- // -------------------------------------------------------------------------
-
public static final Transformer getCascadeTransformer(Cascade cascade)
{
return new CascadeTransformer(cascade);
@@ -127,81 +115,69 @@ public abstract class Transformer
return new DeflateTransformer();
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
* Sets the operational mode of this Transformer
.
- *
+ *
* @param mode the processing mode this Transformer
is required
- * to operate in.
- * @throws IllegalStateException if this instance has already been assigned
- * an operational mode.
+ * to operate in.
+ * @throws IllegalStateException if this instance has already been assigned an
+ * operational mode.
*/
public void setMode(final Operation mode)
{
if (this.mode != null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
this.mode = mode;
}
/**
* Returns true
if this Transformer
was wired in
* pre-processing mode; false
otherwise.
- *
- * @return true
if this Transformer
has been wired
- * in pre-processing mode; false
otherwise.
- * @throws IllegalStateException if this instance has not yet been assigned
- * an operational type.
+ *
+ * @return true
if this Transformer
has been
+ * wired in pre-processing mode; false
otherwise.
+ * @throws IllegalStateException if this instance has not yet been assigned an
+ * operational type.
*/
public boolean isPreProcessing()
{
if (mode == null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
return (mode == Operation.PRE_PROCESSING);
}
/**
* Returns true
if this Transformer
was wired in
* post-processing mode; false
otherwise.
- *
- * @return true
if this Transformer
has been wired
- * in post-processing mode; false
otherwise.
- * @throws IllegalStateException if this instance has not yet been assigned
- * an operational type.
+ *
+ * @return true
if this Transformer
has been
+ * wired in post-processing mode; false
otherwise.
+ * @throws IllegalStateException if this instance has not yet been assigned an
+ * operational type.
*/
public boolean isPostProcessing()
{
- return !isPreProcessing();
+ return ! isPreProcessing();
}
/**
* Initialises the Transformer
for operation with specific
* characteristics.
- *
+ *
* @param attributes a set of name-value pairs that describes the desired
- * future behaviour of this instance.
+ * future behaviour of this instance.
* @throws IllegalStateException if the instance is already initialised.
*/
public void init(Map attributes) throws TransformerException
{
if (wired != null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
Direction flow = (Direction) attributes.get(DIRECTION);
if (flow == null)
- {
- flow = Direction.FORWARD;
- }
+ flow = Direction.FORWARD;
wired = flow;
inBuffer.reset();
outBuffer.reset();
-
tail.init(attributes); // initialise tail first
initDelegate(attributes); // initialise this instance
}
@@ -209,15 +185,13 @@ public abstract class Transformer
/**
* Returns the block-size of this Transformer
. A value of
* 1
indicates that this instance is block-agnostic.
- *
+ *
* @return the current minimal required block size.
*/
public int currentBlockSize()
{
if (wired == null)
- {
- throw new IllegalStateException();
- }
+ throw new IllegalStateException();
return delegateBlockSize();
}
@@ -238,12 +212,12 @@ public abstract class Transformer
* Convenience method that calls the method with same name and three
* arguments, using a byte array of length 1
whose contents are
* the designated byte.
- *
+ *
* @param b the byte to process.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #update(byte[], int, int)
*/
public byte[] update(byte b) throws TransformerException
@@ -253,14 +227,14 @@ public abstract class Transformer
/**
* Convenience method that calls the same method with three arguments. All
- * bytes in in
, starting from index position 0
are
- * considered.
- *
+ * bytes in in
, starting from index position 0
+ * are considered.
+ *
* @param in the input data bytes.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #update(byte[], int, int)
*/
public byte[] update(byte[] in) throws TransformerException
@@ -270,48 +244,42 @@ public abstract class Transformer
/**
* Processes a designated number of bytes from a given byte array.
- *
+ *
* @param in the input data bytes.
* @param offset index of in
from which to start considering
- * data.
+ * data.
* @param length the count of bytes to process.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
*/
public byte[] update(byte[] in, int offset, int length)
throws TransformerException
{
if (wired == null)
- {
- throw new IllegalStateException();
- }
- byte[] result = (wired == Direction.FORWARD ? forwardUpdate(in, offset,
- length)
- : inverseUpdate(in, offset,
- length));
+ throw new IllegalStateException();
+ byte[] result = (wired == Direction.FORWARD ? forwardUpdate(in, offset, length)
+ : inverseUpdate(in, offset, length));
return result;
}
/**
* Convenience method that calls the same method with three arguments. A
* zero-long byte array is used.
- *
+ *
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #lastUpdate(byte[], int, int)
*/
public byte[] lastUpdate() throws TransformerException
{
byte[] result = (wired == Direction.FORWARD ? lastForwardUpdate()
- : lastInverseUpdate());
- if (inBuffer.size() != 0)
- { // we still have some buffered bytes
- throw new TransformerException("lastUpdate(): input buffer not empty");
- }
+ : lastInverseUpdate());
+ if (inBuffer.size() != 0) // we still have some buffered bytes
+ throw new TransformerException("lastUpdate(): input buffer not empty");
return result;
}
@@ -319,12 +287,12 @@ public abstract class Transformer
* Convenience method that calls the method with same name and three
* arguments, using a byte array of length 1
whose contents are
* the designated byte.
- *
+ *
* @param b the byte to process.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #lastUpdate(byte[], int, int)
*/
public byte[] lastUpdate(byte b) throws TransformerException
@@ -334,14 +302,14 @@ public abstract class Transformer
/**
* Convenience method that calls the same method with three arguments. All
- * bytes in in
, starting from index position 0
are
- * considered.
- *
+ * bytes in in
, starting from index position 0
+ * are considered.
+ *
* @param in the input data bytes.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
* @see #lastUpdate(byte[], int, int)
*/
public byte[] lastUpdate(byte[] in) throws TransformerException
@@ -350,18 +318,18 @@ public abstract class Transformer
}
/**
- * Processes a designated number of bytes from a given byte array and
- * signals, at the same time, that this is the last push operation on
- * this Transformer
.
- *
+ * Processes a designated number of bytes from a given byte array and signals,
+ * at the same time, that this is the last push operation on this
+ * Transformer
.
+ *
* @param in the input data bytes.
* @param offset index of in
from which to start considering
- * data.
+ * data.
* @param length the count of bytes to process.
* @return the result of transformation.
* @throws IllegalStateException if the instance is not initialised.
* @throws TransformerException if a transformation-related exception occurs
- * during the operation.
+ * during the operation.
*/
public byte[] lastUpdate(byte[] in, int offset, int length)
throws TransformerException
@@ -378,22 +346,18 @@ public abstract class Transformer
return result;
}
- // helper methods ----------------------------------------------------------
-
private byte[] forwardUpdate(byte[] in, int off, int len)
throws TransformerException
{
- return (isPreProcessing() ? preTransform(in, off, len) : postTransform(in,
- off,
- len));
+ return (isPreProcessing() ? preTransform(in, off, len)
+ : postTransform(in, off, len));
}
private byte[] inverseUpdate(byte[] in, int off, int len)
throws TransformerException
{
- return (isPreProcessing() ? postTransform(in, off, len) : preTransform(in,
- off,
- len));
+ return (isPreProcessing() ? postTransform(in, off, len)
+ : preTransform(in, off, len));
}
private byte[] preTransform(byte[] in, int off, int len)
@@ -444,8 +408,6 @@ public abstract class Transformer
return result;
}
- // abstract methods to be implemented by concrete subclasses ---------------
-
abstract void initDelegate(Map attributes) throws TransformerException;
abstract int delegateBlockSize();
diff --git a/libjava/classpath/gnu/javax/crypto/assembly/TransformerException.java b/libjava/classpath/gnu/javax/crypto/assembly/TransformerException.java
index 412f0f0..2c972f8 100644
--- a/libjava/classpath/gnu/javax/crypto/assembly/TransformerException.java
+++ b/libjava/classpath/gnu/javax/crypto/assembly/TransformerException.java
@@ -43,17 +43,11 @@ import java.io.PrintWriter;
/**
*/
-public class TransformerException extends Exception
+public class TransformerException
+ extends Exception
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private Throwable _exception = null;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public TransformerException()
{
super();
@@ -78,12 +72,6 @@ public class TransformerException extends Exception
this._exception = cause;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instant methods
- // -------------------------------------------------------------------------
-
public Throwable getCause()
{
return _exception;
@@ -98,61 +86,53 @@ public class TransformerException extends Exception
{
super.printStackTrace();
if (_exception != null)
- {
- _exception.printStackTrace();
- }
+ _exception.printStackTrace();
}
/**
* Prints this exception's stack trace to a print stream. If this exception
- * has a root exception; the stack trace of the root exception is also
- * printed to the print stream.
- *
+ * has a root exception; the stack trace of the root exception is also printed
+ * to the print stream.
+ *
* @param ps the non-null print stream to which to print.
*/
public void printStackTrace(PrintStream ps)
{
super.printStackTrace(ps);
if (_exception != null)
- {
- _exception.printStackTrace(ps);
- }
+ _exception.printStackTrace(ps);
}
/**
* Prints this exception's stack trace to a print writer. If this exception
- * has a root exception; the stack trace of the root exception is also
- * printed to the print writer.
- *
+ * has a root exception; the stack trace of the root exception is also printed
+ * to the print writer.
+ *
* @param pw the non-null print writer to use for output.
*/
public void printStackTrace(PrintWriter pw)
{
super.printStackTrace(pw);
if (_exception != null)
- {
- _exception.printStackTrace(pw);
- }
+ _exception.printStackTrace(pw);
}
/**
* Returns the string representation of this exception. The string
- * representation contains this exception's class name, its detailed
- * messsage, and if it has a root exception, the string representation of the
- * root exception. This string representation is meant for debugging and not
- * meant to be interpreted programmatically.
- *
+ * representation contains this exception's class name, its detailed messsage,
+ * and if it has a root exception, the string representation of the root
+ * exception. This string representation is meant for debugging and not meant
+ * to be interpreted programmatically.
+ *
* @return the non-null string representation of this exception.
* @see Throwable#getMessage()
*/
public String toString()
{
- StringBuffer sb = new StringBuffer(this.getClass().getName()).append(": ").append(
- super.toString());
+ StringBuffer sb = new StringBuffer(this.getClass().getName())
+ .append(": ").append(super.toString());
if (_exception != null)
- {
- sb.append("; caused by: ").append(_exception.toString());
- }
+ sb.append("; caused by: ").append(_exception.toString());
return sb.toString();
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/cipher/Anubis.java b/libjava/classpath/gnu/javax/crypto/cipher/Anubis.java
index ca4e8ed..653957e 100644
--- a/libjava/classpath/gnu/javax/crypto/cipher/Anubis.java
+++ b/libjava/classpath/gnu/javax/crypto/cipher/Anubis.java
@@ -38,111 +38,82 @@ exception statement from your version. */
package gnu.javax.crypto.cipher;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-//import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
+import java.util.logging.Logger;
/**
- *
- *
*/
-public final class Anubis extends BaseCipher
+public final class Anubis
+ extends BaseCipher
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- // private static final String NAME = "anubis";
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- // private static final PrintWriter err = new PrintWriter(System.out, true);
- // private static void debug(String s) {
- // err.println(">>> "+NAME+": "+s);
- // }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Anubis.class.getName());
private static final int DEFAULT_BLOCK_SIZE = 16; // in bytes
-
private static final int DEFAULT_KEY_SIZE = 16; // in bytes
-
private static final String Sd = // p. 25 [ANUBIS]
- "\uBA54\u2F74\u53D3\uD24D\u50AC\u8DBF\u7052\u9A4C"
- + "\uEAD5\u97D1\u3351\u5BA6\uDE48\uA899\uDB32\uB7FC"
- + "\uE39E\u919B\uE2BB\u416E\uA5CB\u6B95\uA1F3\uB102"
- + "\uCCC4\u1D14\uC363\uDA5D\u5FDC\u7DCD\u7F5A\u6C5C"
- + "\uF726\uFFED\uE89D\u6F8E\u19A0\uF089\u0F07\uAFFB"
- + "\u0815\u0D04\u0164\uDF76\u79DD\u3D16\u3F37\u6D38"
- + "\uB973\uE935\u5571\u7B8C\u7288\uF62A\u3E5E\u2746"
- + "\u0C65\u6861\u03C1\u57D6\uD958\uD866\uD73A\uC83C"
- + "\uFA96\uA798\uECB8\uC7AE\u694B\uABA9\u670A\u47F2"
- + "\uB522\uE5EE\uBE2B\u8112\u831B\u0E23\uF545\u21CE"
- + "\u492C\uF9E6\uB628\u1782\u1A8B\uFE8A\u09C9\u874E"
- + "\uE12E\uE4E0\uEB90\uA41E\u8560\u0025\uF4F1\u940B"
- + "\uE775\uEF34\u31D4\uD086\u7EAD\uFD29\u303B\u9FF8"
- + "\uC613\u0605\uC511\u777C\u7A78\u361C\u3959\u1856"
- + "\uB3B0\u2420\uB292\uA3C0\u4462\u10B4\u8443\u93C2"
- + "\u4ABD\u8F2D\uBC9C\u6A40\uCFA2\u804F\u1FCA\uAA42";
-
+ "\uBA54\u2F74\u53D3\uD24D\u50AC\u8DBF\u7052\u9A4C"
+ + "\uEAD5\u97D1\u3351\u5BA6\uDE48\uA899\uDB32\uB7FC"
+ + "\uE39E\u919B\uE2BB\u416E\uA5CB\u6B95\uA1F3\uB102"
+ + "\uCCC4\u1D14\uC363\uDA5D\u5FDC\u7DCD\u7F5A\u6C5C"
+ + "\uF726\uFFED\uE89D\u6F8E\u19A0\uF089\u0F07\uAFFB"
+ + "\u0815\u0D04\u0164\uDF76\u79DD\u3D16\u3F37\u6D38"
+ + "\uB973\uE935\u5571\u7B8C\u7288\uF62A\u3E5E\u2746"
+ + "\u0C65\u6861\u03C1\u57D6\uD958\uD866\uD73A\uC83C"
+ + "\uFA96\uA798\uECB8\uC7AE\u694B\uABA9\u670A\u47F2"
+ + "\uB522\uE5EE\uBE2B\u8112\u831B\u0E23\uF545\u21CE"
+ + "\u492C\uF9E6\uB628\u1782\u1A8B\uFE8A\u09C9\u874E"
+ + "\uE12E\uE4E0\uEB90\uA41E\u8560\u0025\uF4F1\u940B"
+ + "\uE775\uEF34\u31D4\uD086\u7EAD\uFD29\u303B\u9FF8"
+ + "\uC613\u0605\uC511\u777C\u7A78\u361C\u3959\u1856"
+ + "\uB3B0\u2420\uB292\uA3C0\u4462\u10B4\u8443\u93C2"
+ + "\u4ABD\u8F2D\uBC9C\u6A40\uCFA2\u804F\u1FCA\uAA42";
private static final byte[] S = new byte[256];
-
private static final int[] T0 = new int[256];
-
private static final int[] T1 = new int[256];
-
private static final int[] T2 = new int[256];
-
private static final int[] T3 = new int[256];
-
private static final int[] T4 = new int[256];
-
private static final int[] T5 = new int[256];
-
/**
* Anubis round constants. This is the largest possible considering that we
* always use R values, R = 8 + N, and 4 <= N <= 10.
*/
private static final int[] rc = new int[18];
-
/**
- * KAT vector (from ecb_vk):
- * I=83
+ * KAT vector (from ecb_vk): I=83
* KEY=000000000000000000002000000000000000000000000000
* CT=2E66AB15773F3D32FB6C697509460DF4
*/
- private static final byte[] KAT_KEY = Util.toBytesFromString("000000000000000000002000000000000000000000000000");
-
- private static final byte[] KAT_CT = Util.toBytesFromString("2E66AB15773F3D32FB6C697509460DF4");
-
+ private static final byte[] KAT_KEY =
+ Util.toBytesFromString("000000000000000000002000000000000000000000000000");
+ private static final byte[] KAT_CT =
+ Util.toBytesFromString("2E66AB15773F3D32FB6C697509460DF4");
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
- // Static code - to initialise lookup tables -------------------------------
-
static
{
long time = System.currentTimeMillis();
-
int ROOT = 0x11d; // para. 2.1 [ANUBIS]
int i, s, s2, s4, s6, s8, t;
char c;
@@ -151,213 +122,172 @@ public final class Anubis extends BaseCipher
c = Sd.charAt(i >>> 1);
s = ((i & 1) == 0 ? c >>> 8 : c) & 0xFF;
S[i] = (byte) s;
-
s2 = s << 1;
if (s2 > 0xFF)
- {
- s2 ^= ROOT;
- }
-
+ s2 ^= ROOT;
s4 = s2 << 1;
if (s4 > 0xFF)
- {
- s4 ^= ROOT;
- }
-
+ s4 ^= ROOT;
s6 = s4 ^ s2;
s8 = s4 << 1;
if (s8 > 0xFF)
- {
- s8 ^= ROOT;
- }
-
- T0[i] = s << 24 | s2 << 16 | s4 << 8 | s6;
- T1[i] = s2 << 24 | s << 16 | s6 << 8 | s4;
- T2[i] = s4 << 24 | s6 << 16 | s << 8 | s2;
+ s8 ^= ROOT;
+ T0[i] = s << 24 | s2 << 16 | s4 << 8 | s6;
+ T1[i] = s2 << 24 | s << 16 | s6 << 8 | s4;
+ T2[i] = s4 << 24 | s6 << 16 | s << 8 | s2;
T3[i] = s6 << 24 | s4 << 16 | s2 << 8 | s;
-
- T4[i] = s << 24 | s << 16 | s << 8 | s;
- T5[s] = s << 24 | s2 << 16 | s6 << 8 | s8;
+ T4[i] = s << 24 | s << 16 | s << 8 | s;
+ T5[s] = s << 24 | s2 << 16 | s6 << 8 | s8;
}
-
// compute round constant
for (i = 0, s = 0; i < 18;)
- {
- rc[i++] = S[(s++) & 0xFF] << 24 | (S[(s++) & 0xFF] & 0xFF) << 16
- | (S[(s++) & 0xFF] & 0xFF) << 8 | (S[(s++) & 0xFF] & 0xFF);
- }
-
+ rc[i++] = S[(s++) & 0xFF] << 24
+ | (S[(s++) & 0xFF] & 0xFF) << 16
+ | (S[(s++) & 0xFF] & 0xFF) << 8
+ | (S[(s++) & 0xFF] & 0xFF);
time = System.currentTimeMillis() - time;
-
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static data");
- System.out.println();
-
- System.out.println();
- System.out.println("T0[]:");
+ log.fine("Static data");
+ log.fine("T0[]:");
+ StringBuilder sb;
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T0[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T0[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T1[]:");
+ log.fine("T1[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T1[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T1[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T2[]:");
+ log.fine("T2[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T2[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T2[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T3[]:");
+ log.fine("T3[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T3[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T3[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T4[]:");
+ log.fine("T4[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T4[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T4[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T5[]:");
+ log.fine("T5[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (t = 0; t < 4; t++)
- {
- System.out.print("0x" + Util.toString(T5[i * 4 + t]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T5[i * 4 + t])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("rc[]:");
+ log.fine("rc[]:");
for (i = 0; i < 18; i++)
- {
- System.out.println("0x" + Util.toString(rc[i]));
- }
- System.out.println();
-
- System.out.println();
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("0x" + Util.toString(rc[i]));
+ log.fine("Total initialization time: " + time + " ms.");
}
}
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Anubis()
{
super(Registry.ANUBIS_CIPHER, DEFAULT_BLOCK_SIZE, DEFAULT_KEY_SIZE);
}
- // Class methods
- // -------------------------------------------------------------------------
-
private static void anubis(byte[] in, int i, byte[] out, int j, int[][] K)
{
// extract encryption round keys
int R = K.length - 1;
int[] Ker = K[0];
-
// mu function + affine key addition
- int a0 = (in[i++] << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i++] & 0xFF))
- ^ Ker[0];
- int a1 = (in[i++] << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i++] & 0xFF))
- ^ Ker[1];
- int a2 = (in[i++] << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i++] & 0xFF))
- ^ Ker[2];
- int a3 = (in[i++] << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i] & 0xFF))
- ^ Ker[3];
-
+ int a0 = (in[i++] << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i++] & 0xFF) ) ^ Ker[0];
+ int a1 = (in[i++] << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i++] & 0xFF) ) ^ Ker[1];
+ int a2 = (in[i++] << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i++] & 0xFF) ) ^ Ker[2];
+ int a3 = (in[i++] << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i] & 0xFF) ) ^ Ker[3];
int b0, b1, b2, b3;
// round function
for (int r = 1; r < R; r++)
{
Ker = K[r];
- b0 = T0[a0 >>> 24] ^ T1[a1 >>> 24] ^ T2[a2 >>> 24] ^ T3[a3 >>> 24]
- ^ Ker[0];
- b1 = T0[(a0 >>> 16) & 0xFF] ^ T1[(a1 >>> 16) & 0xFF]
- ^ T2[(a2 >>> 16) & 0xFF] ^ T3[(a3 >>> 16) & 0xFF] ^ Ker[1];
- b2 = T0[(a0 >>> 8) & 0xFF] ^ T1[(a1 >>> 8) & 0xFF]
- ^ T2[(a2 >>> 8) & 0xFF] ^ T3[(a3 >>> 8) & 0xFF] ^ Ker[2];
- b3 = T0[a0 & 0xFF] ^ T1[a1 & 0xFF] ^ T2[a2 & 0xFF] ^ T3[a3 & 0xFF]
- ^ Ker[3];
+ b0 = T0[ a0 >>> 24 ]
+ ^ T1[ a1 >>> 24 ]
+ ^ T2[ a2 >>> 24 ]
+ ^ T3[ a3 >>> 24 ] ^ Ker[0];
+ b1 = T0[(a0 >>> 16) & 0xFF]
+ ^ T1[(a1 >>> 16) & 0xFF]
+ ^ T2[(a2 >>> 16) & 0xFF]
+ ^ T3[(a3 >>> 16) & 0xFF] ^ Ker[1];
+ b2 = T0[(a0 >>> 8) & 0xFF]
+ ^ T1[(a1 >>> 8) & 0xFF]
+ ^ T2[(a2 >>> 8) & 0xFF]
+ ^ T3[(a3 >>> 8) & 0xFF] ^ Ker[2];
+ b3 = T0[ a0 & 0xFF]
+ ^ T1[ a1 & 0xFF]
+ ^ T2[ a2 & 0xFF]
+ ^ T3[ a3 & 0xFF] ^ Ker[3];
a0 = b0;
a1 = b1;
a2 = b2;
a3 = b3;
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("T" + r + "=" + Util.toString(a0)
- + Util.toString(a1) + Util.toString(a2)
- + Util.toString(a3));
- }
+ if (Configuration.DEBUG)
+ log.fine("T" + r + "=" + Util.toString(a0) + Util.toString(a1)
+ + Util.toString(a2) + Util.toString(a3));
}
-
// last round function
Ker = K[R];
int tt = Ker[0];
- out[j++] = (byte) (S[a0 >>> 24] ^ (tt >>> 24));
- out[j++] = (byte) (S[a1 >>> 24] ^ (tt >>> 16));
- out[j++] = (byte) (S[a2 >>> 24] ^ (tt >>> 8));
- out[j++] = (byte) (S[a3 >>> 24] ^ tt);
+ out[j++] = (byte)(S[ a0 >>> 24 ] ^ (tt >>> 24));
+ out[j++] = (byte)(S[ a1 >>> 24 ] ^ (tt >>> 16));
+ out[j++] = (byte)(S[ a2 >>> 24 ] ^ (tt >>> 8));
+ out[j++] = (byte)(S[ a3 >>> 24 ] ^ tt);
tt = Ker[1];
- out[j++] = (byte) (S[(a0 >>> 16) & 0xFF] ^ (tt >>> 24));
- out[j++] = (byte) (S[(a1 >>> 16) & 0xFF] ^ (tt >>> 16));
- out[j++] = (byte) (S[(a2 >>> 16) & 0xFF] ^ (tt >>> 8));
- out[j++] = (byte) (S[(a3 >>> 16) & 0xFF] ^ tt);
+ out[j++] = (byte)(S[(a0 >>> 16) & 0xFF] ^ (tt >>> 24));
+ out[j++] = (byte)(S[(a1 >>> 16) & 0xFF] ^ (tt >>> 16));
+ out[j++] = (byte)(S[(a2 >>> 16) & 0xFF] ^ (tt >>> 8));
+ out[j++] = (byte)(S[(a3 >>> 16) & 0xFF] ^ tt);
tt = Ker[2];
- out[j++] = (byte) (S[(a0 >>> 8) & 0xFF] ^ (tt >>> 24));
- out[j++] = (byte) (S[(a1 >>> 8) & 0xFF] ^ (tt >>> 16));
- out[j++] = (byte) (S[(a2 >>> 8) & 0xFF] ^ (tt >>> 8));
- out[j++] = (byte) (S[(a3 >>> 8) & 0xFF] ^ tt);
+ out[j++] = (byte)(S[(a0 >>> 8) & 0xFF] ^ (tt >>> 24));
+ out[j++] = (byte)(S[(a1 >>> 8) & 0xFF] ^ (tt >>> 16));
+ out[j++] = (byte)(S[(a2 >>> 8) & 0xFF] ^ (tt >>> 8));
+ out[j++] = (byte)(S[(a3 >>> 8) & 0xFF] ^ tt);
tt = Ker[3];
- out[j++] = (byte) (S[a0 & 0xFF] ^ (tt >>> 24));
- out[j++] = (byte) (S[a1 & 0xFF] ^ (tt >>> 16));
- out[j++] = (byte) (S[a2 & 0xFF] ^ (tt >>> 8));
- out[j] = (byte) (S[a3 & 0xFF] ^ tt);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("T=" + Util.toString(out, j - 15, 16));
- System.out.println();
- }
+ out[j++] = (byte)(S[ a0 & 0xFF] ^ (tt >>> 24));
+ out[j++] = (byte)(S[ a1 & 0xFF] ^ (tt >>> 16));
+ out[j++] = (byte)(S[ a2 & 0xFF] ^ (tt >>> 8));
+ out[j ] = (byte)(S[ a3 & 0xFF] ^ tt);
+ if (Configuration.DEBUG)
+ log.fine("T=" + Util.toString(out, j - 15, 16) + "\n");
}
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.lang.Cloneable interface implementation ----------------------------
-
public Object clone()
{
Anubis result = new Anubis();
@@ -366,12 +296,10 @@ public final class Anubis extends BaseCipher
return result;
}
- // IBlockCipherSpi interface implementation --------------------------------
-
public Iterator blockSizes()
{
ArrayList al = new ArrayList();
- al.add(new Integer(DEFAULT_BLOCK_SIZE));
+ al.add(Integer.valueOf(DEFAULT_BLOCK_SIZE));
return Collections.unmodifiableList(al).iterator();
}
@@ -380,17 +308,14 @@ public final class Anubis extends BaseCipher
{
ArrayList al = new ArrayList();
for (int n = 4; n < 10; n++)
- {
- al.add(new Integer(n * 32 / 8));
- }
-
+ al.add(Integer.valueOf(n * 32 / 8));
return Collections.unmodifiableList(al).iterator();
}
/**
- *
- * Paulo S.L.M. Barreto and
- * Vincent Rijmen.
+ * Paulo S.L.M. Barreto and Vincent Rijmen.
- *
*/
-public class Blowfish extends BaseCipher
+public class Blowfish
+ extends BaseCipher
{
-
- // Constants and variables
- // -----------------------------------------------------------------
-
private static final int DEFAULT_BLOCK_SIZE = 8;
-
private static final int DEFAULT_KEY_SIZE = 8;
-
private static final int MAX_KEY_LENGTH = 56;
-
/** Initial value of the p-array. */
- private static final int[] P = { 0x243f6a88, 0x85a308d3, 0x13198a2e,
- 0x03707344, 0xa4093822, 0x299f31d0,
- 0x082efa98, 0xec4e6c89, 0x452821e6,
- 0x38d01377, 0xbe5466cf, 0x34e90c6c,
- 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5,
- 0xb5470917, 0x9216d5d9, 0x8979fb1b };
-
+ private static final int[] P = {
+ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
+ 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
+ 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b };
/** Initial value of S-box 1. */
- static final int[] KS0 = { 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
- 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
- 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
- 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
- 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
- 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
- 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
- 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
- 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
- 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
- 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
- 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
- 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
- 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
- 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
- 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
- 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
- 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
- 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
- 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
- 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
- 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
- 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
- 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
- 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
- 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
- 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
- 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
- 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
- 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
- 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
- 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
- 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
- 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
- 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
- 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
- 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
- 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
- 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
- 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
- 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
- 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
- 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
- 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
- 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
- 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
- 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
- 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
- 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
- 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
- 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
- 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
- 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
- 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
- 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
- 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
- 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
- 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
- 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
- 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
- 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
- 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
- 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
- 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a };
-
+ static final int[] KS0 = {
+ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
+ 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
+ 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
+ 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
+ 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
+ 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
+ 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
+ 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
+ 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
+ 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
+ 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
+ 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
+ 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
+ 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
+ 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
+ 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
+ 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
+ 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
+ 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
+ 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
+ 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
+ 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
+ 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
+ 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
+ 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
+ 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
+ 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
+ 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
+ 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
+ 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
+ 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
+ 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
+ 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
+ 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
+ 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
+ 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
+ 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
+ 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
+ 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
+ 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
+ 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
+ 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
+ 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a };
/** Initial value of S-box 2. */
- private static final int[] KS1 = { 0x4b7a70e9, 0xb5b32944, 0xdb75092e,
- 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
- 0x9cee60b8, 0x8fedb266, 0xecaa8c71,
- 0x699a17ff, 0x5664526c, 0xc2b19ee1,
- 0x193602a5, 0x75094c29, 0xa0591340,
- 0xe4183a3e, 0x3f54989a, 0x5b429d65,
- 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07,
- 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
- 0x4cdd2086, 0x8470eb26, 0x6382e9c6,
- 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
- 0x3c971814, 0x6b6a70a1, 0x687f3584,
- 0x52a0e286, 0xb79c5305, 0xaa500737,
- 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec,
- 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
- 0xf01c1f04, 0x0200b3ff, 0xae0cf51a,
- 0x3cb574b2, 0x25837a58, 0xdc0921bd,
- 0xd19113f9, 0x7ca92ff6, 0x94324773,
- 0x22f54701, 0x3ae5e581, 0x37c2dadc,
- 0xc8b57634, 0x9af3dda7, 0xa9446146,
- 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
- 0xe238cd99, 0x3bea0e2f, 0x3280bba1,
- 0x183eb331, 0x4e548b38, 0x4f6db908,
- 0x6f420d03, 0xf60a04bf, 0x2cb81290,
- 0x24977c79, 0x5679b072, 0xbcaf89af,
- 0xde9a771f, 0xd9930810, 0xb38bae12,
- 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
- 0x501adde6, 0x9f84cd87, 0x7a584718,
- 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
- 0xec7aec3a, 0xdb851dfa, 0x63094366,
- 0xc464c3d2, 0xef1c1847, 0x3215d908,
- 0xdd433b37, 0x24c2ba16, 0x12a14d43,
- 0x2a65c451, 0x50940002, 0x133ae4dd,
- 0x71dff89e, 0x10314e55, 0x81ac77d6,
- 0x5f11199b, 0x043556f1, 0xd7a3c76b,
- 0x3c11183b, 0x5924a509, 0xf28fe6ed,
- 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
- 0x86e34570, 0xeae96fb1, 0x860e5e0a,
- 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
- 0x2965dcb9, 0x99e71d0f, 0x803e89d6,
- 0x5266c825, 0x2e4cc978, 0x9c10b36a,
- 0xc6150eba, 0x94e2ea78, 0xa5fc3c53,
- 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
- 0x1939260f, 0x19c27960, 0x5223a708,
- 0xf71312b6, 0xebadfe6e, 0xeac31f66,
- 0xe3bc4595, 0xa67bc883, 0xb17f37d1,
- 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
- 0x65582185, 0x68ab9802, 0xeecea50f,
- 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
- 0x1521b628, 0x29076170, 0xecdd4775,
- 0x619f1510, 0x13cca830, 0xeb61bd96,
- 0x0334fe1e, 0xaa0363cf, 0xb5735c90,
- 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
- 0xeecc86bc, 0x60622ca7, 0x9cab5cab,
- 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
- 0xa02369b9, 0x655abb50, 0x40685a32,
- 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
- 0x9b540b19, 0x875fa099, 0x95f7997e,
- 0x623d7da8, 0xf837889a, 0x97e32d77,
- 0x11ed935f, 0x16681281, 0x0e358829,
- 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
- 0x57f584a5, 0x1b227263, 0x9b83c3ff,
- 0x1ac24696, 0xcdb30aeb, 0x532e3054,
- 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef,
- 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
- 0x5d4a14d9, 0xe864b7e3, 0x42105d14,
- 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
- 0xdb6c4f15, 0xfacb4fd0, 0xc742f442,
- 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
- 0xd81e799e, 0x86854dc7, 0xe44b476a,
- 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
- 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3,
- 0x69cb7492, 0x47848a0b, 0x5692b285,
- 0x095bbf00, 0xad19489d, 0x1462b174,
- 0x23820e00, 0x58428d2a, 0x0c55f5ea,
- 0x1dadf43e, 0x233f7061, 0x3372f092,
- 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
- 0x7cde3759, 0xcbee7460, 0x4085f2a7,
- 0xce77326e, 0xa6078084, 0x19f8509e,
- 0xe8efd855, 0x61d99735, 0xa969a7aa,
- 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
- 0x9e447a2e, 0xc3453484, 0xfdd56705,
- 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
- 0x675fda79, 0xe3674340, 0xc5c43465,
- 0x713e38d8, 0x3d28f89e, 0xf16dff20,
- 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b,
- 0xdb83adf7 };
-
+ private static final int[] KS1 = {
+ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
+ 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
+ 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
+ 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
+ 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
+ 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
+ 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
+ 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
+ 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
+ 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
+ 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
+ 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
+ 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
+ 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
+ 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
+ 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
+ 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
+ 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
+ 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
+ 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
+ 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
+ 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
+ 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
+ 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
+ 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
+ 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
+ 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
+ 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
+ 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
+ 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
+ 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
+ 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
+ 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
+ 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
+ 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
+ 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
+ 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
+ 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
+ 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
+ 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
+ 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
+ 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
+ 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 };
/** Initial value of S-box 3. */
- private static final int[] KS2 = { 0xe93d5a68, 0x948140f7, 0xf64c261c,
- 0x94692934, 0x411520f7, 0x7602d4f7,
- 0xbcf46b2e, 0xd4a20068, 0xd4082471,
- 0x3320f46a, 0x43b7d4b7, 0x500061af,
- 0x1e39f62e, 0x97244546, 0x14214f74,
- 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
- 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec,
- 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
- 0x96eb27b3, 0x55fd3941, 0xda2547e6,
- 0xabca0a9a, 0x28507825, 0x530429f4,
- 0x0a2c86da, 0xe9b66dfb, 0x68dc1462,
- 0xd7486900, 0x680ec0a4, 0x27a18dee,
- 0x4f3ffea2, 0xe887ad8c, 0xb58ce006,
- 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
- 0xce78a399, 0x406b2a42, 0x20fe9e35,
- 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
- 0x1dc9faf7, 0x4b6d1856, 0x26a36631,
- 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
- 0x6841e7f7, 0xca7820fb, 0xfb0af54e,
- 0xd8feb397, 0x454056ac, 0xba489527,
- 0x55533a3a, 0x20838d87, 0xfe6ba9b7,
- 0xd096954b, 0x55a867bc, 0xa1159a58,
- 0xcca92963, 0x99e1db33, 0xa62a4a56,
- 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
- 0xfdf8e802, 0x04272f70, 0x80bb155c,
- 0x05282ce3, 0x95c11548, 0xe4c66d22,
- 0x48c1133f, 0xc70f86dc, 0x07f9c9ee,
- 0x41041f0f, 0x404779a4, 0x5d886e17,
- 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f,
- 0x41113564, 0x257b7834, 0x602a9c60,
- 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2,
- 0x02e1329e, 0xaf664fd1, 0xcad18115,
- 0x6b2395e0, 0x333e92e1, 0x3b240b62,
- 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
- 0xde720c8c, 0x2da2f728, 0xd0127845,
- 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
- 0x5449a36f, 0x877d48fa, 0xc39dfd27,
- 0xf33e8d1e, 0x0a476341, 0x992eff74,
- 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60,
- 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
- 0xc67b5510, 0x6d672c37, 0x2765d43b,
- 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
- 0xb5390f92, 0x690fed0b, 0x667b9ffb,
- 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
- 0xbb132f88, 0x515bad24, 0x7b9479bf,
- 0x763bd6eb, 0x37392eb3, 0xcc115979,
- 0x8026e297, 0xf42e312d, 0x6842ada7,
- 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
- 0x6a124237, 0xb79251e7, 0x06a1bbe6,
- 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
- 0x3d25bdd8, 0xe2e1c3c9, 0x44421659,
- 0x0a121386, 0xd90cec6e, 0xd5abea2a,
- 0x64af674e, 0xda86a85f, 0xbebfe988,
- 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
- 0x60787bf8, 0x6003604d, 0xd1fd8346,
- 0xf6381fb0, 0x7745ae04, 0xd736fccc,
- 0x83426b33, 0xf01eab71, 0xb0804187,
- 0x3c005e5f, 0x77a057be, 0xbde8ae24,
- 0x55464299, 0xbf582e61, 0x4e58f48f,
- 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
- 0x5366f9c3, 0xc8b38e74, 0xb475f255,
- 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
- 0x846a0e79, 0x915f95e2, 0x466e598e,
- 0x20b45770, 0x8cd55591, 0xc902de4c,
- 0xb90bace1, 0xbb8205d0, 0x11a86248,
- 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
- 0x662d09a1, 0xc4324633, 0xe85a1f02,
- 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
- 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f,
- 0x2868f169, 0xdcb7da83, 0x573906fe,
- 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01,
- 0xa70683fa, 0xa002b5c4, 0x0de6d027,
- 0x9af88c27, 0x773f8641, 0xc3604c06,
- 0x61a806b5, 0xf0177a28, 0xc0f586e0,
- 0x006058aa, 0x30dc7d62, 0x11e69ed7,
- 0x2338ea63, 0x53c2dd94, 0xc2c21634,
- 0xbbcbee56, 0x90bcb6de, 0xebfc7da1,
- 0xce591d76, 0x6f05e409, 0x4b7c0188,
- 0x39720a3d, 0x7c927c24, 0x86e3725f,
- 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
- 0xed545578, 0x08fca5b5, 0xd83d7cd3,
- 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
- 0xa28514d9, 0x6c51133c, 0x6fd5c7e7,
- 0x56e14ec4, 0x362abfce, 0xddc6c837,
- 0xd79a3234, 0x92638212, 0x670efa8e,
- 0x406000e0 };
-
+ private static final int[] KS2 = {
+ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
+ 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
+ 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
+ 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
+ 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
+ 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
+ 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
+ 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
+ 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
+ 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
+ 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
+ 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
+ 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
+ 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
+ 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
+ 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
+ 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
+ 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
+ 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
+ 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
+ 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
+ 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
+ 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
+ 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
+ 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
+ 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
+ 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
+ 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
+ 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
+ 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
+ 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
+ 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
+ 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
+ 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
+ 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
+ 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
+ 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
+ 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
+ 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
+ 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
+ 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
+ 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
+ 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 };
/** Initial value of S-box 4. */
- private static final int[] KS3 = { 0x3a39ce37, 0xd3faf5cf, 0xabc27737,
- 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
- 0xd3822740, 0x99bc9bbe, 0xd5118e9d,
- 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
- 0xb78c1b6b, 0x21a19045, 0xb26eb1be,
- 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
- 0xc6a376d2, 0x6549c2c8, 0x530ff8ee,
- 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
- 0x2939bbdb, 0xa9ba4650, 0xac9526e8,
- 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
- 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8,
- 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
- 0x83c061ba, 0x9be96a4d, 0x8fe51550,
- 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
- 0x4ba99586, 0xef5562e9, 0xc72fefd3,
- 0xf752f7da, 0x3f046f69, 0x77fa0a59,
- 0x80e4a915, 0x87b08601, 0x9b09e6ad,
- 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
- 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a,
- 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
- 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472,
- 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
- 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d,
- 0x283b57cc, 0xf8d56629, 0x79132e28,
- 0x785f0191, 0xed756055, 0xf7960e44,
- 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
- 0x03a16125, 0x0564f0bd, 0xc3eb9e15,
- 0x3c9057a2, 0x97271aec, 0xa93a072a,
- 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb,
- 0x26dcf319, 0x7533d928, 0xb155fdf5,
- 0x03563482, 0x8aba3cbb, 0x28517711,
- 0xc20ad9f8, 0xabcc5167, 0xccad925f,
- 0x4de81751, 0x3830dc8e, 0x379d5862,
- 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
- 0x5121ce64, 0x774fbe32, 0xa8b6e37e,
- 0xc3293d46, 0x48de5369, 0x6413e680,
- 0xa2ae0810, 0xdd6db224, 0x69852dfd,
- 0x09072166, 0xb39a460a, 0x6445c0dd,
- 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd,
- 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
- 0xdda26a7e, 0x3a59ff45, 0x3e350a44,
- 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
- 0x8d6612ae, 0xbf3c6f47, 0xd29be463,
- 0x542f5d9e, 0xaec2771b, 0xf64e6370,
- 0x740e0d8d, 0xe75b1357, 0xf8721671,
- 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
- 0x34d2466a, 0x0115af84, 0xe1b00428,
- 0x95983a1d, 0x06b89fb4, 0xce6ea048,
- 0x6f3f3b82, 0x3520ab82, 0x011a1d4b,
- 0x277227f8, 0x611560b1, 0xe7933fdc,
- 0xbb3a792b, 0x344525bd, 0xa08839e1,
- 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
- 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3,
- 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
- 0xd0dadecb, 0xd50ada38, 0x0339c32a,
- 0xc6913667, 0x8df9317c, 0xe0b12b4f,
- 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff,
- 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
- 0x0f91fc71, 0x9b941525, 0xfae59361,
- 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
- 0xb6c1075e, 0xe3056a0c, 0x10d25065,
- 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
- 0x4c98a0be, 0x3278e964, 0x9f1f9532,
- 0xe0d392df, 0xd3a0342b, 0x8971f21e,
- 0x1b0a7441, 0x4ba3348c, 0xc5be7120,
- 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
- 0xe60b6f47, 0x0fe3f11d, 0xe54cda54,
- 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
- 0x1618b166, 0xfd2c1d05, 0x848fd2c5,
- 0xf6fb2299, 0xf523f357, 0xa6327623,
- 0x93a83531, 0x56cccd02, 0xacf08162,
- 0x5a75ebb5, 0x6e163697, 0x88d273cc,
- 0xde966292, 0x81b949d0, 0x4c50901b,
- 0x71c65614, 0xe6c6c7bd, 0x327a140a,
- 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd,
- 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
- 0x71126905, 0xb2040222, 0xb6cbcf7c,
- 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
- 0x38abbd60, 0x2547adf0, 0xba38209c,
- 0xf746ce76, 0x77afa1c5, 0x20756060,
- 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0,
- 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
- 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869,
- 0xa65cdea0, 0x3f09252d, 0xc208e69f,
- 0xb74e6132, 0xce77e25b, 0x578fdfe3,
- 0x3ac372e6 };
-
+ private static final int[] KS3 = {
+ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
+ 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
+ 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
+ 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
+ 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
+ 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
+ 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
+ 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
+ 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
+ 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
+ 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
+ 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
+ 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
+ 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
+ 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
+ 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
+ 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
+ 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
+ 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
+ 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
+ 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
+ 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
+ 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
+ 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
+ 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
+ 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
+ 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
+ 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
+ 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
+ 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
+ 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
+ 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
+ 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
+ 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
+ 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
+ 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
+ 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
+ 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
+ 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
+ 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
+ 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
+ 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
+ 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 };
/** Cache of the self test. */
private static Boolean valid;
-
/**
* Test vector, as published in
* href="http://www.counterpane.com/vectors.txt">http://www.counterpane.com/vectors.txt.
@@ -424,20 +264,13 @@ public class Blowfish extends BaseCipher
* CT=4EF997456198DD78
*/
private static final byte[] TV_KEY = Util.toBytesFromString("0000000000000000");
-
private static final byte[] TV_CT = Util.toBytesFromString("4EF997456198DD78");
- // Constructors
- // -----------------------------------------------------------------------
-
public Blowfish()
{
super(Registry.BLOWFISH_CIPHER, DEFAULT_BLOCK_SIZE, DEFAULT_KEY_SIZE);
}
- // Clonable interface implementation.
- // -----------------------------------------------------------------------
-
public Object clone()
{
Blowfish result = new Blowfish();
@@ -445,36 +278,14 @@ public class Blowfish extends BaseCipher
return result;
}
- // Implementations of abstract methods from BaseCipher
- // -----------------------------------------------------------------------
-
public Iterator keySizes()
{
return new Sequence(8, MAX_KEY_LENGTH, 8).iterator();
- // return new Iterator() {
- // private int i = 0;
-
- // public boolean hasNext() {
- // return i <= MAX_KEY_LENGTH-8;
- // }
-
- // public Object next() {
- // if (hasNext()) {
- // i += 8;
- // return new Integer(i);
- // }
- // return null;
- // }
-
- // public void remove() {
- // throw new UnsupportedOperationException();
- // }
- // };
}
public Iterator blockSizes()
{
- return Collections.singleton(new Integer(DEFAULT_BLOCK_SIZE)).iterator();
+ return Collections.singleton(Integer.valueOf(DEFAULT_BLOCK_SIZE)).iterator();
}
public Object makeKey(byte[] k, int bs)
@@ -485,7 +296,6 @@ public class Blowfish extends BaseCipher
System.arraycopy(KS1, 0, ctx.s1, 0, KS1.length);
System.arraycopy(KS2, 0, ctx.s2, 0, KS2.length);
System.arraycopy(KS3, 0, ctx.s3, 0, KS3.length);
-
// XOR the key with the P-box
int l = 0;
for (int i = 0; i < ctx.p.length; i++)
@@ -495,13 +305,10 @@ public class Blowfish extends BaseCipher
{
data = (data << 8) | (k[l++] & 0xff);
if (l >= k.length)
- {
- l = 0;
- }
+ l = 0;
}
ctx.p[i] ^= data;
}
-
// We swap the left and right words here only, so we can avoid
// swapping altogether during encryption/decryption.
int t;
@@ -559,18 +366,22 @@ public class Blowfish extends BaseCipher
public void encrypt(byte[] in, int i, byte[] out, int o, Object k, int bs)
{
Block x = new Block();
- x.left = (in[i] & 0xff) << 24 | (in[i + 1] & 0xff) << 16
- | (in[i + 2] & 0xff) << 8 | (in[i + 3] & 0xff);
- x.right = (in[i + 4] & 0xff) << 24 | (in[i + 5] & 0xff) << 16
- | (in[i + 6] & 0xff) << 8 | (in[i + 7] & 0xff);
+ x.left = (in[i ] & 0xff) << 24
+ | (in[i + 1] & 0xff) << 16
+ | (in[i + 2] & 0xff) << 8
+ | (in[i + 3] & 0xff);
+ x.right = (in[i + 4] & 0xff) << 24
+ | (in[i + 5] & 0xff) << 16
+ | (in[i + 6] & 0xff) << 8
+ | (in[i + 7] & 0xff);
blowfishEncrypt(x, (Context) k);
- out[o] = (byte) (x.right >>> 24);
- out[o + 1] = (byte) (x.right >>> 16);
- out[o + 2] = (byte) (x.right >>> 8);
+ out[o ] = (byte)(x.right >>> 24);
+ out[o + 1] = (byte)(x.right >>> 16);
+ out[o + 2] = (byte)(x.right >>> 8);
out[o + 3] = (byte) x.right;
- out[o + 4] = (byte) (x.left >>> 24);
- out[o + 5] = (byte) (x.left >>> 16);
- out[o + 6] = (byte) (x.left >>> 8);
+ out[o + 4] = (byte)(x.left >>> 24);
+ out[o + 5] = (byte)(x.left >>> 16);
+ out[o + 6] = (byte)(x.left >>> 8);
out[o + 7] = (byte) x.left;
x.left = x.right = 0;
}
@@ -578,63 +389,96 @@ public class Blowfish extends BaseCipher
public void decrypt(byte[] in, int i, byte[] out, int o, Object k, int bs)
{
Block x = new Block();
- x.left = (in[i] & 0xff) << 24 | (in[i + 1] & 0xff) << 16
- | (in[i + 2] & 0xff) << 8 | (in[i + 3] & 0xff);
- x.right = (in[i + 4] & 0xff) << 24 | (in[i + 5] & 0xff) << 16
- | (in[i + 6] & 0xff) << 8 | (in[i + 7] & 0xff);
+ x.left = (in[i ] & 0xff) << 24
+ | (in[i + 1] & 0xff) << 16
+ | (in[i + 2] & 0xff) << 8
+ | (in[i + 3] & 0xff);
+ x.right = (in[i + 4] & 0xff) << 24
+ | (in[i + 5] & 0xff) << 16
+ | (in[i + 6] & 0xff) << 8
+ | (in[i + 7] & 0xff);
blowfishDecrypt(x, (Context) k);
- out[o] = (byte) (x.right >>> 24);
- out[o + 1] = (byte) (x.right >>> 16);
- out[o + 2] = (byte) (x.right >>> 8);
+ out[o ] = (byte)(x.right >>> 24);
+ out[o + 1] = (byte)(x.right >>> 16);
+ out[o + 2] = (byte)(x.right >>> 8);
out[o + 3] = (byte) x.right;
- out[o + 4] = (byte) (x.left >>> 24);
- out[o + 5] = (byte) (x.left >>> 16);
- out[o + 6] = (byte) (x.left >>> 8);
+ out[o + 4] = (byte)(x.left >>> 24);
+ out[o + 5] = (byte)(x.left >>> 16);
+ out[o + 6] = (byte)(x.left >>> 8);
out[o + 7] = (byte) x.left;
x.left = x.right = 0;
}
- // Own methods
- // -----------------------------------------------------------------
-
/** Encrypt a single pair of 32-bit integers. */
private void blowfishEncrypt(Block x, Context ctx)
{
int[] p = ctx.p;
int[] s0 = ctx.s0, s1 = ctx.s1, s2 = ctx.s2, s3 = ctx.s3;
x.left ^= p[0];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[1];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[2];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[3];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[4];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[5];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[6];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[7];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[8];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[9];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[10];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[11];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[12];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[13];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[14];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[15];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[16];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[1];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[2];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[3];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[4];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[5];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[6];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[7];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[8];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[9];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[10];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[11];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[12];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[13];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[14];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[15];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[16];
x.right ^= p[17];
}
@@ -644,38 +488,70 @@ public class Blowfish extends BaseCipher
int[] p = ctx.p;
int[] s0 = ctx.s0, s1 = ctx.s1, s2 = ctx.s2, s3 = ctx.s3;
x.left ^= p[17];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[16];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[15];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[14];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[13];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[12];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[11];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[10];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[9];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[8];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[7];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[6];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[5];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[4];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[3];
- x.right ^= ((s0[x.left >>> 24] + s1[x.left >>> 16 & 0xff]) ^ s2[x.left >>> 8 & 0xff])
- + s3[x.left & 0xff] ^ p[2];
- x.left ^= ((s0[x.right >>> 24] + s1[x.right >>> 16 & 0xff]) ^ s2[x.right >>> 8 & 0xff])
- + s3[x.right & 0xff] ^ p[1];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[16];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[15];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[14];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[13];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[12];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[11];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[10];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[9];
+ x.right ^= ((s0[x.left >>> 24]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[8];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[7];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[6];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[5];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[4];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[3];
+ x.right ^= ((s0[x.left >>> 24 ]
+ + s1[x.left >>> 16 & 0xff])
+ ^ s2[x.left >>> 8 & 0xff])
+ + s3[x.left & 0xff] ^ p[2];
+ x.left ^= ((s0[x.right >>> 24 ]
+ + s1[x.right >>> 16 & 0xff])
+ ^ s2[x.right >>> 8 & 0xff])
+ + s3[x.right & 0xff] ^ p[1];
x.right ^= p[0];
}
@@ -685,30 +561,19 @@ public class Blowfish extends BaseCipher
{
boolean result = super.selfTest(); // symmetry
if (result)
- {
- result = testKat(TV_KEY, TV_CT);
- }
+ result = testKat(TV_KEY, TV_CT);
valid = Boolean.valueOf(result);
}
return valid.booleanValue();
}
- // Inner classes.
- // -----------------------------------------------------------------------
-
/** A simple wrapper for the P- and S-boxes. */
- private class Context implements Cloneable
+ private class Context
+ implements Cloneable
{
-
- // Constants and variables.
- // --------------------------------------------------------------------
-
/** The P-array. */
int[] p, s0, s1, s2, s3;
- // Constructors.
- // --------------------------------------------------------------------
-
/** Default 0-arguments constructor. */
Context()
{
@@ -733,9 +598,6 @@ public class Blowfish extends BaseCipher
this.s3 = (int[]) that.s3.clone();
}
- // Clonable interface implementation.
- // --------------------------------------------------------------------
-
public Object clone()
{
return new Context(this);
@@ -746,4 +608,4 @@ public class Blowfish extends BaseCipher
{
int left, right;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/cipher/Cast5.java b/libjava/classpath/gnu/javax/crypto/cipher/Cast5.java
index a0e0c60..a752153 100644
--- a/libjava/classpath/gnu/javax/crypto/cipher/Cast5.java
+++ b/libjava/classpath/gnu/javax/crypto/cipher/Cast5.java
@@ -47,12 +47,11 @@ import java.util.Collections;
import java.util.Iterator;
/**
- * CAST5
(a.k.a. CAST-128) algorithm,
- * as per RFC-2144, dated May 1997.CAST5
(a.k.a. CAST-128) algorithm,
+ * as per RFC-2144, dated May 1997.
+ *
* "...a DES-like Substitution-Permutation Network (SPN) cryptosystem which
* appears to have good resistance to differential cryptanalysis, linear
@@ -61,19 +60,18 @@ import java.util.Iterator;
* Strict Avalanche Criterion (SAC), Bit Independence Criterion (BIC), no
* complementation property, and an absence of weak and semi-weak keys."
*
- *
- * CAST5
is a symmetric block cipher with a block-size of 8
+ * CAST5
is a symmetric block cipher with a block-size of 8
* bytes and a variable key-size of up to 128 bits. Its authors, and their
* employer (Entrust Technologies, a Nortel majority-owned company), made it
* available worldwide on a royalty-free basis for commercial and non-commercial
- * uses.CAST5
encryption algorithm has been designed to allow a
+ * uses.
+ * CAST5
encryption algorithm has been designed to allow a
* key size that can vary from 40
bits to 128
bits,
* in 8-bit increments (that is, the allowable key sizes are 40, 48, 56,
* 64, ..., 112, 120,
and 128
bits. For variable keysize
- * operation, the specification is as follows:
*
- *
- * 80
bits (i.e.,
* 40, 48, 56, 64, 72,
and 80
bits), the algorithm
@@ -86,25 +84,19 @@ import java.util.Iterator;
* 128
bits (since the CAST5
key schedule assumes
* an input key of 128
bits).
* INPUT: plaintext m1...m64; key K = k1...k128.
* OUTPUT: ciphertext c1...c64.
*
- *
*
*
- *
- *
* (1a) Li = Ri-1;
* (1b) Ri = Li-1 ^ Fi(Ri-1);
@@ -1249,16 +850,16 @@ public class Cast5 extends BaseCipher
public void encrypt(byte[] in, int i, byte[] out, int j, Object k, int bs)
{
if (bs != DEFAULT_BLOCK_SIZE)
- {
- throw new IllegalArgumentException();
- }
+ throw new IllegalArgumentException();
Cast5Key K = (Cast5Key) k;
-
- int L = (in[i++] & 0xFF) << 24 | (in[i++] & 0xFF) << 16
- | (in[i++] & 0xFF) << 8 | in[i++] & 0xFF;
- int R = (in[i++] & 0xFF) << 24 | (in[i++] & 0xFF) << 16
- | (in[i++] & 0xFF) << 8 | in[i] & 0xFF;
-
+ int L = (in[i++] & 0xFF) << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | in[i++] & 0xFF;
+ int R = (in[i++] & 0xFF) << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | in[i ] & 0xFF;
L ^= f1(R, K.Km0, K.Kr0);
R ^= f2(L, K.Km1, K.Kr1); // round 2
L ^= f3(R, K.Km2, K.Kr2);
@@ -1278,30 +879,29 @@ public class Cast5 extends BaseCipher
L ^= f3(R, K.Km14, K.Kr14);
R ^= f1(L, K.Km15, K.Kr15); // round 16
}
-
- out[j++] = (byte) (R >>> 24);
- out[j++] = (byte) (R >>> 16);
- out[j++] = (byte) (R >>> 8);
+ out[j++] = (byte)(R >>> 24);
+ out[j++] = (byte)(R >>> 16);
+ out[j++] = (byte)(R >>> 8);
out[j++] = (byte) R;
- out[j++] = (byte) (L >>> 24);
- out[j++] = (byte) (L >>> 16);
- out[j++] = (byte) (L >>> 8);
- out[j] = (byte) L;
+ out[j++] = (byte)(L >>> 24);
+ out[j++] = (byte)(L >>> 16);
+ out[j++] = (byte)(L >>> 8);
+ out[j ] = (byte) L;
}
public void decrypt(byte[] in, int i, byte[] out, int j, Object k, int bs)
{
if (bs != DEFAULT_BLOCK_SIZE)
- {
- throw new IllegalArgumentException();
- }
+ throw new IllegalArgumentException();
Cast5Key K = (Cast5Key) k;
-
- int L = (in[i++] & 0xFF) << 24 | (in[i++] & 0xFF) << 16
- | (in[i++] & 0xFF) << 8 | in[i++] & 0xFF;
- int R = (in[i++] & 0xFF) << 24 | (in[i++] & 0xFF) << 16
- | (in[i++] & 0xFF) << 8 | in[i] & 0xFF;
-
+ int L = (in[i++] & 0xFF) << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | in[i++] & 0xFF;
+ int R = (in[i++] & 0xFF) << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | in[i ] & 0xFF;
if (K.rounds == _16_ROUNDS)
{
L ^= f1(R, K.Km15, K.Kr15);
@@ -1321,15 +921,14 @@ public class Cast5 extends BaseCipher
R ^= f3(L, K.Km2, K.Kr2);
L ^= f2(R, K.Km1, K.Kr1);
R ^= f1(L, K.Km0, K.Kr0);
-
- out[j++] = (byte) (R >>> 24);
- out[j++] = (byte) (R >>> 16);
- out[j++] = (byte) (R >>> 8);
+ out[j++] = (byte)(R >>> 24);
+ out[j++] = (byte)(R >>> 16);
+ out[j++] = (byte)(R >>> 8);
out[j++] = (byte) R;
- out[j++] = (byte) (L >>> 24);
- out[j++] = (byte) (L >>> 16);
- out[j++] = (byte) (L >>> 8);
- out[j] = (byte) L;
+ out[j++] = (byte)(L >>> 24);
+ out[j++] = (byte)(L >>> 16);
+ out[j++] = (byte)(L >>> 8);
+ out[j ] = (byte) L;
}
public boolean selfTest()
@@ -1338,54 +937,51 @@ public class Cast5 extends BaseCipher
{
boolean result = super.selfTest(); // do symmetry tests
if (result)
- {
- result = testKat(KAT_KEY, KAT_CT, KAT_PT);
- }
+ result = testKat(KAT_KEY, KAT_CT, KAT_PT);
valid = Boolean.valueOf(result);
}
return valid.booleanValue();
}
- // helper methods ----------------------------------------------------------
-
private final int f1(int I, int m, int r)
{
I = m + I;
I = I << r | I >>> (32 - r);
- return (((S1[(I >>> 24) & 0xFF]) ^ S2[(I >>> 16) & 0xFF]) - S3[(I >>> 8) & 0xFF])
- + S4[I & 0xFF];
+ return (((S1[(I >>> 24) & 0xFF])
+ ^ S2[(I >>> 16) & 0xFF])
+ - S3[(I >>> 8) & 0xFF])
+ + S4[ I & 0xFF];
}
private final int f2(int I, int m, int r)
{
I = m ^ I;
I = I << r | I >>> (32 - r);
- return (((S1[(I >>> 24) & 0xFF]) - S2[(I >>> 16) & 0xFF]) + S3[(I >>> 8) & 0xFF])
- ^ S4[I & 0xFF];
+ return (((S1[(I >>> 24) & 0xFF])
+ - S2[(I >>> 16) & 0xFF])
+ + S3[(I >>> 8) & 0xFF])
+ ^ S4[ I & 0xFF];
}
private final int f3(int I, int m, int r)
{
I = m - I;
I = I << r | I >>> (32 - r);
- return (((S1[(I >>> 24) & 0xFF]) + S2[(I >>> 16) & 0xFF]) ^ S3[(I >>> 8) & 0xFF])
- - S4[I & 0xFF];
+ return (((S1[(I >>> 24) & 0xFF])
+ + S2[(I >>> 16) & 0xFF])
+ ^ S3[(I >>> 8) & 0xFF])
+ - S4[ I & 0xFF];
}
- // Inner class(es)
- // =========================================================================
-
/** An opaque CAST5 key object. */
private class Cast5Key
{
int rounds;
-
/** Masking session keys. */
- int Km0, Km1, Km2, Km3, Km4, Km5, Km6, Km7, Km8, Km9, Km10, Km11, Km12,
- Km13, Km14, Km15;
-
+ int Km0, Km1, Km2, Km3, Km4, Km5, Km6, Km7,
+ Km8, Km9, Km10, Km11, Km12, Km13, Km14, Km15;
/** Rotation session keys. */
- int Kr0, Kr1, Kr2, Kr3, Kr4, Kr5, Kr6, Kr7, Kr8, Kr9, Kr10, Kr11, Kr12,
- Kr13, Kr14, Kr15;
+ int Kr0, Kr1, Kr2, Kr3, Kr4, Kr5, Kr6, Kr7,
+ Kr8, Kr9, Kr10, Kr11, Kr12, Kr13, Kr14, Kr15;
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/cipher/CipherFactory.java b/libjava/classpath/gnu/javax/crypto/cipher/CipherFactory.java
index 082bfb8..d6bb422 100644
--- a/libjava/classpath/gnu/javax/crypto/cipher/CipherFactory.java
+++ b/libjava/classpath/gnu/javax/crypto/cipher/CipherFactory.java
@@ -45,105 +45,69 @@ import java.util.HashSet;
import java.util.Set;
/**
- *
null
if none is found.
- * @exception InternalError if the implementation does not pass its
- * self-test.
+ * null
if none is found.
+ * @exception InternalError if the implementation does not pass its self-test.
*/
public static final IBlockCipher getInstance(String name)
{
if (name == null)
- {
- return null;
- }
-
+ return null;
name = name.trim();
IBlockCipher result = null;
if (name.equalsIgnoreCase(ANUBIS_CIPHER))
- {
- result = new Anubis();
- }
+ result = new Anubis();
else if (name.equalsIgnoreCase(BLOWFISH_CIPHER))
- {
- result = new Blowfish();
- }
+ result = new Blowfish();
else if (name.equalsIgnoreCase(DES_CIPHER))
- {
- result = new DES();
- }
+ result = new DES();
else if (name.equalsIgnoreCase(KHAZAD_CIPHER))
- {
- result = new Khazad();
- }
+ result = new Khazad();
else if (name.equalsIgnoreCase(RIJNDAEL_CIPHER)
|| name.equalsIgnoreCase(AES_CIPHER))
- {
- result = new Rijndael();
- }
+ result = new Rijndael();
else if (name.equalsIgnoreCase(SERPENT_CIPHER))
- {
- result = new Serpent();
- }
+ result = new Serpent();
else if (name.equalsIgnoreCase(SQUARE_CIPHER))
- {
- result = new Square();
- }
+ result = new Square();
else if (name.equalsIgnoreCase(TRIPLEDES_CIPHER)
|| name.equalsIgnoreCase(DESEDE_CIPHER))
- {
- result = new TripleDES();
- }
+ result = new TripleDES();
else if (name.equalsIgnoreCase(TWOFISH_CIPHER))
- {
- result = new Twofish();
- }
+ result = new Twofish();
else if (name.equalsIgnoreCase(CAST5_CIPHER)
- || (name.equalsIgnoreCase(CAST128_CIPHER) || (name.equalsIgnoreCase(CAST_128_CIPHER))))
- {
- result = new Cast5();
- }
+ || (name.equalsIgnoreCase(CAST128_CIPHER)
+ || (name.equalsIgnoreCase(CAST_128_CIPHER))))
+ result = new Cast5();
else if (name.equalsIgnoreCase(NULL_CIPHER))
- {
- result = new NullCipher();
- }
+ result = new NullCipher();
- if (result != null && !result.selfTest())
- {
- throw new InternalError(result.name());
- }
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
return result;
}
/**
- *
*
*/
-public class DES extends BaseCipher
+public class DES
+ extends BaseCipher
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** DES operates on 64 bit blocks. */
public static final int BLOCK_SIZE = 8;
-
/** DES uses 56 bits of a 64 bit parity-adjusted key. */
public static final int KEY_SIZE = 8;
-
// S-Boxes 1 through 8.
- private static final int[] SP1 = new int[] { 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 };
-
- private static final int[] SP2 = new int[] { 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 };
-
- private static final int[] SP3 = new int[] { 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 };
-
- private static final int[] SP4 = new int[] { 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 };
-
- private static final int[] SP5 = new int[] { 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 };
-
- private static final int[] SP6 = new int[] { 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 };
-
- private static final int[] SP7 = new int[] { 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 };
-
- private static final int[] SP8 = new int[] { 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 };
-
+ private static final int[] SP1 = new int[] {
+ 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 };
+ private static final int[] SP2 = new int[] {
+ 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 };
+ private static final int[] SP3 = new int[] {
+ 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 };
+ private static final int[] SP4 = new int[] {
+ 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 };
+ private static final int[] SP5 = new int[] {
+ 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 };
+ private static final int[] SP6 = new int[] {
+ 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 };
+ private static final int[] SP7 = new int[] {
+ 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 };
+ private static final int[] SP8 = new int[] {
+ 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 };
/**
* Constants that help in determining whether or not a byte array is parity
* adjusted.
*/
- private static final byte[] PARITY = { 8, 1, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8,
- 0, 2, 8, 0, 8, 8, 0, 8, 0, 0, 8, 8, 0,
- 0, 8, 0, 8, 8, 3, 0, 8, 8, 0, 8, 0, 0,
- 8, 8, 0, 0, 8, 0, 8, 8, 0, 8, 0, 0, 8,
- 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 0, 8, 0,
- 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8,
- 8, 0, 8, 0, 0, 8, 0, 8, 8, 0, 0, 8, 8,
- 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0,
- 0, 8, 8, 0, 8, 0, 0, 8, 0, 8, 8, 0, 8,
- 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0, 0, 8,
- 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8,
- 0, 8, 0, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0,
- 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0, 0,
- 8, 8, 0, 8, 0, 0, 8, 0, 8, 8, 0, 8, 0,
- 0, 8, 8, 0, 0, 8, 0, 8, 8, 0, 8, 0, 0,
- 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 0, 8,
- 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0,
- 8, 8, 0, 4, 8, 8, 0, 8, 0, 0, 8, 8, 0,
- 0, 8, 0, 8, 8, 0, 8, 5, 0, 8, 0, 8, 8,
- 0, 0, 8, 8, 0, 8, 0, 6, 8 };
-
+ private static final byte[] PARITY = {
+ 8, 1, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 2, 8,
+ 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 3,
+ 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0,
+ 8, 0, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 0, 8,
+ 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0,
+ 8, 0, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 0, 8,
+ 8, 0, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 0, 8,
+ 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0,
+ 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0,
+ 8, 0, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 0, 8,
+ 8, 0, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 0, 8,
+ 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0,
+ 8, 0, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 0, 8,
+ 0, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0,
+ 4, 8, 8, 0, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8, 8, 0,
+ 8, 5, 0, 8, 0, 8, 8, 0, 0, 8, 8, 0, 8, 0, 6, 8 };
// Key schedule constants.
-
- private static final byte[] ROTARS = { 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19,
- 21, 23, 25, 27, 28 };
-
- private static final 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 };
-
- private static final 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 };
-
+ private static final byte[] ROTARS = {
+ 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28 };
+ private static final 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 };
+ private static final 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 };
/**
* Weak keys (parity adjusted): If all the bits in each half are either 0
* or 1, then the key used for any cycle of the algorithm is the same as
* all other cycles.
*/
public static final byte[][] WEAK_KEYS = {
- Util.toBytesFromString("0101010101010101"),
- Util.toBytesFromString("01010101FEFEFEFE"),
- Util.toBytesFromString("FEFEFEFE01010101"),
- Util.toBytesFromString("FEFEFEFEFEFEFEFE") };
-
+ Util.toBytesFromString("0101010101010101"),
+ Util.toBytesFromString("01010101FEFEFEFE"),
+ Util.toBytesFromString("FEFEFEFE01010101"),
+ Util.toBytesFromString("FEFEFEFEFEFEFEFE") };
/**
* Semi-weak keys (parity adjusted): Some pairs of keys encrypt plain text
* to identical cipher text. In other words, one key in the pair can decrypt
@@ -403,73 +219,69 @@ public class DES extends BaseCipher
* generated, these semi-weak keys produce only two different sub-keys.
*/
public static final byte[][] SEMIWEAK_KEYS = {
- Util.toBytesFromString("01FE01FE01FE01FE"),
- Util.toBytesFromString("FE01FE01FE01FE01"),
- Util.toBytesFromString("1FE01FE00EF10EF1"),
- Util.toBytesFromString("E01FE01FF10EF10E"),
- Util.toBytesFromString("01E001E001F101F1"),
- Util.toBytesFromString("E001E001F101F101"),
- Util.toBytesFromString("1FFE1FFE0EFE0EFE"),
- Util.toBytesFromString("FE1FFE1FFE0EFE0E"),
- Util.toBytesFromString("011F011F010E010E"),
- Util.toBytesFromString("1F011F010E010E01"),
- Util.toBytesFromString("E0FEE0FEF1FEF1FE"),
- Util.toBytesFromString("FEE0FEE0FEF1FEF1") };
-
+ Util.toBytesFromString("01FE01FE01FE01FE"),
+ Util.toBytesFromString("FE01FE01FE01FE01"),
+ Util.toBytesFromString("1FE01FE00EF10EF1"),
+ Util.toBytesFromString("E01FE01FF10EF10E"),
+ Util.toBytesFromString("01E001E001F101F1"),
+ Util.toBytesFromString("E001E001F101F101"),
+ Util.toBytesFromString("1FFE1FFE0EFE0EFE"),
+ Util.toBytesFromString("FE1FFE1FFE0EFE0E"),
+ Util.toBytesFromString("011F011F010E010E"),
+ Util.toBytesFromString("1F011F010E010E01"),
+ Util.toBytesFromString("E0FEE0FEF1FEF1FE"),
+ Util.toBytesFromString("FEE0FEE0FEF1FEF1") };
/** Possible weak keys (parity adjusted) --produce 4 instead of 16 subkeys. */
public static final byte[][] POSSIBLE_WEAK_KEYS = {
- Util.toBytesFromString("1F1F01010E0E0101"),
- Util.toBytesFromString("011F1F01010E0E01"),
- Util.toBytesFromString("1F01011F0E01010E"),
- Util.toBytesFromString("01011F1F01010E0E"),
- Util.toBytesFromString("E0E00101F1F10101"),
- Util.toBytesFromString("FEFE0101FEFE0101"),
- Util.toBytesFromString("FEE01F01FEF10E01"),
- Util.toBytesFromString("E0FE1F01F1FE0E01"),
- Util.toBytesFromString("FEE0011FFEF1010E"),
- Util.toBytesFromString("E0FE011FF1FE010E"),
- Util.toBytesFromString("E0E01F1FF1F10E0E"),
- Util.toBytesFromString("FEFE1F1FFEFE0E0E"),
- Util.toBytesFromString("1F1F01010E0E0101"),
- Util.toBytesFromString("011F1F01010E0E01"),
- Util.toBytesFromString("1F01011F0E01010E"),
- Util.toBytesFromString("01011F1F01010E0E"),
- Util.toBytesFromString("01E0E00101F1F101"),
- Util.toBytesFromString("1FFEE0010EFEF001"),
- Util.toBytesFromString("1FE0FE010EF1FE01"),
- Util.toBytesFromString("01FEFE0101FEFE01"),
- Util.toBytesFromString("1FE0E01F0EF1F10E"),
- Util.toBytesFromString("01FEE01F01FEF10E"),
- Util.toBytesFromString("01E0FE1F01F1FE0E"),
- Util.toBytesFromString("1FFEFE1F0EFEFE0E"),
-
- Util.toBytesFromString("E00101E0F10101F1"),
- Util.toBytesFromString("FE1F01E0FE0E0EF1"),
- Util.toBytesFromString("FE011FE0FE010EF1"),
- Util.toBytesFromString("E01F1FE0F10E0EF1"),
- Util.toBytesFromString("FE0101FEFE0101FE"),
- Util.toBytesFromString("E01F01FEF10E01FE"),
- Util.toBytesFromString("E0011FFEF1010EFE"),
- Util.toBytesFromString("FE1F1FFEFE0E0EFE"),
- Util.toBytesFromString("1FFE01E00EFE01F1"),
- Util.toBytesFromString("01FE1FE001FE0EF1"),
- Util.toBytesFromString("1FE001FE0EF101FE"),
- Util.toBytesFromString("01E01FFE01F10EFE"),
- Util.toBytesFromString("0101E0E00101F1F1"),
- Util.toBytesFromString("1F1FE0E00E0EF1F1"),
- Util.toBytesFromString("1F01FEE00E01FEF1"),
- Util.toBytesFromString("011FFEE0010EFEF1"),
- Util.toBytesFromString("1F01E0FE0E01F1FE"),
- Util.toBytesFromString("011FE0FE010EF1FE"),
- Util.toBytesFromString("0101FEFE0001FEFE"),
- Util.toBytesFromString("1F1FFEFE0E0EFEFE"),
- Util.toBytesFromString("FEFEE0E0FEFEF1F1"),
- Util.toBytesFromString("E0FEFEE0F1FEFEF1"),
- Util.toBytesFromString("FEE0E0FEFEF1F1FE"),
- Util.toBytesFromString("E0E0FEFEF1F1FEFE") };
-
- // Constructor(s)
- // -------------------------------------------------------------------------
+ Util.toBytesFromString("1F1F01010E0E0101"),
+ Util.toBytesFromString("011F1F01010E0E01"),
+ Util.toBytesFromString("1F01011F0E01010E"),
+ Util.toBytesFromString("01011F1F01010E0E"),
+ Util.toBytesFromString("E0E00101F1F10101"),
+ Util.toBytesFromString("FEFE0101FEFE0101"),
+ Util.toBytesFromString("FEE01F01FEF10E01"),
+ Util.toBytesFromString("E0FE1F01F1FE0E01"),
+ Util.toBytesFromString("FEE0011FFEF1010E"),
+ Util.toBytesFromString("E0FE011FF1FE010E"),
+ Util.toBytesFromString("E0E01F1FF1F10E0E"),
+ Util.toBytesFromString("FEFE1F1FFEFE0E0E"),
+ Util.toBytesFromString("1F1F01010E0E0101"),
+ Util.toBytesFromString("011F1F01010E0E01"),
+ Util.toBytesFromString("1F01011F0E01010E"),
+ Util.toBytesFromString("01011F1F01010E0E"),
+ Util.toBytesFromString("01E0E00101F1F101"),
+ Util.toBytesFromString("1FFEE0010EFEF001"),
+ Util.toBytesFromString("1FE0FE010EF1FE01"),
+ Util.toBytesFromString("01FEFE0101FEFE01"),
+ Util.toBytesFromString("1FE0E01F0EF1F10E"),
+ Util.toBytesFromString("01FEE01F01FEF10E"),
+ Util.toBytesFromString("01E0FE1F01F1FE0E"),
+ Util.toBytesFromString("1FFEFE1F0EFEFE0E"),
+
+ Util.toBytesFromString("E00101E0F10101F1"),
+ Util.toBytesFromString("FE1F01E0FE0E0EF1"),
+ Util.toBytesFromString("FE011FE0FE010EF1"),
+ Util.toBytesFromString("E01F1FE0F10E0EF1"),
+ Util.toBytesFromString("FE0101FEFE0101FE"),
+ Util.toBytesFromString("E01F01FEF10E01FE"),
+ Util.toBytesFromString("E0011FFEF1010EFE"),
+ Util.toBytesFromString("FE1F1FFEFE0E0EFE"),
+ Util.toBytesFromString("1FFE01E00EFE01F1"),
+ Util.toBytesFromString("01FE1FE001FE0EF1"),
+ Util.toBytesFromString("1FE001FE0EF101FE"),
+ Util.toBytesFromString("01E01FFE01F10EFE"),
+ Util.toBytesFromString("0101E0E00101F1F1"),
+ Util.toBytesFromString("1F1FE0E00E0EF1F1"),
+ Util.toBytesFromString("1F01FEE00E01FEF1"),
+ Util.toBytesFromString("011FFEE0010EFEF1"),
+ Util.toBytesFromString("1F01E0FE0E01F1FE"),
+ Util.toBytesFromString("011FE0FE010EF1FE"),
+ Util.toBytesFromString("0101FEFE0001FEFE"),
+ Util.toBytesFromString("1F1FFEFE0E0EFEFE"),
+ Util.toBytesFromString("FEFEE0E0FEFEF1F1"),
+ Util.toBytesFromString("E0FEFEE0F1FEFEF1"),
+ Util.toBytesFromString("FEE0E0FEFEF1F1FE"),
+ Util.toBytesFromString("E0E0FEFEF1F1FEFE") };
/** Default 0-argument constructor. */
public DES()
@@ -477,28 +289,23 @@ public class DES extends BaseCipher
super(Registry.DES_CIPHER, BLOCK_SIZE, KEY_SIZE);
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
- * true
if the key is weak.
*/
public static boolean isWeak(byte[] kb)
{
- // return Arrays.equals(kb, WEAK_KEYS[0]) || Arrays.equals(kb, WEAK_KEYS[1])
- // || Arrays.equals(kb, WEAK_KEYS[2]) || Arrays.equals(kb, WEAK_KEYS[3])
- // || Arrays.equals(kb, WEAK_KEYS[4]) || Arrays.equals(kb, WEAK_KEYS[5])
- // || Arrays.equals(kb, WEAK_KEYS[6]) || Arrays.equals(kb, WEAK_KEYS[7]);
for (int i = 0; i < WEAK_KEYS.length; i++)
- {
- if (Arrays.equals(WEAK_KEYS[i], kb))
- {
- return true;
- }
- }
+ if (Arrays.equals(WEAK_KEYS[i], kb))
+ return true;
return false;
}
/**
- * true
if this key is semi-weak.
*/
public static boolean isSemiWeak(byte[] kb)
{
- // return Arrays.equals(kb, SEMIWEAK_KEYS[0])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[1])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[2])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[3])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[4])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[5])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[6])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[7])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[8])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[9])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[10])
- // || Arrays.equals(kb, SEMIWEAK_KEYS[11]);
for (int i = 0; i < SEMIWEAK_KEYS.length; i++)
- {
- if (Arrays.equals(SEMIWEAK_KEYS[i], kb))
- {
- return true;
- }
- }
+ if (Arrays.equals(SEMIWEAK_KEYS[i], kb))
+ return true;
return false;
}
/**
- * true
if kb
represents a possibly weak key.
@@ -588,18 +371,14 @@ public class DES extends BaseCipher
public static boolean isPossibleWeak(byte[] kb)
{
for (int i = 0; i < POSSIBLE_WEAK_KEYS.length; i++)
- {
- if (Arrays.equals(POSSIBLE_WEAK_KEYS[i], kb))
- {
- return true;
- }
- }
+ if (Arrays.equals(POSSIBLE_WEAK_KEYS[i], kb))
+ return true;
return false;
}
/**
- *
- *
- *
- * reset()
is invoked on the instance. Furthermore, the size of
- * this key material shall be taken as an indication on the key size in which
- * to operate this instance.reset()
is invoked on the instance. Furthermore, the size of
+ * this key material shall be taken as an indication on the key size in which to
+ * operate this instance.in
from which to start considering
- * data.
+ * data.
* @param out the ciphertext.
* @param outOffset index of out
from which to store result.
* @exception IllegalStateException if the instance is not initialised.
@@ -181,11 +171,11 @@ public interface IBlockCipher extends Cloneable
throws IllegalStateException;
/**
- * in
from which to start considering
- * data.
+ * data.
* @param out the ciphertext.
* @param outOffset index of out
from which to store result.
* @exception IllegalStateException if the instance is not initialised.
@@ -194,12 +184,12 @@ public interface IBlockCipher extends Cloneable
throws IllegalStateException;
/**
- * true
if the implementation passes simple
- * correctness tests. Returns false
otherwise.
+ * correctness tests. Returns false
otherwise.
*/
boolean selfTest();
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/cipher/IBlockCipherSpi.java b/libjava/classpath/gnu/javax/crypto/cipher/IBlockCipherSpi.java
index 6fe07ca..1023b12 100644
--- a/libjava/classpath/gnu/javax/crypto/cipher/IBlockCipherSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/cipher/IBlockCipherSpi.java
@@ -42,38 +42,32 @@ import java.security.InvalidKeyException;
import java.util.Iterator;
/**
- * Iterator
over the supported block sizes.
*/
Iterator blockSizes();
/**
- * Iterator
over the supported key sizes.
*/
Iterator keySizes();
/**
- * in
from which to start considering
- * data.
+ * data.
* @param out the ciphertext.
- * @param outOffset index of out
from which to store the result.
+ * @param outOffset index of out
from which to store the
+ * result.
* @param k the session key to use.
* @param bs the block size to use.
* @exception IllegalArgumentException if the block size is invalid.
* @exception ArrayIndexOutOfBoundsException if there is not enough room in
- * either the plaintext or ciphertext buffers.
+ * either the plaintext or ciphertext buffers.
*/
void encrypt(byte[] in, int inOffset, byte[] out, int outOffset, Object k,
int bs);
/**
- * in
from which to start considering
- * data.
+ * data.
* @param out the plaintext.
- * @param outOffset index of out
from which to store the result.
+ * @param outOffset index of out
from which to store the
+ * result.
* @param k the session key to use.
* @param bs the block size to use.
* @exception IllegalArgumentException if the block size is invalid.
* @exception ArrayIndexOutOfBoundsException if there is not enough room in
- * either the plaintext or ciphertext buffers.
+ * either the plaintext or ciphertext buffers.
*/
void decrypt(byte[] in, int inOffset, byte[] out, int outOffset, Object k,
int bs);
/**
- * true
if the implementation passes simple
- * correctness tests. Returns false
otherwise.
+ * correctness tests. Returns false
otherwise.
*/
boolean selfTest();
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/cipher/Khazad.java b/libjava/classpath/gnu/javax/crypto/cipher/Khazad.java
index 3a95874..491301f 100644
--- a/libjava/classpath/gnu/javax/crypto/cipher/Khazad.java
+++ b/libjava/classpath/gnu/javax/crypto/cipher/Khazad.java
@@ -38,113 +38,79 @@ exception statement from your version. */
package gnu.javax.crypto.cipher;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-//import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
+import java.util.logging.Logger;
/**
- *
- *
*/
-public final class Khazad extends BaseCipher
+public final class Khazad
+ extends BaseCipher
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- // private static final String NAME = "khazad";
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- // private static final PrintWriter err = new PrintWriter(System.out, true);
- // private static void debug(String s) {
- // err.println(">>> "+NAME+": "+s);
- // }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Khazad.class.getName());
private static final int DEFAULT_BLOCK_SIZE = 8; // in bytes
-
private static final int DEFAULT_KEY_SIZE = 16; // in bytes
-
private static final int R = 8; // standard number of rounds; para. 3.7
-
private static final String Sd = // p. 20 [KHAZAD]
- "\uBA54\u2F74\u53D3\uD24D\u50AC\u8DBF\u7052\u9A4C"
- + "\uEAD5\u97D1\u3351\u5BA6\uDE48\uA899\uDB32\uB7FC"
- + "\uE39E\u919B\uE2BB\u416E\uA5CB\u6B95\uA1F3\uB102"
- + "\uCCC4\u1D14\uC363\uDA5D\u5FDC\u7DCD\u7F5A\u6C5C"
- + "\uF726\uFFED\uE89D\u6F8E\u19A0\uF089\u0F07\uAFFB"
- + "\u0815\u0D04\u0164\uDF76\u79DD\u3D16\u3F37\u6D38"
- + "\uB973\uE935\u5571\u7B8C\u7288\uF62A\u3E5E\u2746"
- + "\u0C65\u6861\u03C1\u57D6\uD958\uD866\uD73A\uC83C"
- + "\uFA96\uA798\uECB8\uC7AE\u694B\uABA9\u670A\u47F2"
- + "\uB522\uE5EE\uBE2B\u8112\u831B\u0E23\uF545\u21CE"
- + "\u492C\uF9E6\uB628\u1782\u1A8B\uFE8A\u09C9\u874E"
- + "\uE12E\uE4E0\uEB90\uA41E\u8560\u0025\uF4F1\u940B"
- + "\uE775\uEF34\u31D4\uD086\u7EAD\uFD29\u303B\u9FF8"
- + "\uC613\u0605\uC511\u777C\u7A78\u361C\u3959\u1856"
- + "\uB3B0\u2420\uB292\uA3C0\u4462\u10B4\u8443\u93C2"
- + "\u4ABD\u8F2D\uBC9C\u6A40\uCFA2\u804F\u1FCA\uAA42";
-
+ "\uBA54\u2F74\u53D3\uD24D\u50AC\u8DBF\u7052\u9A4C"
+ + "\uEAD5\u97D1\u3351\u5BA6\uDE48\uA899\uDB32\uB7FC"
+ + "\uE39E\u919B\uE2BB\u416E\uA5CB\u6B95\uA1F3\uB102"
+ + "\uCCC4\u1D14\uC363\uDA5D\u5FDC\u7DCD\u7F5A\u6C5C"
+ + "\uF726\uFFED\uE89D\u6F8E\u19A0\uF089\u0F07\uAFFB"
+ + "\u0815\u0D04\u0164\uDF76\u79DD\u3D16\u3F37\u6D38"
+ + "\uB973\uE935\u5571\u7B8C\u7288\uF62A\u3E5E\u2746"
+ + "\u0C65\u6861\u03C1\u57D6\uD958\uD866\uD73A\uC83C"
+ + "\uFA96\uA798\uECB8\uC7AE\u694B\uABA9\u670A\u47F2"
+ + "\uB522\uE5EE\uBE2B\u8112\u831B\u0E23\uF545\u21CE"
+ + "\u492C\uF9E6\uB628\u1782\u1A8B\uFE8A\u09C9\u874E"
+ + "\uE12E\uE4E0\uEB90\uA41E\u8560\u0025\uF4F1\u940B"
+ + "\uE775\uEF34\u31D4\uD086\u7EAD\uFD29\u303B\u9FF8"
+ + "\uC613\u0605\uC511\u777C\u7A78\u361C\u3959\u1856"
+ + "\uB3B0\u2420\uB292\uA3C0\u4462\u10B4\u8443\u93C2"
+ + "\u4ABD\u8F2D\uBC9C\u6A40\uCFA2\u804F\u1FCA\uAA42";
private static final byte[] S = new byte[256];
-
private static final int[] T0 = new int[256];
-
private static final int[] T1 = new int[256];
-
private static final int[] T2 = new int[256];
-
private static final int[] T3 = new int[256];
-
private static final int[] T4 = new int[256];
-
private static final int[] T5 = new int[256];
-
private static final int[] T6 = new int[256];
-
private static final int[] T7 = new int[256];
-
private static final int[][] rc = new int[R + 1][2]; // round constants
-
/**
- * KAT vector (from ecb_vk):
- * I=120
- * KEY=00000000000000000000000000000100
+ * KAT vector (from ecb_vk): I=120 KEY=00000000000000000000000000000100
* CT=A0C86A1BBE2CBF4C
*/
- private static final byte[] KAT_KEY = Util.toBytesFromString("00000000000000000000000000000100");
-
+ private static final byte[] KAT_KEY =
+ Util.toBytesFromString("00000000000000000000000000000100");
private static final byte[] KAT_CT = Util.toBytesFromString("A0C86A1BBE2CBF4C");
-
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
- // Static code - to intialise lookup tables --------------------------------
-
static
{
long time = System.currentTimeMillis();
-
long ROOT = 0x11d; // para. 2.1 [KHAZAD]
int i, j;
int s, s2, s3, s4, s5, s6, s7, s8, sb;
@@ -154,198 +120,177 @@ public final class Khazad extends BaseCipher
c = Sd.charAt(i >>> 1);
s = ((i & 1) == 0 ? c >>> 8 : c) & 0xFF;
S[i] = (byte) s;
-
s2 = s << 1;
if (s2 > 0xFF)
s2 ^= ROOT;
-
s3 = s2 ^ s;
s4 = s2 << 1;
if (s4 > 0xFF)
s4 ^= ROOT;
-
s5 = s4 ^ s;
s6 = s4 ^ s2;
s7 = s6 ^ s;
s8 = s4 << 1;
if (s8 > 0xFF)
s8 ^= ROOT;
-
sb = s8 ^ s2 ^ s;
-
- T0[i] = s << 24 | s3 << 16 | s4 << 8 | s5;
- T1[i] = s3 << 24 | s << 16 | s5 << 8 | s4;
- T2[i] = s4 << 24 | s5 << 16 | s << 8 | s3;
+ T0[i] = s << 24 | s3 << 16 | s4 << 8 | s5;
+ T1[i] = s3 << 24 | s << 16 | s5 << 8 | s4;
+ T2[i] = s4 << 24 | s5 << 16 | s << 8 | s3;
T3[i] = s5 << 24 | s4 << 16 | s3 << 8 | s;
T4[i] = s6 << 24 | s8 << 16 | sb << 8 | s7;
T5[i] = s8 << 24 | s6 << 16 | s7 << 8 | sb;
T6[i] = sb << 24 | s7 << 16 | s6 << 8 | s8;
T7[i] = s7 << 24 | sb << 16 | s8 << 8 | s6;
}
-
- for (i = 0, j = 0; i < R + 1; i++)
+ for (i = 0, j = 0; i < R + 1; i++) // compute round constant
{
- // compute round constant
- rc[i][0] = S[j++] << 24 | (S[j++] & 0xFF) << 16
- | (S[j++] & 0xFF) << 8 | (S[j++] & 0xFF);
- rc[i][1] = S[j++] << 24 | (S[j++] & 0xFF) << 16
- | (S[j++] & 0xFF) << 8 | (S[j++] & 0xFF);
+ rc[i][0] = S[j++] << 24
+ | (S[j++] & 0xFF) << 16
+ | (S[j++] & 0xFF) << 8
+ | (S[j++] & 0xFF);
+ rc[i][1] = S[j++] << 24
+ | (S[j++] & 0xFF) << 16
+ | (S[j++] & 0xFF) << 8
+ | (S[j++] & 0xFF);
}
-
time = System.currentTimeMillis() - time;
-
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static data");
- System.out.println();
-
- System.out.println();
- System.out.println("T0[]:");
+ log.fine("Static data");
+ log.fine("T0[]:");
+ StringBuilder b;
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T0[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T0[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T1[]:");
+ log.fine("T1[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T1[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T1[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T2[]:");
+ log.fine("T2[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T2[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T2[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T3[]:");
+ log.fine("T3[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T3[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T3[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T4[]:");
+ log.fine("T4[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T4[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T4[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T5[]:");
+ log.fine("T5[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T6[]:");
+ log.fine("T6[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T6[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T6[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("T7[]:");
+ log.fine("T7[]:");
for (i = 0; i < 64; i++)
{
+ b = new StringBuilder();
for (j = 0; j < 4; j++)
- System.out.print("0x" + Util.toString(T7[i * 4 + j]) + ", ");
- System.out.println();
+ b.append("0x").append(Util.toString(T7[i * 4 + j])).append(", ");
+ log.fine(b.toString());
}
- System.out.println();
- System.out.println("rc[]:");
+ log.fine("rc[]:");
for (i = 0; i < R + 1; i++)
- System.out.print("0x" + Util.toString(rc[i][0])
- + Util.toString(rc[i][1]));
- System.out.println();
-
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("0x" + Util.toString(rc[i][0]) + Util.toString(rc[i][1]));
+ log.fine("Total initialization time: " + time + " ms.");
}
}
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Khazad()
{
super(Registry.KHAZAD_CIPHER, DEFAULT_BLOCK_SIZE, DEFAULT_KEY_SIZE);
}
- // Class methods
- // -------------------------------------------------------------------------
-
private static void khazad(byte[] in, int i, byte[] out, int j, int[][] K)
{
// sigma(K[0])
int k0 = K[0][0];
int k1 = K[0][1];
- int a0 = (in[i++] << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i++] & 0xFF))
- ^ k0;
- int a1 = (in[i++] << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i] & 0xFF))
- ^ k1;
-
+ int a0 = (in[i++] << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i++] & 0xFF) ) ^ k0;
+ int a1 = (in[i++] << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i ] & 0xFF) ) ^ k1;
int b0, b1;
// round function
for (int r = 1; r < R; r++)
{
k0 = K[r][0];
k1 = K[r][1];
- b0 = T0[a0 >>> 24] ^ T1[(a0 >>> 16) & 0xFF] ^ T2[(a0 >>> 8) & 0xFF]
- ^ T3[a0 & 0xFF] ^ T4[a1 >>> 24] ^ T5[(a1 >>> 16) & 0xFF]
- ^ T6[(a1 >>> 8) & 0xFF] ^ T7[a1 & 0xFF] ^ k0;
- b1 = T0[a1 >>> 24] ^ T1[(a1 >>> 16) & 0xFF] ^ T2[(a1 >>> 8) & 0xFF]
- ^ T3[a1 & 0xFF] ^ T4[a0 >>> 24] ^ T5[(a0 >>> 16) & 0xFF]
- ^ T6[(a0 >>> 8) & 0xFF] ^ T7[a0 & 0xFF] ^ k1;
+ b0 = T0[ a0 >>> 24 ]
+ ^ T1[(a0 >>> 16) & 0xFF]
+ ^ T2[(a0 >>> 8) & 0xFF]
+ ^ T3[ a0 & 0xFF]
+ ^ T4[ a1 >>> 24 ]
+ ^ T5[(a1 >>> 16) & 0xFF]
+ ^ T6[(a1 >>> 8) & 0xFF]
+ ^ T7[ a1 & 0xFF] ^ k0;
+ b1 = T0[ a1 >>> 24 ]
+ ^ T1[(a1 >>> 16) & 0xFF]
+ ^ T2[(a1 >>> 8) & 0xFF]
+ ^ T3[ a1 & 0xFF]
+ ^ T4[ a0 >>> 24 ]
+ ^ T5[(a0 >>> 16) & 0xFF]
+ ^ T6[(a0 >>> 8) & 0xFF]
+ ^ T7[ a0 & 0xFF] ^ k1;
a0 = b0;
a1 = b1;
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("T" + r + "=" + Util.toString(a0)
- + Util.toString(a1));
- }
+ if (Configuration.DEBUG)
+ log.fine("T" + r + "=" + Util.toString(a0) + Util.toString(a1));
}
-
// sigma(K[R]) o gamma applied to previous output
k0 = K[R][0];
k1 = K[R][1];
-
- out[j++] = (byte) (S[a0 >>> 24] ^ (k0 >>> 24));
- out[j++] = (byte) (S[(a0 >>> 16) & 0xFF] ^ (k0 >>> 16));
- out[j++] = (byte) (S[(a0 >>> 8) & 0xFF] ^ (k0 >>> 8));
- out[j++] = (byte) (S[a0 & 0xFF] ^ k0);
- out[j++] = (byte) (S[a1 >>> 24] ^ (k1 >>> 24));
- out[j++] = (byte) (S[(a1 >>> 16) & 0xFF] ^ (k1 >>> 16));
- out[j++] = (byte) (S[(a1 >>> 8) & 0xFF] ^ (k1 >>> 8));
- out[j] = (byte) (S[a1 & 0xFF] ^ k1);
-
- if (DEBUG && debuglevel > 6)
- {
- System.out.println("T=" + Util.toString(out, j - 7, 8));
- System.out.println();
- }
+ out[j++] = (byte)(S[ a0 >>> 24 ] ^ (k0 >>> 24));
+ out[j++] = (byte)(S[(a0 >>> 16) & 0xFF] ^ (k0 >>> 16));
+ out[j++] = (byte)(S[(a0 >>> 8) & 0xFF] ^ (k0 >>> 8));
+ out[j++] = (byte)(S[ a0 & 0xFF] ^ k0 );
+ out[j++] = (byte)(S[ a1 >>> 24 ] ^ (k1 >>> 24));
+ out[j++] = (byte)(S[(a1 >>> 16) & 0xFF] ^ (k1 >>> 16));
+ out[j++] = (byte)(S[(a1 >>> 8) & 0xFF] ^ (k1 >>> 8));
+ out[j ] = (byte)(S[ a1 & 0xFF] ^ k1 );
+ if (Configuration.DEBUG)
+ log.fine("T=" + Util.toString(out, j - 7, 8) + "\n");
}
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.lang.Cloneable interface implementation ----------------------------
-
public Object clone()
{
Khazad result = new Khazad();
@@ -354,12 +299,10 @@ public final class Khazad extends BaseCipher
return result;
}
- // IBlockCipherSpi interface implementation --------------------------------
-
public Iterator blockSizes()
{
ArrayList al = new ArrayList();
- al.add(new Integer(DEFAULT_BLOCK_SIZE));
+ al.add(Integer.valueOf(DEFAULT_BLOCK_SIZE));
return Collections.unmodifiableList(al).iterator();
}
@@ -367,15 +310,14 @@ public final class Khazad extends BaseCipher
public Iterator keySizes()
{
ArrayList al = new ArrayList();
- al.add(new Integer(DEFAULT_KEY_SIZE));
-
+ al.add(Integer.valueOf(DEFAULT_KEY_SIZE));
return Collections.unmodifiableList(al).iterator();
}
/**
- *
- * Paulo S.L.M. Barreto and
- * Vincent Rijmen.
+ * Paulo S.L.M. Barreto and Vincent Rijmen.
- *
*/
-public final class Rijndael extends BaseCipher
+public final class Rijndael
+ extends BaseCipher
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- // private static final String NAME = "rijndael";
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 9;
-
- // private static final PrintWriter err = new PrintWriter(System.out, true);
- // private static void debug(String s) {
- // err.println(">>> "+NAME+": "+s);
- // }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(Rijndael.class.getName());
private static final int DEFAULT_BLOCK_SIZE = 16; // in bytes
-
private static final int DEFAULT_KEY_SIZE = 16; // in bytes
-
- private static final String SS = "\u637C\u777B\uF26B\u6FC5\u3001\u672B\uFED7\uAB76"
- + "\uCA82\uC97D\uFA59\u47F0\uADD4\uA2AF\u9CA4\u72C0"
- + "\uB7FD\u9326\u363F\uF7CC\u34A5\uE5F1\u71D8\u3115"
- + "\u04C7\u23C3\u1896\u059A\u0712\u80E2\uEB27\uB275"
- + "\u0983\u2C1A\u1B6E\u5AA0\u523B\uD6B3\u29E3\u2F84"
- + "\u53D1\u00ED\u20FC\uB15B\u6ACB\uBE39\u4A4C\u58CF"
- + "\uD0EF\uAAFB\u434D\u3385\u45F9\u027F\u503C\u9FA8"
- + "\u51A3\u408F\u929D\u38F5\uBCB6\uDA21\u10FF\uF3D2"
- + "\uCD0C\u13EC\u5F97\u4417\uC4A7\u7E3D\u645D\u1973"
- + "\u6081\u4FDC\u222A\u9088\u46EE\uB814\uDE5E\u0BDB"
- + "\uE032\u3A0A\u4906\u245C\uC2D3\uAC62\u9195\uE479"
- + "\uE7C8\u376D\u8DD5\u4EA9\u6C56\uF4EA\u657A\uAE08"
- + "\uBA78\u252E\u1CA6\uB4C6\uE8DD\u741F\u4BBD\u8B8A"
- + "\u703E\uB566\u4803\uF60E\u6135\u57B9\u86C1\u1D9E"
- + "\uE1F8\u9811\u69D9\u8E94\u9B1E\u87E9\uCE55\u28DF"
- + "\u8CA1\u890D\uBFE6\u4268\u4199\u2D0F\uB054\uBB16";
-
+ private static final String SS =
+ "\u637C\u777B\uF26B\u6FC5\u3001\u672B\uFED7\uAB76"
+ + "\uCA82\uC97D\uFA59\u47F0\uADD4\uA2AF\u9CA4\u72C0"
+ + "\uB7FD\u9326\u363F\uF7CC\u34A5\uE5F1\u71D8\u3115"
+ + "\u04C7\u23C3\u1896\u059A\u0712\u80E2\uEB27\uB275"
+ + "\u0983\u2C1A\u1B6E\u5AA0\u523B\uD6B3\u29E3\u2F84"
+ + "\u53D1\u00ED\u20FC\uB15B\u6ACB\uBE39\u4A4C\u58CF"
+ + "\uD0EF\uAAFB\u434D\u3385\u45F9\u027F\u503C\u9FA8"
+ + "\u51A3\u408F\u929D\u38F5\uBCB6\uDA21\u10FF\uF3D2"
+ + "\uCD0C\u13EC\u5F97\u4417\uC4A7\u7E3D\u645D\u1973"
+ + "\u6081\u4FDC\u222A\u9088\u46EE\uB814\uDE5E\u0BDB"
+ + "\uE032\u3A0A\u4906\u245C\uC2D3\uAC62\u9195\uE479"
+ + "\uE7C8\u376D\u8DD5\u4EA9\u6C56\uF4EA\u657A\uAE08"
+ + "\uBA78\u252E\u1CA6\uB4C6\uE8DD\u741F\u4BBD\u8B8A"
+ + "\u703E\uB566\u4803\uF60E\u6135\u57B9\u86C1\u1D9E"
+ + "\uE1F8\u9811\u69D9\u8E94\u9B1E\u87E9\uCE55\u28DF"
+ + "\u8CA1\u890D\uBFE6\u4268\u4199\u2D0F\uB054\uBB16";
private static final byte[] S = new byte[256];
-
private static final byte[] Si = new byte[256];
-
private static final int[] T1 = new int[256];
-
private static final int[] T2 = new int[256];
-
private static final int[] T3 = new int[256];
-
private static final int[] T4 = new int[256];
-
private static final int[] T5 = new int[256];
-
private static final int[] T6 = new int[256];
-
private static final int[] T7 = new int[256];
-
private static final int[] T8 = new int[256];
-
private static final int[] U1 = new int[256];
-
private static final int[] U2 = new int[256];
-
private static final int[] U3 = new int[256];
-
private static final int[] U4 = new int[256];
-
private static final byte[] rcon = new byte[30];
-
private static final int[][][] shifts = new int[][][] {
- { { 0, 0 }, { 1, 3 },
- { 2, 2 }, { 3, 1 } },
- { { 0, 0 }, { 1, 5 },
- { 2, 4 }, { 3, 3 } },
- { { 0, 0 }, { 1, 7 },
- { 3, 5 }, { 4, 4 } } };
-
+ { { 0, 0 }, { 1, 3 }, { 2, 2 }, { 3, 1 } },
+ { { 0, 0 }, { 1, 5 }, { 2, 4 }, { 3, 3 } },
+ { { 0, 0 }, { 1, 7 }, { 3, 5 }, { 4, 4 } } };
/**
- * KAT vector (from ecb_vk):
- * I=96
+ * KAT vector (from ecb_vk): I=96
* KEY=0000000000000000000000010000000000000000000000000000000000000000
* CT=E44429474D6FC3084EB2A6B8B46AF754
*/
- private static final byte[] KAT_KEY = Util.toBytesFromString("0000000000000000000000010000000000000000000000000000000000000000");
-
- private static final byte[] KAT_CT = Util.toBytesFromString("E44429474D6FC3084EB2A6B8B46AF754");
-
+ private static final byte[] KAT_KEY = Util.toBytesFromString(
+ "0000000000000000000000010000000000000000000000000000000000000000");
+ private static final byte[] KAT_CT = Util.toBytesFromString(
+ "E44429474D6FC3084EB2A6B8B46AF754");
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
- // Static code - to intialise lookup tables --------------------------------
-
static
{
long time = System.currentTimeMillis();
-
int ROOT = 0x11B;
int i, j = 0;
-
// S-box, inverse S-box, T-boxes, U-boxes
int s, s2, s3, i2, i4, i8, i9, ib, id, ie, t;
char c;
for (i = 0; i < 256; i++)
{
c = SS.charAt(i >>> 1);
- S[i] = (byte) (((i & 1) == 0) ? c >>> 8 : c & 0xFF);
+ S[i] = (byte)(((i & 1) == 0) ? c >>> 8 : c & 0xFF);
s = S[i] & 0xFF;
Si[s] = (byte) i;
s2 = s << 1;
if (s2 >= 0x100)
- {
- s2 ^= ROOT;
- }
+ s2 ^= ROOT;
s3 = s2 ^ s;
i2 = i << 1;
if (i2 >= 0x100)
- {
- i2 ^= ROOT;
- }
+ i2 ^= ROOT;
i4 = i2 << 1;
if (i4 >= 0x100)
- {
- i4 ^= ROOT;
- }
+ i4 ^= ROOT;
i8 = i4 << 1;
if (i8 >= 0x100)
- {
- i8 ^= ROOT;
- }
+ i8 ^= ROOT;
i9 = i8 ^ i;
ib = i9 ^ i2;
id = i9 ^ i4;
ie = i8 ^ i4 ^ i2;
-
T1[i] = t = (s2 << 24) | (s << 16) | (s << 8) | s3;
- T2[i] = (t >>> 8) | (t << 24);
+ T2[i] = (t >>> 8) | (t << 24);
T3[i] = (t >>> 16) | (t << 16);
- T4[i] = (t >>> 24) | (t << 8);
-
+ T4[i] = (t >>> 24) | (t << 8);
T5[s] = U1[i] = t = (ie << 24) | (i9 << 16) | (id << 8) | ib;
- T6[s] = U2[i] = (t >>> 8) | (t << 24);
+ T6[s] = U2[i] = (t >>> 8) | (t << 24);
T7[s] = U3[i] = (t >>> 16) | (t << 16);
- T8[s] = U4[i] = (t >>> 24) | (t << 8);
+ T8[s] = U4[i] = (t >>> 24) | (t << 8);
}
- //
// round constants
- //
int r = 1;
rcon[0] = 1;
for (i = 1; i < 30; i++)
{
r <<= 1;
if (r >= 0x100)
- {
- r ^= ROOT;
- }
+ r ^= ROOT;
rcon[i] = (byte) r;
}
-
time = System.currentTimeMillis() - time;
-
- if (DEBUG && debuglevel > 8)
+ if (Configuration.DEBUG)
{
- System.out.println("==========");
- System.out.println();
- System.out.println("Static Data");
- System.out.println();
- System.out.println("S[]:");
+ log.fine("Static Data");
+ log.fine("S[]:");
+ StringBuilder sb;
for (i = 0; i < 16; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 16; j++)
- {
- System.out.print("0x" + Util.toString(S[i * 16 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(S[i * 16 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("Si[]:");
+ log.fine("Si[]:");
for (i = 0; i < 16; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 16; j++)
- {
- System.out.print("0x" + Util.toString(Si[i * 16 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(Si[i * 16 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T1[]:");
+ log.fine("T1[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T1[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T1[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T2[]:");
+ log.fine("T2[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T2[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T2[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T3[]:");
+ log.fine("T3[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T3[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T3[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T4[]:");
+ log.fine("T4[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T4[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T4[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T5[]:");
+ log.fine("T5[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T5[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T5[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T6[]:");
+ log.fine("T6[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T6[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T6[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T7[]:");
+ log.fine("T7[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T7[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T7[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("T8[]:");
+ log.fine("T8[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(T8[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(T8[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("U1[]:");
+ log.fine("U1[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(U1[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(U1[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("U2[]:");
+ log.fine("U2[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(U2[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(U2[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("U3[]:");
+ log.fine("U3[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.print("0x" + Util.toString(U3[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(U3[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("U4[]:");
+ log.fine("U4[]:");
for (i = 0; i < 64; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 4; j++)
- {
- System.out.println("0x" + Util.toString(U4[i * 4 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(U4[i * 4 + j])).append(", ");
+ log.fine(sb.toString());
}
- System.out.println();
- System.out.println("rcon[]:");
+ log.fine("rcon[]:");
for (i = 0; i < 5; i++)
{
+ sb = new StringBuilder();
for (j = 0; j < 6; j++)
- {
- System.out.print("0x" + Util.toString(rcon[i * 6 + j]) + ", ");
- }
- System.out.println();
+ sb.append("0x").append(Util.toString(rcon[i * 6 + j])).append(", ");
+ log.fine(sb.toString());
}
-
- System.out.println();
- System.out.println("Total initialization time: " + time + " ms.");
- System.out.println();
+ log.fine("Total initialization time: " + time + " ms.");
}
}
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Rijndael()
{
super(Registry.RIJNDAEL_CIPHER, DEFAULT_BLOCK_SIZE, DEFAULT_KEY_SIZE);
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
- *
- * Vincent Rijmen and
- * Joan Daemen.
+ * Vincent Rijmen and
+ * Joan Daemen.
- *
*/
-public class Serpent extends BaseCipher
+public class Serpent
+ extends BaseCipher
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final int DEFAULT_KEY_SIZE = 16;
-
private static final int DEFAULT_BLOCK_SIZE = 16;
-
private static final int ROUNDS = 32;
-
/** The fractional part of the golden ratio, (sqrt(5)+1)/2. */
private static final int PHI = 0x9e3779b9;
-
/**
- * KAT vector (from ecb_vk):
- * I=9
+ * KAT vector (from ecb_vk): I=9
* KEY=008000000000000000000000000000000000000000000000
* CT=5587B5BCB9EE5A28BA2BACC418005240
*/
- private static final byte[] KAT_KEY = Util.toReversedBytesFromString("008000000000000000000000000000000000000000000000");
-
- private static final byte[] KAT_CT = Util.toReversedBytesFromString("5587B5BCB9EE5A28BA2BACC418005240");
-
+ private static final byte[] KAT_KEY = Util.toReversedBytesFromString(
+ "008000000000000000000000000000000000000000000000");
+ private static final byte[] KAT_CT =
+ Util.toReversedBytesFromString("5587B5BCB9EE5A28BA2BACC418005240");
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
-
private int x0, x1, x2, x3, x4;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial zero-argument constructor. */
public Serpent()
{
super(Registry.SERPENT_CIPHER, DEFAULT_BLOCK_SIZE, DEFAULT_KEY_SIZE);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.lang.Cloneable interface implementation ----------------------------
-
public Object clone()
{
Serpent result = new Serpent();
@@ -126,20 +105,17 @@ public class Serpent extends BaseCipher
return result;
}
- // IBlockCipherSpi interface implementation --------------------------------
-
public Iterator blockSizes()
{
- return Collections.singleton(new Integer(DEFAULT_BLOCK_SIZE)).iterator();
+ return Collections.singleton(Integer.valueOf(DEFAULT_BLOCK_SIZE)).iterator();
}
public Iterator keySizes()
{
ArrayList keySizes = new ArrayList();
- keySizes.add(new Integer(16));
- keySizes.add(new Integer(24));
- keySizes.add(new Integer(32));
-
+ keySizes.add(Integer.valueOf(16));
+ keySizes.add(Integer.valueOf(24));
+ keySizes.add(Integer.valueOf(32));
return Collections.unmodifiableList(keySizes).iterator();
}
@@ -148,24 +124,19 @@ public class Serpent extends BaseCipher
// Not strictly true, but here to conform with the AES proposal.
// This restriction can be removed if deemed necessary.
if (kb.length != 16 && kb.length != 24 && kb.length != 32)
- {
- throw new InvalidKeyException("Key length is not 16, 24, or 32 bytes");
- }
+ throw new InvalidKeyException("Key length is not 16, 24, or 32 bytes");
Key key = new Key();
-
// Here w is our "pre-key".
int[] w = new int[4 * (ROUNDS + 1)];
int i, j;
for (i = 0, j = 0; i < 8 && j < kb.length; i++)
- {
- w[i] = (kb[j++] & 0xff) | (kb[j++] & 0xff) << 8
- | (kb[j++] & 0xff) << 16 | (kb[j++] & 0xff) << 24;
- }
+ w[i] = (kb[j++] & 0xff)
+ | (kb[j++] & 0xff) << 8
+ | (kb[j++] & 0xff) << 16
+ | (kb[j++] & 0xff) << 24;
// Pad key if < 256 bits.
if (i != 8)
- {
- w[i] = 1;
- }
+ w[i] = 1;
// Transform using w_i-8 ... w_i-1
for (i = 8, j = 0; i < 16; i++)
{
@@ -174,16 +145,13 @@ public class Serpent extends BaseCipher
}
// Translate by 8.
for (i = 0; i < 8; i++)
- {
- w[i] = w[i + 8];
- }
+ w[i] = w[i + 8];
// Transform the rest of the key.
for (; i < w.length; i++)
{
int t = w[i - 8] ^ w[i - 5] ^ w[i - 3] ^ w[i - 1] ^ PHI ^ i;
w[i] = t << 11 | t >>> 21;
}
-
// After these s-boxes the pre-key (w, above) will become the
// session key (key, below).
sbox3(w[0], w[1], w[2], w[3]);
@@ -351,7 +319,6 @@ public class Serpent extends BaseCipher
key.k129 = x1;
key.k130 = x2;
key.k131 = x3;
-
return key;
}
@@ -359,16 +326,22 @@ public class Serpent extends BaseCipher
Object K, int bs)
{
Key key = (Key) K;
-
- x0 = (in[i] & 0xff) | (in[i + 1] & 0xff) << 8 | (in[i + 2] & 0xff) << 16
- | (in[i + 3] & 0xff) << 24;
- x1 = (in[i + 4] & 0xff) | (in[i + 5] & 0xff) << 8
- | (in[i + 6] & 0xff) << 16 | (in[i + 7] & 0xff) << 24;
- x2 = (in[i + 8] & 0xff) | (in[i + 9] & 0xff) << 8
- | (in[i + 10] & 0xff) << 16 | (in[i + 11] & 0xff) << 24;
- x3 = (in[i + 12] & 0xff) | (in[i + 13] & 0xff) << 8
- | (in[i + 14] & 0xff) << 16 | (in[i + 15] & 0xff) << 24;
-
+ x0 = (in[i ] & 0xff)
+ | (in[i + 1] & 0xff) << 8
+ | (in[i + 2] & 0xff) << 16
+ | (in[i + 3] & 0xff) << 24;
+ x1 = (in[i + 4] & 0xff)
+ | (in[i + 5] & 0xff) << 8
+ | (in[i + 6] & 0xff) << 16
+ | (in[i + 7] & 0xff) << 24;
+ x2 = (in[i + 8] & 0xff)
+ | (in[i + 9] & 0xff) << 8
+ | (in[i + 10] & 0xff) << 16
+ | (in[i + 11] & 0xff) << 24;
+ x3 = (in[i + 12] & 0xff)
+ | (in[i + 13] & 0xff) << 8
+ | (in[i + 14] & 0xff) << 16
+ | (in[i + 15] & 0xff) << 24;
x0 ^= key.k0;
x1 ^= key.k1;
x2 ^= key.k2;
@@ -412,7 +385,6 @@ public class Serpent extends BaseCipher
x0 = x3;
x3 = x2;
x2 = x4;
-
x0 ^= key.k32;
x1 ^= key.k33;
x2 ^= key.k34;
@@ -456,7 +428,6 @@ public class Serpent extends BaseCipher
x0 = x3;
x3 = x2;
x2 = x4;
-
x0 ^= key.k64;
x1 ^= key.k65;
x2 ^= key.k66;
@@ -500,7 +471,6 @@ public class Serpent extends BaseCipher
x0 = x3;
x3 = x2;
x2 = x4;
-
x0 ^= key.k96;
x1 ^= key.k97;
x2 ^= key.k98;
@@ -548,39 +518,44 @@ public class Serpent extends BaseCipher
x1 ^= key.k129;
x2 ^= key.k130;
x3 ^= key.k131;
-
- out[o] = (byte) x0;
- out[o + 1] = (byte) (x0 >>> 8);
- out[o + 2] = (byte) (x0 >>> 16);
- out[o + 3] = (byte) (x0 >>> 24);
- out[o + 4] = (byte) x1;
- out[o + 5] = (byte) (x1 >>> 8);
- out[o + 6] = (byte) (x1 >>> 16);
- out[o + 7] = (byte) (x1 >>> 24);
- out[o + 8] = (byte) x2;
- out[o + 9] = (byte) (x2 >>> 8);
- out[o + 10] = (byte) (x2 >>> 16);
- out[o + 11] = (byte) (x2 >>> 24);
+ out[o ] = (byte) x0;
+ out[o + 1] = (byte)(x0 >>> 8);
+ out[o + 2] = (byte)(x0 >>> 16);
+ out[o + 3] = (byte)(x0 >>> 24);
+ out[o + 4] = (byte) x1;
+ out[o + 5] = (byte)(x1 >>> 8);
+ out[o + 6] = (byte)(x1 >>> 16);
+ out[o + 7] = (byte)(x1 >>> 24);
+ out[o + 8] = (byte) x2;
+ out[o + 9] = (byte)(x2 >>> 8);
+ out[o + 10] = (byte)(x2 >>> 16);
+ out[o + 11] = (byte)(x2 >>> 24);
out[o + 12] = (byte) x3;
- out[o + 13] = (byte) (x3 >>> 8);
- out[o + 14] = (byte) (x3 >>> 16);
- out[o + 15] = (byte) (x3 >>> 24);
+ out[o + 13] = (byte)(x3 >>> 8);
+ out[o + 14] = (byte)(x3 >>> 16);
+ out[o + 15] = (byte)(x3 >>> 24);
}
public synchronized void decrypt(byte[] in, int i, byte[] out, int o,
Object K, int bs)
{
Key key = (Key) K;
-
- x0 = (in[i] & 0xff) | (in[i + 1] & 0xff) << 8 | (in[i + 2] & 0xff) << 16
- | (in[i + 3] & 0xff) << 24;
- x1 = (in[i + 4] & 0xff) | (in[i + 5] & 0xff) << 8
- | (in[i + 6] & 0xff) << 16 | (in[i + 7] & 0xff) << 24;
- x2 = (in[i + 8] & 0xff) | (in[i + 9] & 0xff) << 8
- | (in[i + 10] & 0xff) << 16 | (in[i + 11] & 0xff) << 24;
- x3 = (in[i + 12] & 0xff) | (in[i + 13] & 0xff) << 8
- | (in[i + 14] & 0xff) << 16 | (in[i + 15] & 0xff) << 24;
-
+ x0 = (in[i ] & 0xff)
+ | (in[i + 1] & 0xff) << 8
+ | (in[i + 2] & 0xff) << 16
+ | (in[i + 3] & 0xff) << 24;
+ x1 = (in[i + 4] & 0xff)
+ | (in[i + 5] & 0xff) << 8
+ | (in[i + 6] & 0xff) << 16
+ | (in[i + 7] & 0xff) << 24;
+ x2 = (in[i + 8] & 0xff)
+ | (in[i + 9] & 0xff) << 8
+ | (in[i + 10] & 0xff) << 16
+ | (in[i + 11] & 0xff) << 24;
+ x3 = (in[i + 12] & 0xff)
+ | (in[i + 13] & 0xff) << 8
+ | (in[i + 14] & 0xff) << 16
+ | (in[i + 15] & 0xff) << 24;
x0 ^= key.k128;
x1 ^= key.k129;
x2 ^= key.k130;
@@ -629,7 +604,6 @@ public class Serpent extends BaseCipher
x1 = x3;
x3 = x4;
x4 = x2;
-
x3 ^= key.k92;
x0 ^= key.k93;
x1 ^= key.k94;
@@ -673,7 +647,6 @@ public class Serpent extends BaseCipher
x1 = x3;
x3 = x4;
x4 = x2;
-
x3 ^= key.k60;
x0 ^= key.k61;
x1 ^= key.k62;
@@ -717,7 +690,6 @@ public class Serpent extends BaseCipher
x1 = x3;
x3 = x4;
x4 = x2;
-
x3 ^= key.k28;
x0 ^= key.k29;
x1 ^= key.k30;
@@ -756,28 +728,26 @@ public class Serpent extends BaseCipher
x2 = x1;
x1 = x3;
x3 = x4;
-
x0 ^= key.k0;
x1 ^= key.k1;
x2 ^= key.k2;
x3 ^= key.k3;
-
- out[o] = (byte) x0;
- out[o + 1] = (byte) (x0 >>> 8);
- out[o + 2] = (byte) (x0 >>> 16);
- out[o + 3] = (byte) (x0 >>> 24);
- out[o + 4] = (byte) x1;
- out[o + 5] = (byte) (x1 >>> 8);
- out[o + 6] = (byte) (x1 >>> 16);
- out[o + 7] = (byte) (x1 >>> 24);
- out[o + 8] = (byte) x2;
- out[o + 9] = (byte) (x2 >>> 8);
- out[o + 10] = (byte) (x2 >>> 16);
- out[o + 11] = (byte) (x2 >>> 24);
+ out[o ] = (byte) x0;
+ out[o + 1] = (byte)(x0 >>> 8);
+ out[o + 2] = (byte)(x0 >>> 16);
+ out[o + 3] = (byte)(x0 >>> 24);
+ out[o + 4] = (byte) x1;
+ out[o + 5] = (byte)(x1 >>> 8);
+ out[o + 6] = (byte)(x1 >>> 16);
+ out[o + 7] = (byte)(x1 >>> 24);
+ out[o + 8] = (byte) x2;
+ out[o + 9] = (byte)(x2 >>> 8);
+ out[o + 10] = (byte)(x2 >>> 16);
+ out[o + 11] = (byte)(x2 >>> 24);
out[o + 12] = (byte) x3;
- out[o + 13] = (byte) (x3 >>> 8);
- out[o + 14] = (byte) (x3 >>> 16);
- out[o + 15] = (byte) (x3 >>> 24);
+ out[o + 13] = (byte)(x3 >>> 8);
+ out[o + 14] = (byte)(x3 >>> 16);
+ out[o + 15] = (byte)(x3 >>> 24);
}
public boolean selfTest()
@@ -786,19 +756,14 @@ public class Serpent extends BaseCipher
{
boolean result = super.selfTest(); // do symmetry tests
if (result)
- {
- result = testKat(KAT_KEY, KAT_CT);
- }
+ result = testKat(KAT_KEY, KAT_CT);
valid = Boolean.valueOf(result);
}
return valid.booleanValue();
}
- // Own methods. ----------------------------------------------------------
-
// These first few S-boxes operate directly on the "registers",
// x0..x4, and perform the linear transform.
-
private void sbox0()
{
x3 ^= x0;
@@ -1492,8 +1457,6 @@ public class Serpent extends BaseCipher
x2 ^= x1;
}
- // These S-Box functions are used in the key setup.
-
/** S-Box 0. */
private void sbox0(int r0, int r1, int r2, int r3)
{
@@ -1654,15 +1617,9 @@ public class Serpent extends BaseCipher
x3 = r0;
}
- // Inner classes.
- // -----------------------------------------------------------------------
-
- private class Key implements Cloneable
+ private class Key
+ implements Cloneable
{
-
- // Constants and variables.
- // --------------------------------------------------------------------
-
int k0, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15,
k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29,
k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43,
@@ -1674,9 +1631,6 @@ public class Serpent extends BaseCipher
k112, k113, k114, k115, k116, k117, k118, k119, k120, k121, k122, k123,
k124, k125, k126, k127, k128, k129, k130, k131;
- // Constructors.
- // --------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
Key()
{
@@ -1819,12 +1773,9 @@ public class Serpent extends BaseCipher
this.k131 = that.k131;
}
- // Cloneable interface implementation.
- // --------------------------------------------------------------------
-
public Object clone()
{
return new Key(this);
}
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/cipher/Square.java b/libjava/classpath/gnu/javax/crypto/cipher/Square.java
index a73116e..af738da 100644
--- a/libjava/classpath/gnu/javax/crypto/cipher/Square.java
+++ b/libjava/classpath/gnu/javax/crypto/cipher/Square.java
@@ -47,145 +47,74 @@ import java.util.Collections;
import java.util.Iterator;
/**
- *
- *
*/
-public final class Square extends BaseCipher
+public final class Square
+ extends BaseCipher
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final int DEFAULT_BLOCK_SIZE = 16; // in bytes
-
private static final int DEFAULT_KEY_SIZE = 16; // in bytes
-
private static final int ROUNDS = 8;
-
private static final int ROOT = 0x1F5; // for generating GF(2**8)
-
private static final int[] OFFSET = new int[ROUNDS];
-
- private static final String Sdata = "\uB1CE\uC395\u5AAD\uE702\u4D44\uFB91\u0C87\uA150"
- + "\uCB67\u54DD\u468F\uE14E\uF0FD\uFCEB\uF9C4\u1A6E"
- + "\u5EF5\uCC8D\u1C56\u43FE\u0761\uF875\u59FF\u0322"
- + "\u8AD1\u13EE\u8800\u0E34\u1580\u94E3\uEDB5\u5323"
- + "\u4B47\u17A7\u9035\uABD8\uB8DF\u4F57\u9A92\uDB1B"
- + "\u3CC8\u9904\u8EE0\uD77D\u85BB\u402C\u3A45\uF142"
- + "\u6520\u4118\u7225\u9370\u3605\uF20B\uA379\uEC08"
- + "\u2731\u32B6\u7CB0\u0A73\u5B7B\uB781\uD20D\u6A26"
- + "\u9E58\u9C83\u74B3\uAC30\u7A69\u770F\uAE21\uDED0"
- + "\u2E97\u10A4\u98A8\uD468\u2D62\u296D\u1649\u76C7"
- + "\uE8C1\u9637\uE5CA\uF4E9\u6312\uC2A6\u14BC\uD328"
- + "\uAF2F\uE624\u52C6\uA009\uBD8C\uCF5D\u115F\u01C5"
- + "\u9F3D\uA29B\uC93B\uBE51\u191F\u3F5C\uB2EF\u4ACD"
- + "\uBFBA\u6F64\uD9F3\u3EB4\uAADC\uD506\uC07E\uF666"
- + "\u6C84\u7138\uB91D\u7F9D\u488B\u2ADA\uA533\u8239"
- + "\uD678\u86FA\uE42B\uA91E\u8960\u6BEA\u554C\uF7E2";
-
+ private static final String Sdata =
+ "\uB1CE\uC395\u5AAD\uE702\u4D44\uFB91\u0C87\uA150"
+ + "\uCB67\u54DD\u468F\uE14E\uF0FD\uFCEB\uF9C4\u1A6E"
+ + "\u5EF5\uCC8D\u1C56\u43FE\u0761\uF875\u59FF\u0322"
+ + "\u8AD1\u13EE\u8800\u0E34\u1580\u94E3\uEDB5\u5323"
+ + "\u4B47\u17A7\u9035\uABD8\uB8DF\u4F57\u9A92\uDB1B"
+ + "\u3CC8\u9904\u8EE0\uD77D\u85BB\u402C\u3A45\uF142"
+ + "\u6520\u4118\u7225\u9370\u3605\uF20B\uA379\uEC08"
+ + "\u2731\u32B6\u7CB0\u0A73\u5B7B\uB781\uD20D\u6A26"
+ + "\u9E58\u9C83\u74B3\uAC30\u7A69\u770F\uAE21\uDED0"
+ + "\u2E97\u10A4\u98A8\uD468\u2D62\u296D\u1649\u76C7"
+ + "\uE8C1\u9637\uE5CA\uF4E9\u6312\uC2A6\u14BC\uD328"
+ + "\uAF2F\uE624\u52C6\uA009\uBD8C\uCF5D\u115F\u01C5"
+ + "\u9F3D\uA29B\uC93B\uBE51\u191F\u3F5C\uB2EF\u4ACD"
+ + "\uBFBA\u6F64\uD9F3\u3EB4\uAADC\uD506\uC07E\uF666"
+ + "\u6C84\u7138\uB91D\u7F9D\u488B\u2ADA\uA533\u8239"
+ + "\uD678\u86FA\uE42B\uA91E\u8960\u6BEA\u554C\uF7E2";
/** Substitution boxes for encryption and decryption. */
private static final byte[] Se = new byte[256];
-
private static final byte[] Sd = new byte[256];
-
/** Transposition boxes for encryption and decryption. */
private static final int[] Te = new int[256];
-
private static final int[] Td = new int[256];
-
/**
- * KAT vector (from ecb_vk):
- * I=87
- * KEY=00000000000000000000020000000000
+ * KAT vector (from ecb_vk): I=87 KEY=00000000000000000000020000000000
* CT=A9DF031B4E25E89F527EFFF89CB0BEBA
*/
- private static final byte[] KAT_KEY = Util.toBytesFromString("00000000000000000000020000000000");
-
- private static final byte[] KAT_CT = Util.toBytesFromString("A9DF031B4E25E89F527EFFF89CB0BEBA");
-
+ private static final byte[] KAT_KEY =
+ Util.toBytesFromString("00000000000000000000020000000000");
+ private static final byte[] KAT_CT =
+ Util.toBytesFromString("A9DF031B4E25E89F527EFFF89CB0BEBA");
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
-
- // Static code - to intialise lookup tables
- // -------------------------------------------------------------------------
-
static
{
int i, j;
- /*
- // Generate exp and log tables used in multiplication over GF(2 ** m)
- byte[] exp = new byte[256];
- byte[] log = new byte[256];
-
- exp[0] = 1;
- for (i = 1; i < 256; i++) {
- j = exp[i - 1] << 1;
- if ((j & 0x100) != 0) {
- j ^= ROOT; // reduce j (mod ROOT)
- }
-
- exp[i] = (byte) j;
- log[j & 0xFF] = (byte) i;
- }
-
- // Compute the substitution box Se[] and its inverse Sd[] based on
- // F(x) = x**{-1} plus affine transform of the output.
- Se[0] = 0;
- Se[1] = 1;
- for (i = 2; i < 256; i++) {
- Se[i] = exp[(255 - log[i]) & 0xFF];
- }
-
- // Let Se[i] be represented as an 8-row vector V over GF(2); the affine
- // transformation is A * V + T, where the rows of the 8 x 8 matrix A are
- // contained in trans[0]...trans[7] and the 8-row vector T is contained
- // in 0xB1.
- int[] trans = new int[] {0x01, 0x03, 0x05, 0x0F, 0x1F, 0x3D, 0x7B, 0xD6};
- int u, v;
- for (i = 0; i < 256; i++) {
- v = 0xB1; // affine part of the transform
- for (j = 0; j < 8; j++) {
- u = Se[i] & trans[j] & 0xFF; // column-wise mult. over GF(2)
- u ^= u >>> 4; // sum of all bits of u over GF(2)
- u ^= u >>> 2;
- u ^= u >>> 1;
- u &= 1;
- v ^= u << j; // row alignment of the result
- }
- Se[i] = (byte) v;
- Sd[v] = (byte) i; // inverse substitution box
- }
-
- System.out.println("Se="+Util.toUnicodeString(Se));
- System.out.println("Sd="+Util.toUnicodeString(Sd));
- */
- /**/
// re-construct Se box values
int limit = Sdata.length();
char c1;
for (i = 0, j = 0; i < limit; i++)
{
c1 = Sdata.charAt(i);
- Se[j++] = (byte) (c1 >>> 8);
+ Se[j++] = (byte)(c1 >>> 8);
Se[j++] = (byte) c1;
}
-
// compute Sd box values
for (i = 0; i < 256; i++)
- {
- Sd[Se[i] & 0xFF] = (byte) i;
- }
-
+ Sd[Se[i] & 0xFF] = (byte) i;
// generate OFFSET values
OFFSET[0] = 1;
for (i = 1; i < ROUNDS; i++)
@@ -193,9 +122,7 @@ public final class Square extends BaseCipher
OFFSET[i] = mul(OFFSET[i - 1], 2);
OFFSET[i - 1] <<= 24;
}
-
OFFSET[ROUNDS - 1] <<= 24;
-
// generate Te and Td boxes if we're not reading their values
// Notes:
// (1) The function mul() computes the product of two elements of GF(2**8)
@@ -207,111 +134,122 @@ public final class Square extends BaseCipher
for (i = 0; i < 256; i++)
{
j = Se[i] & 0xFF;
- Te[i] = (Se[i & 3] == 0) ? 0 : mul(j, 2) << 24 | j << 16 | j << 8
- | mul(j, 3);
-
+ Te[i] = (Se[i & 3] == 0) ? 0
+ : mul(j, 2) << 24
+ | j << 16
+ | j << 8
+ | mul(j, 3);
j = Sd[i] & 0xFF;
- Td[i] = (Sd[i & 3] == 0) ? 0 : mul(j, 14) << 24 | mul(j, 9) << 16
- | mul(j, 13) << 8 | mul(j, 11);
+ Td[i] = (Sd[i & 3] == 0) ? 0
+ : mul(j, 14) << 24
+ | mul(j, 9) << 16
+ | mul(j, 13) << 8
+ | mul(j, 11);
}
- /**/
}
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public Square()
{
super(Registry.SQUARE_CIPHER, DEFAULT_BLOCK_SIZE, DEFAULT_KEY_SIZE);
}
- // Class methods
- // -------------------------------------------------------------------------
-
private static void square(byte[] in, int i, byte[] out, int j, int[][] K,
int[] T, byte[] S)
{
- int a = ((in[i++]) << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i++] & 0xFF))
- ^ K[0][0];
- int b = ((in[i++]) << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i++] & 0xFF))
- ^ K[0][1];
- int c = ((in[i++]) << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i++] & 0xFF))
- ^ K[0][2];
- int d = ((in[i++]) << 24 | (in[i++] & 0xFF) << 16 | (in[i++] & 0xFF) << 8 | (in[i] & 0xFF))
- ^ K[0][3];
-
+ int a = ((in[i++]) << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i++] & 0xFF) ) ^ K[0][0];
+ int b = ((in[i++]) << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i++] & 0xFF) ) ^ K[0][1];
+ int c = ((in[i++]) << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i++] & 0xFF) ) ^ K[0][2];
+ int d = ((in[i++]) << 24
+ | (in[i++] & 0xFF) << 16
+ | (in[i++] & 0xFF) << 8
+ | (in[i ] & 0xFF) ) ^ K[0][3];
int r, aa, bb, cc, dd;
for (r = 1; r < ROUNDS; r++)
{ // R - 1 full rounds
- aa = T[(a >>> 24)] ^ rot32R(T[(b >>> 24)], 8)
- ^ rot32R(T[(c >>> 24)], 16) ^ rot32R(T[(d >>> 24)], 24) ^ K[r][0];
- bb = T[(a >>> 16) & 0xFF] ^ rot32R(T[(b >>> 16) & 0xFF], 8)
- ^ rot32R(T[(c >>> 16) & 0xFF], 16)
- ^ rot32R(T[(d >>> 16) & 0xFF], 24) ^ K[r][1];
- cc = T[(a >>> 8) & 0xFF] ^ rot32R(T[(b >>> 8) & 0xFF], 8)
- ^ rot32R(T[(c >>> 8) & 0xFF], 16)
- ^ rot32R(T[(d >>> 8) & 0xFF], 24) ^ K[r][2];
- dd = T[a & 0xFF] ^ rot32R(T[b & 0xFF], 8) ^ rot32R(T[c & 0xFF], 16)
- ^ rot32R(T[d & 0xFF], 24) ^ K[r][3];
-
+ aa = T[(a >>> 24) ]
+ ^ rot32R(T[(b >>> 24) ], 8)
+ ^ rot32R(T[(c >>> 24) ], 16)
+ ^ rot32R(T[(d >>> 24) ], 24) ^ K[r][0];
+ bb = T[(a >>> 16) & 0xFF]
+ ^ rot32R(T[(b >>> 16) & 0xFF], 8)
+ ^ rot32R(T[(c >>> 16) & 0xFF], 16)
+ ^ rot32R(T[(d >>> 16) & 0xFF], 24) ^ K[r][1];
+ cc = T[(a >>> 8) & 0xFF]
+ ^ rot32R(T[(b >>> 8) & 0xFF], 8)
+ ^ rot32R(T[(c >>> 8) & 0xFF], 16)
+ ^ rot32R(T[(d >>> 8) & 0xFF], 24) ^ K[r][2];
+ dd = T[ a & 0xFF]
+ ^ rot32R(T[ b & 0xFF], 8)
+ ^ rot32R(T[ c & 0xFF], 16)
+ ^ rot32R(T[ d & 0xFF], 24) ^ K[r][3];
a = aa;
b = bb;
c = cc;
d = dd;
}
-
// last round (diffusion becomes only transposition)
- aa = ((S[(a >>> 24)]) << 24 | (S[(b >>> 24)] & 0xFF) << 16
- | (S[(c >>> 24)] & 0xFF) << 8 | (S[(d >>> 24)] & 0xFF))
- ^ K[r][0];
- bb = ((S[(a >>> 16) & 0xFF]) << 24 | (S[(b >>> 16) & 0xFF] & 0xFF) << 16
- | (S[(c >>> 16) & 0xFF] & 0xFF) << 8 | (S[(d >>> 16) & 0xFF] & 0xFF))
- ^ K[r][1];
- cc = ((S[(a >>> 8) & 0xFF]) << 24 | (S[(b >>> 8) & 0xFF] & 0xFF) << 16
- | (S[(c >>> 8) & 0xFF] & 0xFF) << 8 | (S[(d >>> 8) & 0xFF] & 0xFF))
- ^ K[r][2];
- dd = ((S[a & 0xFF]) << 24 | (S[b & 0xFF] & 0xFF) << 16
- | (S[c & 0xFF] & 0xFF) << 8 | (S[d & 0xFF] & 0xFF))
- ^ K[r][3];
-
- out[j++] = (byte) (aa >>> 24);
- out[j++] = (byte) (aa >>> 16);
- out[j++] = (byte) (aa >>> 8);
+ aa = ((S[(a >>> 24) ] ) << 24
+ | (S[(b >>> 24) ] & 0xFF) << 16
+ | (S[(c >>> 24) ] & 0xFF) << 8
+ | (S[(d >>> 24) ] & 0xFF) ) ^ K[r][0];
+ bb = ((S[(a >>> 16) & 0xFF] ) << 24
+ | (S[(b >>> 16) & 0xFF] & 0xFF) << 16
+ | (S[(c >>> 16) & 0xFF] & 0xFF) << 8
+ | (S[(d >>> 16) & 0xFF] & 0xFF) ) ^ K[r][1];
+ cc = ((S[(a >>> 8) & 0xFF] ) << 24
+ | (S[(b >>> 8) & 0xFF] & 0xFF) << 16
+ | (S[(c >>> 8) & 0xFF] & 0xFF) << 8
+ | (S[(d >>> 8) & 0xFF] & 0xFF) ) ^ K[r][2];
+ dd = ((S[ a & 0xFF] ) << 24
+ | (S[ b & 0xFF] & 0xFF) << 16
+ | (S[ c & 0xFF] & 0xFF) << 8
+ | (S[ d & 0xFF] & 0xFF) ) ^ K[r][3];
+ out[j++] = (byte)(aa >>> 24);
+ out[j++] = (byte)(aa >>> 16);
+ out[j++] = (byte)(aa >>> 8);
out[j++] = (byte) aa;
- out[j++] = (byte) (bb >>> 24);
- out[j++] = (byte) (bb >>> 16);
- out[j++] = (byte) (bb >>> 8);
+ out[j++] = (byte)(bb >>> 24);
+ out[j++] = (byte)(bb >>> 16);
+ out[j++] = (byte)(bb >>> 8);
out[j++] = (byte) bb;
- out[j++] = (byte) (cc >>> 24);
- out[j++] = (byte) (cc >>> 16);
- out[j++] = (byte) (cc >>> 8);
+ out[j++] = (byte)(cc >>> 24);
+ out[j++] = (byte)(cc >>> 16);
+ out[j++] = (byte)(cc >>> 8);
out[j++] = (byte) cc;
- out[j++] = (byte) (dd >>> 24);
- out[j++] = (byte) (dd >>> 16);
- out[j++] = (byte) (dd >>> 8);
- out[j] = (byte) dd;
+ out[j++] = (byte)(dd >>> 24);
+ out[j++] = (byte)(dd >>> 16);
+ out[j++] = (byte)(dd >>> 8);
+ out[j ] = (byte) dd;
}
/**
- *
- * Joan Daemen,
- * Lars Knudsen and
- * Vincent Rijmen.
+ * Joan Daemen, Lars Knudsen and Vincent Rijmen.
- * for (i = 0; i < 4; i++) {
- * out[i] = 0;
- * for (j = 0, n = 24; j < 4; j++, n -= 8) {
- * k = mul(in[i] >>> 24, G[0][j]) ^
- * mul(in[i] >>> 16, G[1][j]) ^
- * mul(in[i] >>> 8, G[2][j]) ^
- * mul(in[i] , G[3][j]);
- * out[i] ^= k << n;
+ * for (i = 0; i < 4; i++)
+ * {
+ * out[i] = 0;
+ * for (j = 0, n = 24; j < 4; j++, n -= 8)
+ * {
+ * k = mul(in[i] >>> 24, G[0][j]) ˆ mul(in[i] >>> 16, G[1][j])
+ * ˆ mul(in[i] >>> 8, G[2][j]) ˆ mul(in[i], G[3][j]);
+ * out[i] ˆ= k << n;
* }
- * }
+ * }
*
*/
private static void transform(int[] in, int[] out)
@@ -332,8 +270,8 @@ public final class Square extends BaseCipher
}
/**
- * Ci =
- * Ek3 ( Ek2-1 ( Ek1 ( Pi )))
- *
- * Pi =
- * Ek1-1 ( Ek2 ( Ek3-1 ( Ci )))
- *
- * Ci = Ek3 ( Ek2-1 (
+ * Ek1 ( Pi )))
+ *
+ * Pi = Ek1-1 (
+ * Ek2 ( Ek3-1 ( Ci )))
+ *
+ *
- *
*/
-public class TripleDES extends BaseCipher
+public class TripleDES
+ extends BaseCipher
{
-
- // Constants and variables.
- // -----------------------------------------------------------------------
-
/** Triple-DES only operates on 64 bit blocks. */
public static final int BLOCK_SIZE = 8;
-
- /** Triple-DES uses 168 bits of a parity-adjusted 192 bit key. */
+ /** By default, Triple-DES uses 168 bits of a parity-adjusted 192 bit key. */
public static final int KEY_SIZE = 24;
-
/** The underlying DES instance. */
private DES des;
- // Constructors.
- // -----------------------------------------------------------------------
-
/**
* Default 0-arguments constructor.
*/
@@ -97,27 +93,48 @@ public class TripleDES extends BaseCipher
des = new DES();
}
- // Class methods.
- // -----------------------------------------------------------------------
-
/**
- * Transform a key so it will be parity adjusted.
- *
- * @param kb The key bytes to adjust.
+ * Convenience method which calls the method with same name and three
+ * arguments, passing 3
as the value of the first parameter.
+ *
+ * @param kb The key bytes to adjust.
* @param offset The starting offset into the key bytes.
- * @see DES#adjustParity(byte[],int)
*/
public static void adjustParity(byte[] kb, int offset)
{
+ adjustParity(3, kb, offset);
+ }
+
+ /**
+ * Adjusts, in-situ, the parity of the designated bytes, so they can be used
+ * as DES keys for a 3-DES 1-, 2- or 3-key cipher.
+ *
+ * @param keyCount the number of independent DES keys. Can be either
+ * 1
, 2
or 3
. Any other value
+ * will cause an {@link IllegalArgumentException} to be raised.
+ * @param kb the array containing the key bytes to adjust. MUST have at least
+ * 8 * keyCount
bytes starting at offset position
+ * offset
, otherwise an
+ * {@link ArrayIndexOutOfBoundsException} will be raised.
+ * @param offset the starting offset into the array.
+ * @see DES#adjustParity(byte[],int)
+ */
+ public static void adjustParity(int keyCount, byte[] kb, int offset)
+ {
+ if (keyCount < 1 || keyCount > 3)
+ throw new IllegalArgumentException("Invalid keyCount value: " + keyCount);
DES.adjustParity(kb, offset);
- DES.adjustParity(kb, offset + 8);
- DES.adjustParity(kb, offset + 16);
+ if (keyCount > 1)
+ DES.adjustParity(kb, offset + 8);
+ if (keyCount > 2)
+ DES.adjustParity(kb, offset + 16);
}
/**
- * Tests if a byte array has already been parity adjusted.
- *
- * @param kb The key bytes to test.
+ * Convenience method which calls the method with same name and three
+ * arguments, passing 3
as the value of the first parameter.
+ *
+ * @param kb The key bytes to test.
* @param offset The starting offset into the key bytes.
* @return true
if the bytes in kb starting at
* offset are parity adjusted.
@@ -126,13 +143,38 @@ public class TripleDES extends BaseCipher
*/
public static boolean isParityAdjusted(byte[] kb, int offset)
{
- return DES.isParityAdjusted(kb, offset)
- && DES.isParityAdjusted(kb, offset + 8)
- && DES.isParityAdjusted(kb, offset + 16);
+ return isParityAdjusted(3, kb, offset);
}
- // Methods implementing BaseCipher.
- // -----------------------------------------------------------------------
+ /**
+ * Tests if enough bytes, expected to be used as DES keys for a 3-DES 1-, 2-
+ * or 3-key cipher, located in a designated byte array, has already been
+ * parity adjusted.
+ *
+ * @param keyCount the number of independent DES keys. Can be either
+ * 1
, 2
or 3
. Any other value
+ * will cause an {@link IllegalArgumentException} to be raised.
+ * @param kb the array containing the key bytes to test. MUST have at least
+ * 8 * keyCount
bytes starting at offset position
+ * offset
, otherwise an
+ * {@link ArrayIndexOutOfBoundsException} will be raised.
+ * @param offset the starting offset into the array.
+ * @return true
if the bytes in kb starting at
+ * offset are parity adjusted.
+ * @see DES#isParityAdjusted(byte[],int)
+ * @see #adjustParity(int,byte[],int)
+ */
+ public static boolean isParityAdjusted(int keyCount, byte[] kb, int offset)
+ {
+ if (keyCount < 1 || keyCount > 3)
+ throw new IllegalArgumentException("Invalid keyCount value: " + keyCount);
+ boolean result = DES.isParityAdjusted(kb, offset);
+ if (keyCount > 1)
+ result = result && DES.isParityAdjusted(kb, offset + 8);
+ if (keyCount > 2)
+ result = result && DES.isParityAdjusted(kb, offset + 16);
+ return result;
+ }
public Object clone()
{
@@ -141,32 +183,54 @@ public class TripleDES extends BaseCipher
public Iterator blockSizes()
{
- return Collections.singleton(new Integer(BLOCK_SIZE)).iterator();
+ return Collections.singleton(Integer.valueOf(BLOCK_SIZE)).iterator();
}
public Iterator keySizes()
{
- return Collections.singleton(new Integer(KEY_SIZE)).iterator();
+ ArrayList al = new ArrayList();
+ al.add(Integer.valueOf(8));
+ al.add(Integer.valueOf(16));
+ al.add(Integer.valueOf(24));
+ return Collections.unmodifiableList(al).iterator();
}
public Object makeKey(byte[] kb, int bs) throws InvalidKeyException
{
- if (kb.length != KEY_SIZE)
- throw new InvalidKeyException("TripleDES key must be 24 bytes");
-
- if (!isParityAdjusted(kb, 0))
- adjustParity(kb, 0);
-
- byte[] k1 = new byte[DES.KEY_SIZE], k2 = new byte[DES.KEY_SIZE], k3 = new byte[DES.KEY_SIZE];
- System.arraycopy(kb, 0, k1, 0, DES.KEY_SIZE);
- System.arraycopy(kb, DES.KEY_SIZE, k2, 0, DES.KEY_SIZE);
- System.arraycopy(kb, 2 * DES.KEY_SIZE, k3, 0, DES.KEY_SIZE);
+ if (kb.length != 8 && kb.length != 16 && kb.length != 24)
+ throw new InvalidKeyException("TripleDES key must be 8, 16 or 24 bytes: "
+ + kb.length);
Context ctx = new Context();
-
+ byte[] k1 = new byte[DES.KEY_SIZE];
+ System.arraycopy(kb, 0, k1, 0, DES.KEY_SIZE);
+ if (! DES.isParityAdjusted(k1, 0))
+ DES.adjustParity(k1, 0);
ctx.k1 = (DES.Context) des.makeKey(k1, bs);
- ctx.k2 = (DES.Context) des.makeKey(k2, bs);
- ctx.k3 = (DES.Context) des.makeKey(k3, bs);
+ if (kb.length == 8)
+ {
+ ctx.k2 = (DES.Context) des.makeKey(k1, bs);
+ ctx.k3 = (DES.Context) des.makeKey(k1, bs);
+ }
+ else
+ {
+ byte[] k2 = new byte[DES.KEY_SIZE];
+ System.arraycopy(kb, DES.KEY_SIZE, k2, 0, DES.KEY_SIZE);
+ if (! DES.isParityAdjusted(k2, 0))
+ DES.adjustParity(k2, 0);
+ ctx.k2 = (DES.Context) des.makeKey(k2, bs);
+
+ byte[] k3 = new byte[DES.KEY_SIZE];
+ if (kb.length == 16)
+ ctx.k3 = (DES.Context) des.makeKey(k1, bs);
+ else
+ {
+ System.arraycopy(kb, 2 * DES.KEY_SIZE, k3, 0, DES.KEY_SIZE);
+ if (! DES.isParityAdjusted(k3, 0))
+ DES.adjustParity(k3, 0);
+ ctx.k3 = (DES.Context) des.makeKey(k3, bs);
+ }
+ }
return ctx;
}
@@ -186,11 +250,8 @@ public class TripleDES extends BaseCipher
des.decrypt(temp, 0, out, o, ((Context) K).k1, bs);
}
- // Inner classes.
- // -----------------------------------------------------------------------
-
private final class Context
{
DES.Context k1, k2, k3;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/cipher/Twofish.java b/libjava/classpath/gnu/javax/crypto/cipher/Twofish.java
index f5565d4..b693244 100644
--- a/libjava/classpath/gnu/javax/crypto/cipher/Twofish.java
+++ b/libjava/classpath/gnu/javax/crypto/cipher/Twofish.java
@@ -38,204 +38,142 @@ exception statement from your version. */
package gnu.javax.crypto.cipher;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
-//import java.io.PrintWriter;
import java.security.InvalidKeyException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
+import java.util.logging.Logger;
/**
- * n + 1
8-byte blocks where
+ * n
is the smallest number of 8-byte blocks that contain the
+ * designated number of input bytes.
+ */
+ protected int getOutputSizeForWrap(int inputLength)
+ {
+ int n = (inputLength + 7) / 8;
+ return 8 * (n + 1);
+ }
+
+ /**
+ * AES Key Wrapping algorithms operate on an 8-byte block; a block half the
+ * size of the AES block itself.
+ * n - 1
8-byte blocks where
+ * n
is the smallest number of 8-byte blocks that contain the
+ * designated number of input bytes.
+ */
+ protected int getOutputSizeForUnwrap(int inputLength)
+ {
+ int n = (inputLength + 7) / 8;
+ return 8 * (n - 1);
+ }
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/AESSpi.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/AESSpi.java
index 33de689..1322e5e 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/AESSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/AESSpi.java
@@ -50,23 +50,17 @@ import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
/**
- * The implementation of the AES Service Provider Interface
- * (SPI) adapter.
+ * The implementation of the AES Service Provider Interface (SPI)
+ * adapter.
*/
-public final class AESSpi extends CipherAdapter
+public final class AESSpi
+ extends CipherAdapter
{
-
- // Constructors.
- // -----------------------------------------------------------------------
-
public AESSpi()
{
super(Registry.AES_CIPHER, 16);
}
- // Methods from CipherAdapter
- // -----------------------------------------------------------------------
-
protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
SecureRandom random) throws InvalidKeyException,
InvalidAlgorithmParameterException
@@ -74,10 +68,8 @@ public final class AESSpi extends CipherAdapter
if (params instanceof BlockCipherParameterSpec)
{
if (((BlockCipherParameterSpec) params).getBlockSize() != 16)
- {
- throw new InvalidAlgorithmParameterException(
- "AES block size must be 16 bytes");
- }
+ throw new InvalidAlgorithmParameterException(
+ "AES block size must be 16 bytes");
}
super.engineInit(opmode, key, params, random);
}
@@ -90,9 +82,7 @@ public final class AESSpi extends CipherAdapter
try
{
if (params != null)
- {
- spec = params.getParameterSpec(BlockCipherParameterSpec.class);
- }
+ spec = params.getParameterSpec(BlockCipherParameterSpec.class);
}
catch (InvalidParameterSpecException ipse)
{
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/ARCFourSpi.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/ARCFourSpi.java
index 963fa1c..abcb486 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/ARCFourSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/ARCFourSpi.java
@@ -62,29 +62,20 @@ import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
/**
- * The Service Provider Interface (SPI) for the ARCFOUR
- * stream cipher.
+ * The Service Provider Interface (SPI) for the ARCFOUR stream
+ * cipher.
*/
-public class ARCFourSpi extends CipherSpi
+public class ARCFourSpi
+ extends CipherSpi
{
-
- // Constants and variables.
- // -----------------------------------------------------------------------
-
private IRandom keystream;
- // Constructors.
- // -----------------------------------------------------------------------
-
public ARCFourSpi()
{
super();
keystream = PRNGFactory.getInstance(Registry.ARCFOUR_PRNG);
}
- // Methods implementing CipherSpi.
- // -----------------------------------------------------------------------
-
protected int engineGetBlockSize()
{
return 0; // stream cipher.
@@ -119,14 +110,10 @@ public class ARCFourSpi extends CipherSpi
throws InvalidKeyException
{
if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE)
- {
- throw new IllegalArgumentException(
- "arcfour is for encryption or decryption only");
- }
- if (key == null || !key.getFormat().equalsIgnoreCase("RAW"))
- {
- throw new InvalidKeyException("key must be non-null raw bytes");
- }
+ throw new IllegalArgumentException(
+ "arcfour is for encryption or decryption only");
+ if (key == null || ! key.getFormat().equalsIgnoreCase("RAW"))
+ throw new InvalidKeyException("key must be non-null raw bytes");
HashMap attrib = new HashMap();
attrib.put(ARCFour.ARCFOUR_KEY_MATERIAL, key.getEncoded());
keystream.init(attrib);
@@ -149,16 +136,12 @@ public class ARCFourSpi extends CipherSpi
protected byte[] engineUpdate(byte[] in, int offset, int length)
{
if (length < 0 || offset < 0 || length + offset > in.length)
- {
- throw new ArrayIndexOutOfBoundsException();
- }
+ throw new ArrayIndexOutOfBoundsException();
byte[] result = new byte[length];
try
{
for (int i = 0; i < length; i++)
- {
- result[i] = (byte) (in[i + offset] ^ keystream.nextByte());
- }
+ result[i] = (byte)(in[i + offset] ^ keystream.nextByte());
}
catch (LimitReachedException wontHappen)
{
@@ -171,19 +154,13 @@ public class ARCFourSpi extends CipherSpi
{
if (length < 0 || inOffset < 0 || length + inOffset > in.length
|| outOffset < 0)
- {
- throw new ArrayIndexOutOfBoundsException();
- }
+ throw new ArrayIndexOutOfBoundsException();
if (outOffset + length > out.length)
- {
- throw new ShortBufferException();
- }
+ throw new ShortBufferException();
try
{
for (int i = 0; i < length; i++)
- {
- out[i + outOffset] = (byte) (in[i + inOffset] ^ keystream.nextByte());
- }
+ out[i + outOffset] = (byte)(in[i + inOffset] ^ keystream.nextByte());
}
catch (LimitReachedException wontHappen)
{
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/AnubisSpi.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/AnubisSpi.java
index 0fca3b4..e35e4e7 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/AnubisSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/AnubisSpi.java
@@ -44,12 +44,9 @@ import gnu.java.security.Registry;
* The implementation of the Anubis Service Provider Interface
* (SPI) adapter.
*/
-public final class AnubisSpi extends CipherAdapter
+public final class AnubisSpi
+ extends CipherAdapter
{
-
- // Constructors.
- // --------------------------------------------------------------------
-
public AnubisSpi()
{
super(Registry.ANUBIS_CIPHER);
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/BlowfishSpi.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/BlowfishSpi.java
index d31d7e1..fec200c 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/BlowfishSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/BlowfishSpi.java
@@ -44,12 +44,9 @@ import gnu.java.security.Registry;
* The implementation of the Blowfish Service Provider Interface
* (SPI) adapter.
*/
-public final class BlowfishSpi extends CipherAdapter
+public final class BlowfishSpi
+ extends CipherAdapter
{
-
- // Constructors.
- // --------------------------------------------------------------------
-
public BlowfishSpi()
{
super(Registry.BLOWFISH_CIPHER);
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/Cast5Spi.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/Cast5Spi.java
index b1d4cf70..bf08034 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/Cast5Spi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/Cast5Spi.java
@@ -43,26 +43,12 @@ import gnu.java.security.Registry;
/**
* The implementation of the CAST5
(a.k.a. CAST-128) Service
* Provider Interface (SPI) Adapter.
- *
- * @version Revision: $
*/
-public class Cast5Spi extends CipherAdapter
+public class Cast5Spi
+ extends CipherAdapter
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public Cast5Spi()
{
super(Registry.CAST5_CIPHER);
}
-
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/CipherAdapter.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/CipherAdapter.java
index 5eaa31b..b7cd755 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/CipherAdapter.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/CipherAdapter.java
@@ -38,8 +38,9 @@ exception statement from your version. */
package gnu.javax.crypto.jce.cipher;
-import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.java.security.Registry;
import gnu.javax.crypto.cipher.CipherFactory;
+import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.jce.spec.BlockCipherParameterSpec;
import gnu.javax.crypto.mode.IMode;
import gnu.javax.crypto.mode.ModeFactory;
@@ -56,6 +57,7 @@ import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidParameterSpecException;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.Map;
import javax.crypto.BadPaddingException;
@@ -67,61 +69,48 @@ import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
/**
- * key
is invalid or the cipher
+ * needs extra parameters which can not be derived from
+ * key
; e.g. an IV.
+ */
+ private void engineInitHandler(int opmode, Key key, SecureRandom random)
+ throws InvalidKeyException
+ {
switch (opmode)
{
case Cipher.ENCRYPT_MODE:
- attributes.put(IMode.STATE, new Integer(IMode.ENCRYPTION));
+ attributes.put(IMode.STATE, Integer.valueOf(IMode.ENCRYPTION));
break;
case Cipher.DECRYPT_MODE:
- attributes.put(IMode.STATE, new Integer(IMode.DECRYPTION));
+ attributes.put(IMode.STATE, Integer.valueOf(IMode.DECRYPTION));
break;
}
- if (!key.getFormat().equalsIgnoreCase("RAW"))
- {
- throw new InvalidKeyException("bad key format " + key.getFormat());
- }
+ if (! key.getFormat().equalsIgnoreCase("RAW"))
+ throw new InvalidKeyException("bad key format " + key.getFormat());
byte[] kb = key.getEncoded();
+ int kbLength = kb.length;
if (keyLen == 0)
{
- keyLen = kb.length;
+ // no key-size given; instead key-material is provided in kb --which
+ // can be more than what we need. if we don't cull this down to what
+ // the cipher likes/wants we may get an InvalidKeyException.
+ //
+ // try to find the largest key-size value that is less than or equal
+ // to kbLength
+ for (Iterator it = cipher.keySizes(); it.hasNext();)
+ {
+ int aKeySize = ((Integer) it.next()).intValue();
+ if (aKeySize == kbLength)
+ {
+ keyLen = aKeySize;
+ break;
+ }
+ else if (aKeySize < kbLength)
+ keyLen = aKeySize;
+ else // all remaining key-sizes are longer than kb.length
+ break;
+ }
}
- else if (keyLen < kb.length)
+ if (keyLen == 0)
+ {
+ // we were unable to find a key-size, among those advertised by the
+ // cipher, that is less than or equal to the length of the kb array.
+ // set keyLen to kbLength. either the cipher implementation will throw
+ // an InvalidKeyException, or it is implemented in a way which can deal
+ // with an unsupported key-size.
+ keyLen = kbLength;
+ }
+ if (keyLen < kbLength)
{
byte[] kbb = kb;
kb = new byte[keyLen];
@@ -280,31 +307,54 @@ class CipherAdapter extends CipherSpi
{
if (params == null)
{
- byte[] iv = new byte[blockLen];
- random.nextBytes(iv);
- attributes.put(IMode.IV, iv);
+ // All cipher modes require parameters (like an IV) except ECB. When
+ // these cant be derived from the given key then it must be generated
+ // randomly if in ENCRYPT or WRAP mode. Parameters that have defaults
+ // for our cipher must be set to these defaults.
+ if (! mode.name().toLowerCase().startsWith(Registry.ECB_MODE + "("))
+ {
+ switch (opmode)
+ {
+ case Cipher.ENCRYPT_MODE:
+ case Cipher.WRAP_MODE:
+ byte[] iv = new byte[blockLen];
+ random.nextBytes(iv);
+ attributes.put(IMode.IV, iv);
+ break;
+ default:
+ throw new InvalidAlgorithmParameterException(
+ "Required algorithm parameters are missing for mode: "
+ + mode.name());
+ }
+ }
+ // Add default for block length etc.
blockLen = cipher.defaultBlockSize();
- attributes.put(IBlockCipher.CIPHER_BLOCK_SIZE, new Integer(blockLen));
+ attributes.put(IBlockCipher.CIPHER_BLOCK_SIZE,
+ Integer.valueOf(blockLen));
keyLen = 0;
}
else if (params instanceof BlockCipherParameterSpec)
{
- attributes.put(
- IBlockCipher.CIPHER_BLOCK_SIZE,
- new Integer(
- ((BlockCipherParameterSpec) params).getBlockSize()));
- attributes.put(IMode.IV, ((BlockCipherParameterSpec) params).getIV());
- keyLen = ((BlockCipherParameterSpec) params).getKeySize();
- blockLen = ((BlockCipherParameterSpec) params).getBlockSize();
+ BlockCipherParameterSpec bcps = (BlockCipherParameterSpec) params;
+ blockLen = bcps.getBlockSize();
+ attributes.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(blockLen));
+ attributes.put(IMode.IV, bcps.getIV());
+ keyLen = bcps.getKeySize();
}
else if (params instanceof IvParameterSpec)
{
+ // The size of the IV must match the block size
+ if (((IvParameterSpec) params).getIV().length != cipher.defaultBlockSize())
+ {
+ throw new InvalidAlgorithmParameterException();
+ }
+
attributes.put(IMode.IV, ((IvParameterSpec) params).getIV());
blockLen = cipher.defaultBlockSize();
- attributes.put(IBlockCipher.CIPHER_BLOCK_SIZE, new Integer(blockLen));
+ attributes.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(blockLen));
keyLen = 0;
}
- engineInit(opmode, key, random);
+ engineInitHandler(opmode, key, random);
}
protected void engineInit(int opmode, Key key, AlgorithmParameters params,
@@ -315,9 +365,7 @@ class CipherAdapter extends CipherSpi
try
{
if (params != null)
- {
- spec = params.getParameterSpec(BlockCipherParameterSpec.class);
- }
+ spec = params.getParameterSpec(BlockCipherParameterSpec.class);
}
catch (InvalidParameterSpecException ignored)
{
@@ -334,91 +382,50 @@ class CipherAdapter extends CipherSpi
{
engineUpdate(input, off, len, out, 0);
}
- catch (ShortBufferException x)
- { // should not happen
+ catch (ShortBufferException x) // should not happen
+ {
x.printStackTrace(System.err);
}
return out;
}
- // protected int
- // engineUpdate(byte[] in, int inOff, int inLen, byte[] out, int outOff)
- // throws ShortBufferException
- // {
- // int blockSize = mode.currentBlockSize();
- // int count = (partLen + inLen) / blockSize;
- // if (count * blockSize > out.length - outOff) {
- // throw new ShortBufferException();
- // }
- // byte[] buf;
- // if (partLen > 0 && count > 0) {
- // buf = new byte[partLen + inLen];
- // System.arraycopy(partBlock, 0, buf, 0, partLen);
- // if (in != null && inLen > 0) {
- // System.arraycopy(in, inOff, buf, partLen, inLen);
- // }
- // partLen = 0;
- // inOff = 0;
- // } else {
- // buf = in;
- // }
- // for (int i = 0; i < count; i++) {
- // mode.update(buf, i * blockSize + inOff, out, i * blockSize + outOff);
- // }
- // if (inOff + inLen > count * blockSize) {
- // partLen = (inOff + inLen) - (count * blockSize);
- // System.arraycopy(in, count * blockSize, partBlock, 0, partLen);
- // }
- // return count * blockSize;
- // }
-
protected int engineUpdate(byte[] in, int inOff, int inLen, byte[] out,
int outOff) throws ShortBufferException
{
- if (inLen == 0)
- { // nothing to process
- return 0;
- }
+ if (inLen == 0) // nothing to process
+ return 0;
final int blockSize = mode.currentBlockSize();
final int blockCount = (partLen + inLen) / blockSize;
final int result = blockCount * blockSize;
if (result > out.length - outOff)
+ throw new ShortBufferException();
+ if (blockCount == 0) // not enough bytes for even 1 block
{
- throw new ShortBufferException();
- }
- if (blockCount == 0)
- { // not enough bytes for even 1 block
System.arraycopy(in, inOff, partBlock, partLen, inLen);
partLen += inLen;
return 0;
}
final byte[] buf;
// we have enough bytes for at least 1 block
- if (partLen == 0)
- { // if no cached bytes use input
- buf = in;
- }
- else
- { // prefix input with cached bytes
+ if (partLen == 0) // if no cached bytes use input
+ buf = in;
+ else // prefix input with cached bytes
+ {
buf = new byte[partLen + inLen];
System.arraycopy(partBlock, 0, buf, 0, partLen);
if (in != null && inLen > 0)
- {
- System.arraycopy(in, inOff, buf, partLen, inLen);
- }
+ System.arraycopy(in, inOff, buf, partLen, inLen);
inOff = 0;
}
- for (int i = 0; i < blockCount; i++)
- { // update blockCount * blockSize
+ for (int i = 0; i < blockCount; i++) // update blockCount * blockSize
+ {
mode.update(buf, inOff, out, outOff);
inOff += blockSize;
outOff += blockSize;
}
partLen += inLen - result;
- if (partLen > 0)
- { // cache remaining bytes from buf
- System.arraycopy(buf, inOff, partBlock, 0, partLen);
- }
+ if (partLen > 0) // cache remaining bytes from buf
+ System.arraycopy(buf, inOff, partBlock, 0, partLen);
return result;
}
@@ -458,9 +465,7 @@ class CipherAdapter extends CipherSpi
else
{
if (partLen > 0)
- {
- throw new IllegalBlockSizeException(partLen + " trailing bytes");
- }
+ throw new IllegalBlockSizeException(partLen + " trailing bytes");
result = buf;
}
@@ -483,9 +488,7 @@ class CipherAdapter extends CipherSpi
{
byte[] buf = engineDoFinal(in, inOff, inLen);
if (out.length + outOff < buf.length)
- {
- throw new ShortBufferException();
- }
+ throw new ShortBufferException();
System.arraycopy(buf, 0, out, outOff, buf.length);
return buf.length;
}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/DESSpi.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/DESSpi.java
index ff86071..21f62b4 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/DESSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/DESSpi.java
@@ -41,15 +41,12 @@ package gnu.javax.crypto.jce.cipher;
import gnu.java.security.Registry;
/**
- * The implementation of the DES Service Provider Interface
- * (SPI) adapter.
+ * The implementation of the DES Service Provider Interface (SPI)
+ * adapter.
*/
-public final class DESSpi extends CipherAdapter
+public final class DESSpi
+ extends CipherAdapter
{
-
- // Constructors.
- // --------------------------------------------------------------------
-
public DESSpi()
{
super(Registry.DES_CIPHER);
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/KeyWrappingAlgorithmAdapter.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/KeyWrappingAlgorithmAdapter.java
new file mode 100644
index 0000000..03356a2
--- /dev/null
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/KeyWrappingAlgorithmAdapter.java
@@ -0,0 +1,423 @@
+/* KeyWrappingAlgorithmAdapter.java -- Base Adapter for Key Wrapping algorithms
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.jce.cipher;
+
+import gnu.java.security.Configuration;
+import gnu.java.security.Registry;
+import gnu.javax.crypto.jce.spec.BlockCipherParameterSpec;
+import gnu.javax.crypto.kwa.IKeyWrappingAlgorithm;
+import gnu.javax.crypto.kwa.KeyUnwrappingException;
+import gnu.javax.crypto.kwa.KeyWrappingAlgorithmFactory;
+
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.InvalidParameterSpecException;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.CipherSpi;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.ShortBufferException;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * An abstract base class to facilitate implementations of JCE Adapters for
+ * symmetric key block ciphers capable of providing key-wrapping functionality.
+ */
+abstract class KeyWrappingAlgorithmAdapter
+ extends CipherSpi
+{
+ private static final Logger log = Logger.getLogger(KeyWrappingAlgorithmAdapter.class.getName());
+ /** JCE canonical name of a null-padder. */
+ private static final String NO_PADDING = "nopadding";
+ /** Concrete Key Wrapping Algorithm SPI. */
+ protected IKeyWrappingAlgorithm kwAlgorithm;
+ /** Size in bytes of the padding block to be provided by external padders. */
+ protected int kwaBlockSize;
+ /** KEK size in bytes. */
+ protected int kwaKeySize;
+ /** Name of the supported mode. */
+ protected String supportedMode;
+ /** Operational mode in which this instance was initialised. */
+ protected int opmode = -1;
+ /** Initialisation Vector if/when user wants to override default one. */
+ byte[] iv;
+
+ /**
+ * Creates a new JCE Adapter for the designated Key Wrapping Algorithm name.
+ *
+ * @param name the canonical name of the key-wrapping algorithm.
+ * @param blockSize the block size in bytes of the underlying symmetric-key
+ * block cipher algorithm.
+ * @param keySize the allowed size in bytes of the KEK bytes to initialise the
+ * underlying symmetric-key block cipher algorithm with.
+ * @param supportedMode canonical name of the block mode the underlying cipher
+ * is supporting.
+ */
+ protected KeyWrappingAlgorithmAdapter(String name, int blockSize, int keySize,
+ String supportedMode)
+ {
+ super();
+
+ this.kwAlgorithm = KeyWrappingAlgorithmFactory.getInstance(name);
+ this.kwaBlockSize = blockSize;
+ this.kwaKeySize = keySize;
+ this.supportedMode = supportedMode;
+ }
+
+ /**
+ * Wraps the encoded form of a designated {@link Key}.
+ *
+ * @param key the key-material to wrap.
+ * @return the wrapped key.
+ * @throws InvalidKeyException If the key cannot be wrapped.
+ */
+ protected byte[] engineWrap(Key key)
+ throws InvalidKeyException, IllegalBlockSizeException
+ {
+ byte[] keyMaterial = key.getEncoded();
+ byte[] result = kwAlgorithm.wrap(keyMaterial, 0, keyMaterial.length);
+ return result;
+ }
+
+ /**
+ * Unwraps a previously-wrapped key-material.
+ *
+ * @param wrappedKey the wrapped key-material to unwrap.
+ * @param wrappedKeyAlgorithm the canonical name of the algorithm, which the
+ * unwrapped key-material represents. This name is used to
+ * instantiate a concrete instance of a {@link Key} for that
+ * algorithm. For example, if the value of this parameter is
+ * DSS
and the type (the next parameter) is
+ * {@link Cipher#PUBLIC_KEY} then an attempt to construct a concrete
+ * instance of a {@link java.security.interfaces.DSAPublicKey},
+ * using the unwrapped key material, shall be made.
+ * @param wrappedKeyType the type of wrapped key-material. MUST be one of
+ * {@link Cipher#PRIVATE_KEY}, {@link Cipher#PUBLIC_KEY}, or
+ * {@link Cipher#SECRET_KEY}.
+ * @return the unwrapped key-material as an instance of {@link Key} or one of
+ * its subclasses.
+ * @throws InvalidKeyException If the key cannot be unwrapped, or if
+ * wrappedKeyType
is an inappropriate type for the
+ * unwrapped key.
+ * @throws NoSuchAlgorithmException If the wrappedKeyAlgorithm
+ * is unknown to every currently installed Security Provider.
+ */
+ protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
+ int wrappedKeyType)
+ throws InvalidKeyException, NoSuchAlgorithmException
+ {
+ byte[] keyBytes;
+ try
+ {
+ keyBytes = kwAlgorithm.unwrap(wrappedKey, 0, wrappedKey.length);
+ }
+ catch (KeyUnwrappingException x)
+ {
+ InvalidKeyException y = new InvalidKeyException("engineUnwrap()");
+ y.initCause(x);
+ throw y;
+ }
+ Key result;
+ switch (wrappedKeyType)
+ {
+ case Cipher.SECRET_KEY:
+ result = new SecretKeySpec(keyBytes, wrappedKeyAlgorithm);
+ break;
+ case Cipher.PRIVATE_KEY:
+ case Cipher.PUBLIC_KEY:
+ X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
+ KeyFactory keyFactory = KeyFactory.getInstance(wrappedKeyAlgorithm);
+ try
+ {
+ if (wrappedKeyType == Cipher.PRIVATE_KEY)
+ result = keyFactory.generatePrivate(keySpec);
+ else
+ result = keyFactory.generatePublic(keySpec);
+ }
+ catch (InvalidKeySpecException x)
+ {
+ InvalidKeyException y = new InvalidKeyException("engineUnwrap()");
+ y.initCause(x);
+ throw y;
+ }
+ break;
+ default:
+ IllegalArgumentException x = new IllegalArgumentException("Invalid 'wrappedKeyType': "
+ + wrappedKeyType);
+ InvalidKeyException y = new InvalidKeyException("engineUnwrap()");
+ y.initCause(x);
+ throw y;
+ }
+ return result;
+ }
+
+ protected int engineGetBlockSize()
+ {
+ return kwaBlockSize;
+ }
+
+ protected byte[] engineGetIV()
+ {
+ return iv == null ? null : (byte[]) iv.clone();
+ }
+
+ protected int engineGetOutputSize(int inputLength)
+ {
+ switch (opmode)
+ {
+ case Cipher.WRAP_MODE:
+ return getOutputSizeForWrap(inputLength);
+ case Cipher.UNWRAP_MODE:
+ return getOutputSizeForUnwrap(inputLength);
+ default:
+ throw new IllegalStateException();
+ }
+ }
+
+ protected AlgorithmParameters engineGetParameters()
+ {
+ BlockCipherParameterSpec spec = new BlockCipherParameterSpec(iv,
+ kwaBlockSize,
+ kwaKeySize);
+ AlgorithmParameters result = null;
+ try
+ {
+ result = AlgorithmParameters.getInstance("BlockCipherParameters");
+ result.init(spec);
+ }
+ catch (NoSuchAlgorithmException x)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Unable to find BlockCipherParameters. Return null");
+ }
+ catch (InvalidParameterSpecException x)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Unable to initialise BlockCipherParameters. Return null");
+ }
+ return result;
+ }
+
+ protected void engineInit(int opmode, Key key, SecureRandom random)
+ throws InvalidKeyException
+ {
+ checkOpMode(opmode);
+ byte[] kekBytes = checkAndGetKekBytes(key);
+ initAlgorithm(opmode, kekBytes, null, random);
+ }
+
+ protected void engineInit(int opmode, Key key, AlgorithmParameters params,
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException, InvalidKeyException
+ {
+ AlgorithmParameterSpec spec = null;
+ try
+ {
+ if (params != null)
+ spec = params.getParameterSpec(BlockCipherParameterSpec.class);
+ }
+ catch (InvalidParameterSpecException x)
+ {
+ if (Configuration.DEBUG)
+ log.fine("Unable to translate algorithm parameters into an instance "
+ + "of BlockCipherParameterSpec. Discard");
+ }
+ engineInit(opmode, key, spec, random);
+ }
+
+ protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params,
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException, InvalidKeyException
+ {
+ checkOpMode(opmode);
+ byte[] kekBytes = checkAndGetKekBytes(key);
+ byte[] ivBytes = null;
+ if (params instanceof BlockCipherParameterSpec)
+ ivBytes = ((BlockCipherParameterSpec) params).getIV();
+ else if (params instanceof IvParameterSpec)
+ ivBytes = ((IvParameterSpec) params).getIV();
+
+ initAlgorithm(opmode, kekBytes, ivBytes, random);
+ }
+
+ protected void engineSetMode(String mode) throws NoSuchAlgorithmException
+ {
+ if (! supportedMode.equalsIgnoreCase(mode))
+ throw new UnsupportedOperationException("Only " + supportedMode
+ + " is supported");
+ }
+
+ /**
+ * NoPadding is the only padding algorithm supported by Key Wrapping Algorithm
+ * implementations in RI.
+ */
+ protected void engineSetPadding(String padding) throws NoSuchPaddingException
+ {
+ if (! NO_PADDING.equalsIgnoreCase(padding))
+ throw new UnsupportedOperationException("Only NoPadding is supported");
+ }
+
+ protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLength)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ protected int engineUpdate(byte[] input, int inputOffset, int inputLength,
+ byte[] output, int outputOffset)
+ throws ShortBufferException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLength)
+ throws IllegalBlockSizeException, BadPaddingException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ protected int engineDoFinal(byte[] input, int inputOffset, int inputLength,
+ byte[] output, int outputOffset)
+ throws IllegalBlockSizeException, BadPaddingException, ShortBufferException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Return the minimum size in bytes of a place holder large enough to receive
+ * the cipher text resulting from a wrap method with the designated size of
+ * the plain text.
+ * kwaBlockSize
--passed to this method through its
+ * constructor-- greater than or equal to the designated
+ * inputLength
.
+ *
+ * @param inputLength the size of a plain text.
+ * @return an estimate of the size, in bytes, of the place holder to receive
+ * the resulting bytes of a wrap method.
+ */
+ protected int getOutputSizeForWrap(int inputLength)
+ {
+ return kwaBlockSize * (inputLength + kwaBlockSize - 1) / kwaBlockSize;
+ }
+
+ /**
+ * Return the minimum size in bytes of a place holder large enough to receive
+ * the plain text resulting from an unwrap method with the designated size of
+ * the cipher text.
+ * paddingBlockSize
--passed to this method through its
+ * constructor-- greater than or equal to the designated
+ * inputLength
.
+ *
+ * @param inputLength the size of a cipher text.
+ * @return an estimate of the size, in bytes, of the place holder to receive
+ * the resulting bytes of an uwrap method.
+ */
+ protected int getOutputSizeForUnwrap(int inputLength)
+ {
+ return kwaBlockSize * (inputLength + kwaBlockSize - 1) / kwaBlockSize;
+ }
+
+ private void checkOpMode(int opmode)
+ {
+ switch (opmode)
+ {
+ case Cipher.WRAP_MODE:
+ case Cipher.UNWRAP_MODE:
+ return;
+ }
+ throw new IllegalArgumentException("Unsupported operational mode: " + opmode);
+ }
+
+ /**
+ * Returns the key bytes, iff it was in RAW format.
+ *
+ * @param key the opaque JCE secret key to use as the KEK.
+ * @return the bytes of the encoded form of the designated kek, iff it was in
+ * RAW format.
+ * @throws InvalidKeyException if the designated key is not in the RAW format.
+ */
+ private byte[] checkAndGetKekBytes(Key key) throws InvalidKeyException
+ {
+ if (! Registry.RAW_ENCODING_SHORT_NAME.equalsIgnoreCase(key.getFormat()))
+ throw new InvalidKeyException("Only RAW key format is supported");
+ byte[] result = key.getEncoded();
+ int kekSize = result.length;
+ if (kekSize != kwaKeySize)
+ throw new InvalidKeyException("Invalid key material size. Expected "
+ + kwaKeySize + " but found " + kekSize);
+ return result;
+ }
+
+ private void initAlgorithm(int opmode, byte[] kek, byte[] ivBytes,
+ SecureRandom rnd)
+ throws InvalidKeyException
+ {
+ this.opmode = opmode;
+ Map attributes = new HashMap();
+ attributes.put(IKeyWrappingAlgorithm.KEY_ENCRYPTION_KEY_MATERIAL, kek);
+ if (ivBytes != null)
+ {
+ this.iv = (byte[]) ivBytes.clone();
+ attributes.put(IKeyWrappingAlgorithm.INITIAL_VALUE, this.iv);
+ }
+ else
+ this.iv = null;
+ if (rnd != null)
+ attributes.put(IKeyWrappingAlgorithm.SOURCE_OF_RANDOMNESS, rnd);
+
+ kwAlgorithm.init(attributes);
+ }
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/KhazadSpi.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/KhazadSpi.java
index 397c27d..6e744a2 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/KhazadSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/KhazadSpi.java
@@ -44,12 +44,9 @@ import gnu.java.security.Registry;
* The implementation of the Khazad Service Provider Interface
* (SPI) adapter.
*/
-public final class KhazadSpi extends CipherAdapter
+public final class KhazadSpi
+ extends CipherAdapter
{
-
- // Constructors.
- // --------------------------------------------------------------------
-
public KhazadSpi()
{
super(Registry.KHAZAD_CIPHER);
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/NullCipherSpi.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/NullCipherSpi.java
index e6d78ef..e50e00c 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/NullCipherSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/NullCipherSpi.java
@@ -44,12 +44,9 @@ import gnu.java.security.Registry;
* The implementation of the Null cipher Service Provider Interface
* (SPI) adapter.
*/
-public final class NullCipherSpi extends CipherAdapter
+public final class NullCipherSpi
+ extends CipherAdapter
{
-
- // Constructors.
- // -----------------------------------------------------------------------
-
public NullCipherSpi()
{
super(Registry.NULL_CIPHER);
diff --git a/libjava/classpath/gnu/javax/crypto/jce/cipher/PBES2.java b/libjava/classpath/gnu/javax/crypto/jce/cipher/PBES2.java
index 9889ab9..26a6a2c 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/cipher/PBES2.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/cipher/PBES2.java
@@ -55,20 +55,13 @@ import javax.crypto.interfaces.PBEKey;
import javax.crypto.spec.SecretKeySpec;
/**
- *
- *
- *
+ * BlockCipherParameters ::= SEQUENCE {
- * blockSize INTEGER,
- * keySize INTEGER,
- * initializationVector OCTET STRING OPTIONAL }
- *
+ * BlockCipherParameters ::= SEQUENCE {
+ * blockSize INTEGER,
+ * keySize INTEGER,
+ * initializationVector OCTET STRING OPTIONAL }
+ *
+ *
* @return The parameters, encoded an an ASN.1 DER sequence.
* @throws java.io.IOException If encoding these parameters fails.
*/
@@ -90,114 +85,59 @@ public class BlockCipherParameters extends AlgorithmParametersSpi
protected byte[] engineGetEncoded(String format) throws IOException
{
- if (!format.equalsIgnoreCase(DEFAULT_FORMAT)
- && !format.equalsIgnoreCase("asn1"))
- {
- throw new IOException("unknown format \"" + format + "\"");
- }
- // This is probably a bad idea.
- /*
- int len = 12 + ((cipherSpec.getIV() != null)
- ? cipherSpec.getIV().length + 2 : 0);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- out.write(0x30);
- out.write(len);
- out.write(0x02);
- out.write(4);
- out.write(cipherSpec.getBlockSize() >>> 24 & 0xff);
- out.write(cipherSpec.getBlockSize() >>> 16 & 0xff);
- out.write(cipherSpec.getBlockSize() >>> 8 & 0xff);
- out.write(cipherSpec.getBlockSize() & 0xff);
- out.write(0x02);
- out.write(4);
- out.write(cipherSpec.getKeySize() >>> 24 & 0xff);
- out.write(cipherSpec.getKeySize() >>> 16 & 0xff);
- out.write(cipherSpec.getKeySize() >>> 8 & 0xff);
- out.write(cipherSpec.getKeySize() & 0xff);
- if (cipherSpec.getIV() != null) {
- out.write(0x04);
- len = cipherSpec.getIV().length;
- out.write(len & 0xff);
- out.write(cipherSpec.getIV());
- }
- out.write(0); out.write(0);
- return out.toByteArray();*/
+ if (! format.equalsIgnoreCase(DEFAULT_FORMAT)
+ && ! format.equalsIgnoreCase("asn1"))
+ throw new IOException("unknown format \"" + format + "\"");
DERWriter writer = new DERWriter();
+ int cipherBlockSize = cipherSpec.getBlockSize();
+ int cipherKeySize = cipherSpec.getKeySize();
+ byte[] iv = cipherSpec.getIV();
return writer.joinarrays(
- writer.writeBigInteger(BigInteger.valueOf(cipherSpec.getBlockSize())),
- writer.writeBigInteger(BigInteger.valueOf(cipherSpec.getKeySize())),
- (cipherSpec.getIV() != null) ? writer.writeBigInteger(new BigInteger(
- cipherSpec.getIV()))
- : new byte[0]);
+ writer.writeBigInteger(BigInteger.valueOf(cipherBlockSize)),
+ writer.writeBigInteger(BigInteger.valueOf(cipherKeySize)),
+ (iv != null) ? writer.writeBigInteger(new BigInteger(iv))
+ : new byte[0]);
}
protected void engineInit(AlgorithmParameterSpec spec)
throws InvalidParameterSpecException
{
if (spec instanceof BlockCipherParameterSpec)
- {
- cipherSpec = (BlockCipherParameterSpec) spec;
- }
+ cipherSpec = (BlockCipherParameterSpec) spec;
else
- {
- throw new InvalidParameterSpecException();
- }
+ throw new InvalidParameterSpecException();
}
protected void engineInit(byte[] encoded, String format) throws IOException
{
- if (!format.equalsIgnoreCase(DEFAULT_FORMAT)
- && !format.equalsIgnoreCase("ASN1"))
- {
- throw new IOException("invalid format: only accepts ASN.1");
- }
+ if (! format.equalsIgnoreCase(DEFAULT_FORMAT)
+ && ! format.equalsIgnoreCase("ASN1"))
+ throw new IOException("invalid format: only accepts ASN.1");
engineInit(encoded);
}
protected void engineInit(byte[] encoded) throws IOException
{
- // This is probably an equally bad idea.
- /*if (encoded[0] != 0x30) {
- throw new IOException("malformed ASN.1 sequence");
- }
- if (encoded[2] != 0x02 || encoded[3] != 4) {
- throw new IOException("malformed ASN.1 sequence");
- }
- int blockSize = encoded[4] << 24 | encoded[5] << 16
- | encoded[6] << 8 | encoded[7];
- if (encoded[8] != 0x02 || encoded[9] != 4) {
- throw new IOException("malformed ASN.1 sequence");
- }
- int keySize = encoded[10] << 24 | encoded[11] << 16
- | encoded[12] << 8 | encoded[13];
- if (encoded[14] == 0x04) {
- int len = encoded[15] & 0xff;
- byte[] iv = new byte[len];
- System.arraycopy(encoded, 16, iv, 0, len);
- cipherSpec = new BlockCipherParameterSpec(iv, blockSize, keySize);
- } else if (encoded[14] == 0) {
- cipherSpec = new BlockCipherParameterSpec(blockSize, keySize);
- } else {
- throw new IOException("malformed ASN.1 sequence");
- }*/
DERReader reader = new DERReader(encoded);
int bs = reader.getBigInteger().intValue();
int ks = reader.getBigInteger().intValue();
byte[] iv = null;
if (reader.hasMorePrimitives())
- {
- iv = reader.getBigInteger().toByteArray();
- }
+ iv = reader.getBigInteger().toByteArray();
cipherSpec = new BlockCipherParameterSpec(iv, bs, ks);
- System.out.println(cipherSpec);
+ if (Configuration.DEBUG)
+ log.fine("cipherSpec: " + cipherSpec);
}
protected AlgorithmParameterSpec engineGetParameterSpec(Class c)
throws InvalidParameterSpecException
{
if (c.isInstance(cipherSpec))
+ return cipherSpec;
+ if (IvParameterSpec.class.isAssignableFrom(c))
{
- return cipherSpec;
+ IvParameterSpec result = new IvParameterSpec(cipherSpec.getIV());
+ return result;
}
throw new InvalidParameterSpecException();
}
@@ -206,4 +146,4 @@ public class BlockCipherParameters extends AlgorithmParametersSpi
{
return cipherSpec.toString();
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/params/DEREncodingException.java b/libjava/classpath/gnu/javax/crypto/jce/params/DEREncodingException.java
index ddfa6e1..b89ceda 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/params/DEREncodingException.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/params/DEREncodingException.java
@@ -38,7 +38,8 @@ exception statement from your version. */
package gnu.javax.crypto.jce.params;
-class DEREncodingException extends java.io.IOException
+class DEREncodingException
+ extends java.io.IOException
{
public DEREncodingException()
@@ -50,4 +51,4 @@ class DEREncodingException extends java.io.IOException
{
super(msg);
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/params/DERReader.java b/libjava/classpath/gnu/javax/crypto/jce/params/DERReader.java
index f614232..68c6802 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/params/DERReader.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/params/DERReader.java
@@ -43,15 +43,10 @@ import java.math.BigInteger;
class DERReader
{
byte source[];
-
int pos;
-
static final int UNIVERSAL = 1;
-
static final int APPLICATION = 2;
-
static final int CONTEXT_SPECIFIC = 3;
-
static final int PRIVATE = 4;
public DERReader()
@@ -86,53 +81,37 @@ class DERReader
return new BigInteger(getPrimitive());
}
- //Reads Primitive, definite-length method
+ // Reads Primitive, definite-length method
private byte[] getPrimitive() throws DEREncodingException
{
int tmp = pos;
-
- //Read Identifier
+ // Read Identifier
byte identifier = source[tmp++];
if ((0x20 & identifier) != 0)
throw new DEREncodingException();
int type = translateLeadIdentifierByte(identifier);
- //System.out.println("Type: " + type);
-
- //get tag
+ // get tag
int tag = (0x1f & identifier);
- //if( tag == 0x1f)
- // tag = getIdentifier(tmp);
- //System.out.println("Tag: " + tag);
-
- //get length
- byte len = source[tmp]; //may be length of length parameter
+ // get length
+ byte len = source[tmp]; // may be length of length parameter
long length = 0x7f & len;
int i;
if ((0x80 & len) != 0)
{
- //System.out.println("Extra Long Length");
len &= 0x7f;
- //System.out.println("Length of Length: " + len);
- //get length here
+ // get length here
length = 0;
for (i = 0; i < len; i++)
{
tmp++;
length <<= 8;
length += (source[tmp] < 0) ? (256 + source[tmp]) : source[tmp];
- //System.out.println("Length of Length: " + length);
}
tmp++;
}
else
tmp++;
- /*System.out.println("Position: " + tmp);
- System.out.println("Length: " + length);
- for( i = 0; i < 10; i++)
- System.out.print(source[tmp + i] + " ");
- System.out.println();*/
-
byte tmpb[] = new byte[(int) length];
System.arraycopy(source, tmp, tmpb, 0, (int) length);
pos = (int) (tmp + length);
@@ -157,4 +136,4 @@ class DERReader
tpos++;
return tpos;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/params/DERWriter.java b/libjava/classpath/gnu/javax/crypto/jce/params/DERWriter.java
index 876c2cd..7bdea10 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/params/DERWriter.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/params/DERWriter.java
@@ -43,11 +43,8 @@ import java.math.BigInteger;
class DERWriter
{
static final int UNIVERSAL = 1;
-
static final int APPLICATION = 2;
-
static final int CONTEXT_SPECIFIC = 3;
-
static final int PRIVATE = 4;
public DERWriter()
@@ -56,7 +53,8 @@ class DERWriter
public byte[] writeBigInteger(BigInteger i)
{
- return writePrimitive(0x02, UNIVERSAL,
+ return writePrimitive(0x02,
+ UNIVERSAL,
(int) Math.ceil((double) i.bitLength() / 8),
i.toByteArray());
}
@@ -71,7 +69,7 @@ class DERWriter
public byte[] joinarrays(byte a[], byte b[])
{
byte d[] = new byte[a.length + b.length];
- System.arraycopy(a, 0, d, 0, a.length);
+ System.arraycopy(a, 0, d, 0, a.length);
System.arraycopy(b, 0, d, a.length, b.length);
return d;
}
@@ -92,7 +90,7 @@ class DERWriter
{
int count = (int) (Math.log(identifier) / Math.log(256));
b = new byte[count + 1];
- b[0] = (byte) (translateLeadIdentifierByte(identifierencoding) | 0x1f);
+ b[0] = (byte)(translateLeadIdentifierByte(identifierencoding) | 0x1f);
int i;
for (i = 1; i < (count + 1); i++)
{
@@ -100,14 +98,13 @@ class DERWriter
b[i] |= 0x80;
}
b[i - 1] ^= 0x80;
- //System.out.println("Identifier1: " + b[0]);
return b;
}
else
{
b = new byte[1];
- b[0] = (byte) ((translateLeadIdentifierByte(identifierencoding) | (byte) (identifier & 0x1f)) & 0xdf);
- //System.out.println("Identifier2: " + b[0]);
+ b[0] = (byte)((translateLeadIdentifierByte(identifierencoding)
+ | (byte)(identifier & 0x1f)) & 0xdf);
return b;
}
}
@@ -130,25 +127,17 @@ class DERWriter
if (length > 127)
{
int count = (int) Math.ceil(Math.log(length) / Math.log(256));
- //System.out.println("Length byte count: " + count);
b = new byte[count + 1];
- b[0] = (byte) ((count & 0x7f) | 0x80);
+ b[0] = (byte)((count & 0x7f) | 0x80);
for (int i = 1; i < (count + 1); i++)
- {
- b[i] = (byte) (length >>> (8 * (count - i)));
- //System.out.println("Length1 byte1: " + (length >>> (8 * ( count - i) )));
- //System.out.println("Length1 byte2: " + b[i]);
- }
-
- //System.out.println("Length1: " + length);
+ b[i] = (byte) (length >>> (8 * (count - i)));
return b;
}
else
{
b = new byte[1];
b[0] = (byte) (length & 0x7f);
- //System.out.println("Length2: " + length);
return b;
}
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/prng/ARCFourRandomSpi.java b/libjava/classpath/gnu/javax/crypto/jce/prng/ARCFourRandomSpi.java
index 0c07156..652793b 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/prng/ARCFourRandomSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/prng/ARCFourRandomSpi.java
@@ -48,24 +48,17 @@ import java.security.SecureRandomSpi;
import java.util.HashMap;
/**
- * Implementation of the Service Provider Interface (SPI)
- * for the ARCFOUR keystream generator.
+ * Implementation of the Service Provider Interface (SPI) for
+ * the ARCFOUR keystream generator.
*/
-public class ARCFourRandomSpi extends SecureRandomSpi
+public class ARCFourRandomSpi
+ extends SecureRandomSpi
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** Our underlying prng instance. */
private IRandom adaptee;
-
/** Have we been initialized? */
private boolean virgin;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
* Default 0-arguments constructor.
*/
@@ -76,20 +69,10 @@ public class ARCFourRandomSpi extends SecureRandomSpi
virgin = true;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.security.SecureRandomSpi interface implementation ------------------
-
public byte[] engineGenerateSeed(int numBytes)
{
if (numBytes < 1)
- {
- return new byte[0];
- }
+ return new byte[0];
byte[] result = new byte[numBytes];
this.engineNextBytes(result);
return result;
@@ -98,9 +81,7 @@ public class ARCFourRandomSpi extends SecureRandomSpi
public void engineNextBytes(byte[] bytes)
{
if (virgin)
- {
- this.engineSetSeed(new byte[0]);
- }
+ this.engineSetSeed(new byte[0]);
try
{
adaptee.nextBytes(bytes, 0, bytes.length);
@@ -117,4 +98,4 @@ public class ARCFourRandomSpi extends SecureRandomSpi
adaptee.init(attributes);
virgin = false;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/prng/CSPRNGSpi.java b/libjava/classpath/gnu/javax/crypto/jce/prng/CSPRNGSpi.java
index c0aa015..6ded636 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/prng/CSPRNGSpi.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/prng/CSPRNGSpi.java
@@ -38,29 +38,22 @@ exception statement from your version. */
package gnu.javax.crypto.jce.prng;
-import gnu.java.security.Registry;
-import gnu.javax.crypto.prng.CSPRNG;
import gnu.java.security.prng.IRandom;
import gnu.java.security.prng.LimitReachedException;
+import gnu.javax.crypto.prng.CSPRNG;
import java.net.MalformedURLException;
import java.security.SecureRandomSpi;
/**
- * The implementation of the continuously-seeded SecureRandom
- * Service Provider Interface (SPI) adapter.null
if
- * there is no IV.
+ *
+ * @param iv The initialization vector, or null
if there is no
+ * IV.
* @param blockSize The cipher's block size, in bytes.
- * @param keySize The cipher's key size, in bytes.
+ * @param keySize The cipher's key size, in bytes.
*/
public BlockCipherParameterSpec(byte[] iv, int blockSize, int keySize)
{
@@ -87,22 +73,19 @@ public class BlockCipherParameterSpec implements AlgorithmParameterSpec
/**
* Create a new parameter specification with no IV.
- *
+ *
* @param blockSize The cipher's block size, in bytes.
- * @param keySize The cipher's key size, in bytes.
+ * @param keySize The cipher's key size, in bytes.
*/
public BlockCipherParameterSpec(int blockSize, int keySize)
{
this(null, blockSize, keySize);
}
- // Instance methods.
- // -----------------------------------------------------------------------
-
/**
- * Get the initialization vector for the cipher, or null
- * if there is no IV.
- *
+ * Get the initialization vector for the cipher, or null
if
+ * there is no IV.
+ *
* @return The IV.
*/
public byte[] getIV()
@@ -112,7 +95,7 @@ public class BlockCipherParameterSpec implements AlgorithmParameterSpec
/**
* Get the block size of the cipher these parameters are for.
- *
+ *
* @return The block size.
*/
public int getBlockSize()
@@ -122,7 +105,7 @@ public class BlockCipherParameterSpec implements AlgorithmParameterSpec
/**
* Get the key size of the cipher these parameters are for.
- *
+ *
* @return The block size.
*/
public int getKeySize()
@@ -133,7 +116,7 @@ public class BlockCipherParameterSpec implements AlgorithmParameterSpec
public String toString()
{
return getClass().getName() + " { "
- + ((iv != null) ? ("IV=" + Util.toString(iv)) + ", " : "") + "BS="
- + blockSize + ", KS=" + keySize + " }";
+ + ((iv != null) ? ("IV=" + Util.toString(iv)) + ", " : "")
+ + "BS=" + blockSize + ", KS=" + keySize + " }";
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/spec/TMMHParameterSpec.java b/libjava/classpath/gnu/javax/crypto/jce/spec/TMMHParameterSpec.java
index 0ebec09..3564372 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/spec/TMMHParameterSpec.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/spec/TMMHParameterSpec.java
@@ -45,35 +45,27 @@ import java.security.spec.AlgorithmParameterSpec;
/**
* This class represents the algorithm parameters for the Truncated
* Multi-Modular Hash function for use with JCE-derived instances of
- * {@link gnu.crypto.mac.TMMH16}.
- *
- * null
if no prefix was
- * specified.
- *
+ * Return the prefix, or null
if no prefix was specified.
+ *
* @return The prefix.
*/
public byte[] getPrefix()
{
return prefix;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/jce/spec/UMac32ParameterSpec.java b/libjava/classpath/gnu/javax/crypto/jce/spec/UMac32ParameterSpec.java
index 47d807d..0990cc6 100644
--- a/libjava/classpath/gnu/javax/crypto/jce/spec/UMac32ParameterSpec.java
+++ b/libjava/classpath/gnu/javax/crypto/jce/spec/UMac32ParameterSpec.java
@@ -41,25 +41,19 @@ package gnu.javax.crypto.jce.spec;
import java.security.spec.AlgorithmParameterSpec;
/**
- * This class represents the parameters for the UMAC-32 message
- * authentication code algorithm. In practice this means the
- * Nonce material used to initialize the algorithm.
+ * This class represents the parameters for the UMAC-32 message authentication
+ * code algorithm. In practice this means the Nonce material used to
+ * initialize the algorithm.
*/
-public class UMac32ParameterSpec implements AlgorithmParameterSpec
+public class UMac32ParameterSpec
+ implements AlgorithmParameterSpec
{
-
- // Constants and variables.
- // -----------------------------------------------------------------------
-
/** The Nonce material. */
protected byte[] nonce;
- // Constructors.
- // -----------------------------------------------------------------------
-
/**
* Create a new parameter instance.
- *
+ *
* @param nonce The nonce material.
*/
public UMac32ParameterSpec(byte[] nonce)
@@ -67,16 +61,13 @@ public class UMac32ParameterSpec implements AlgorithmParameterSpec
this.nonce = nonce;
}
- // Instance methods.
- // -----------------------------------------------------------------------
-
/**
* Return the nonce material.
- *
+ *
* @return The nonce material.
*/
public byte[] getNonce()
{
return nonce;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/key/BaseKeyAgreementParty.java b/libjava/classpath/gnu/javax/crypto/key/BaseKeyAgreementParty.java
index bfd9378..fc5ddb7 100644
--- a/libjava/classpath/gnu/javax/crypto/key/BaseKeyAgreementParty.java
+++ b/libjava/classpath/gnu/javax/crypto/key/BaseKeyAgreementParty.java
@@ -47,41 +47,28 @@ import java.security.SecureRandom;
import java.util.Map;
/**
- * null
if this is an
- * intermediary step that does not cause any output.
+ * intermediary step that does not cause any output.
* @throws KeyAgreementException if an exception occurs during the processing
- * of the incoming message, or during the generation of the outgoing message.
+ * of the incoming message, or during the generation of the outgoing
+ * message.
*/
OutgoingMessage processMessage(IncomingMessage in)
throws KeyAgreementException;
/**
- * true
if the party in the key agreement protocol
+ * Returns true
if the party in the key agreement protocol
* exchange has completed its part of the exchange. If this is the case an
* {@link IllegalStateException} is thrown for any method invocation except
* init()
or reset()
.
+ *
* @return true
if this party has completed its part of the key
- * agreement protocol exchange; false
otherwise.
+ * agreement protocol exchange; false
otherwise.
*/
boolean isComplete();
/**
- * getInstance(raw, 0, raw.length)
.
- *
+ *
* @param raw the encoded form, excluding the header bytes.
* @return a new instance of IncomingMessage
.
*/
@@ -126,9 +113,9 @@ public class IncomingMessage
}
/**
- * null
root cause exception. */
private Throwable cause = null;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- * KeyAgreementException
. The
- * root exception and the detailed message are null
.KeyAgreementException
. The
+ * root exception and the detailed message are null
.
*/
public KeyAgreementException()
{
@@ -71,11 +64,11 @@ public class KeyAgreementException extends KeyManagementException implements
}
/**
- * KeyAgreementException
with a
- * detailed message. The root exception is null
.KeyAgreementException
with a
+ * detailed message. The root exception is null
.
+ *
* @param detail a possibly null
string containing details of
- * the exception.
+ * the exception.
* @see Throwable#getMessage()
*/
public KeyAgreementException(String detail)
@@ -84,13 +77,13 @@ public class KeyAgreementException extends KeyManagementException implements
}
/**
- * KeyAgreementException
with a
- * detailed message and a root exception.KeyAgreementException
with a
+ * detailed message and a root exception.
+ *
* @param detail a possibly null
string containing details of
- * the exception.
+ * the exception.
* @param cause a possibly null
root exception that caused this
- * exception.
+ * exception.
* @see Throwable#getMessage()
* @see #getCause()
*/
@@ -100,17 +93,11 @@ public class KeyAgreementException extends KeyManagementException implements
this.cause = cause;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
- * null
if the cause
- * is nonexistent or unknown. The cause is the throwable that caused
- * this exception to be thrown.null
if the cause is
+ * nonexistent or unknown. The cause is the throwable that caused this
+ * exception to be thrown.
+ *
* @return the possibly null
exception that caused this one.
*/
public Throwable getCause()
@@ -119,69 +106,61 @@ public class KeyAgreementException extends KeyManagementException implements
}
/**
- * System.err
. If this
+ * Prints this exception's stack trace to System.err
. If this
* exception has a root exception; the stack trace of the root
- * exception is also printed to System.err
.System.err
.
*/
public void printStackTrace()
{
super.printStackTrace();
if (cause != null)
- {
- cause.printStackTrace();
- }
+ cause.printStackTrace();
}
/**
- * A
in a two-party A..B
exchange, given the
* canonical name of this protocol. Party A
is usually the
- * initiator of the exchange.A
, or null
if none found.
+ * A
, or null
if none found.
*/
public static IKeyAgreementParty getPartyAInstance(String name)
{
if (name == null)
- {
- return null;
- }
-
+ return null;
name = name.trim();
IKeyAgreementParty result = null;
if (name.equalsIgnoreCase(Registry.DH_KA))
- {
- result = new DiffieHellmanSender();
- }
+ result = new DiffieHellmanSender();
else if (name.equalsIgnoreCase(Registry.ELGAMAL_KA))
- {
- result = new ElGamalSender();
- }
+ result = new ElGamalSender();
else if (name.equalsIgnoreCase(Registry.SRP6_KA))
- {
- result = new SRP6User();
- }
+ result = new SRP6User();
else if (name.equalsIgnoreCase(Registry.SRP_SASL_KA))
- {
- result = new SRP6SaslClient();
- }
+ result = new SRP6SaslClient();
else if (name.equalsIgnoreCase(Registry.SRP_TLS_KA))
- {
- result = new SRP6TLSClient();
- }
-
+ result = new SRP6TLSClient();
return result;
}
/**
- * B
in a two-party A..B
exchange, given the
- * canonical name of this protocol.B
, or null
if none found.
+ * B
, or null
if none found.
*/
public static IKeyAgreementParty getPartyBInstance(String name)
{
if (name == null)
- {
- return null;
- }
-
+ return null;
name = name.trim();
IKeyAgreementParty result = null;
if (name.equalsIgnoreCase(Registry.DH_KA))
- {
- result = new DiffieHellmanReceiver();
- }
+ result = new DiffieHellmanReceiver();
else if (name.equalsIgnoreCase(Registry.ELGAMAL_KA))
- {
- result = new ElGamalReceiver();
- }
+ result = new ElGamalReceiver();
else if (name.equalsIgnoreCase(Registry.SRP6_KA))
- {
- result = new SRP6Host();
- }
+ result = new SRP6Host();
else if (name.equalsIgnoreCase(Registry.SRP_SASL_KA))
- {
- result = new SRP6SaslServer();
- }
+ result = new SRP6SaslServer();
else if (name.equalsIgnoreCase(Registry.SRP_TLS_KA))
- {
- result = new SRP6TLSServer();
- }
-
+ result = new SRP6TLSServer();
return result;
}
/**
- *
- * key --> 4-byte-length || 1-byte-type-and-format || encoded-key-bytes
+ * key --> 4-byte-length || 1-byte-type-and-format || encoded-key-bytes
*
*
* @param k the public key to encode.
@@ -152,9 +134,8 @@ public class OutgoingMessage
* representing the total length, excluding these 4 bytes, of the bytes
* representing the encoded key and the one-byte representing the key-type and
* format; i.e.
- *
*
- * key --> 4-byte-length || 1-byte-type-and-format || encoded-key-bytes
+ * key --> 4-byte-length || 1-byte-type-and-format || encoded-key-bytes
*
*
* @param k the private key to encode.
@@ -166,8 +147,8 @@ public class OutgoingMessage
}
/**
- * null
for the q
+ * parameter. RFC-2631 DOES NOT allow for an optional value for that
+ * parameter, hence we replace such null values with 0
, and do
+ * the reverse in the corresponding decode method.
*
* @return the DER encoded form of the ASN.1 representation of the
* PrivateKeyInfo field in an X.509 certificate.
@@ -117,6 +124,8 @@ public class DHKeyPairPKCS8Codec
BigInteger p = pk.getParams().getP();
BigInteger g = pk.getParams().getG();
BigInteger q = pk.getQ();
+ if (q == null)
+ q = BigInteger.ZERO;
BigInteger x = pk.getX();
ArrayList params = new ArrayList(3);
@@ -212,6 +221,8 @@ public class DHKeyPairPKCS8Codec
val = der.read();
DerUtil.checkIsBigInteger(val, "Wrong Q field");
q = (BigInteger) val.getValue();
+ if (q.compareTo(BigInteger.ZERO) == 0)
+ q = null;
val = der.read();
byte[] xBytes = (byte[]) val.getValue();
diff --git a/libjava/classpath/gnu/javax/crypto/key/dh/DHKeyPairRawCodec.java b/libjava/classpath/gnu/javax/crypto/key/dh/DHKeyPairRawCodec.java
index c0ff82be..aefcd5f 100644
--- a/libjava/classpath/gnu/javax/crypto/key/dh/DHKeyPairRawCodec.java
+++ b/libjava/classpath/gnu/javax/crypto/key/dh/DHKeyPairRawCodec.java
@@ -47,62 +47,49 @@ import java.security.PrivateKey;
import java.security.PublicKey;
/**
- *
- *
- *
+ *
* @param key the key to encode.
* @return the Raw format encoding of the designated key.
* @throws IllegalArgumentException if the designated key is not a DH one.
@@ -110,59 +97,49 @@ public class DHKeyPairRawCodec implements IKeyPairCodec
*/
public byte[] encodePublicKey(PublicKey key)
{
- if (!(key instanceof GnuDHPublicKey))
- {
- throw new IllegalArgumentException("key");
- }
-
+ if (! (key instanceof GnuDHPublicKey))
+ throw new IllegalArgumentException("key");
GnuDHPublicKey dhKey = (GnuDHPublicKey) key;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_DH_PUBLIC_KEY[0]);
baos.write(Registry.MAGIC_RAW_DH_PUBLIC_KEY[1]);
baos.write(Registry.MAGIC_RAW_DH_PUBLIC_KEY[2]);
baos.write(Registry.MAGIC_RAW_DH_PUBLIC_KEY[3]);
-
// version
baos.write(0x01);
-
// q
byte[] buffer = dhKey.getQ().toByteArray();
int length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// p
buffer = dhKey.getParams().getP().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// g
buffer = dhKey.getParams().getG().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// y
buffer = dhKey.getY().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -173,83 +150,84 @@ public class DHKeyPairRawCodec implements IKeyPairCodec
|| k[1] != Registry.MAGIC_RAW_DH_PUBLIC_KEY[1]
|| k[2] != Registry.MAGIC_RAW_DH_PUBLIC_KEY[2]
|| k[3] != Registry.MAGIC_RAW_DH_PUBLIC_KEY[3])
- {
- throw new IllegalArgumentException("magic");
- }
-
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
+ throw new IllegalArgumentException("version");
int i = 5;
int l;
byte[] buffer;
-
// q
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger q = new BigInteger(1, buffer);
-
// p
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger p = new BigInteger(1, buffer);
-
// g
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger g = new BigInteger(1, buffer);
-
// y
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger y = new BigInteger(1, buffer);
-
return new GnuDHPublicKey(q, p, g, y);
}
/**
- * q
in internet order,toByteArray()
method on the DH parameter q
,p
in internet order,toByteArray()
method on the DH parameter p
,g
,toByteArray()
method on the DH parameter g
,y
,toByteArray()
method on the DH parameter y
,q
in internet order,toByteArray()
method on the DH parameter q
,
+ * p
in internet order,toByteArray()
method on the DH parameter p
,
+ * g
,toByteArray()
method on the DH parameter g
,
+ * y
,toByteArray()
method on the DH parameter y
,
+ *
- *
- *
+ *
* @param key the key to encode.
* @return the Raw format encoding of the designated key.
* @throws IllegalArgumentException if the designated key is not a DH one.
@@ -257,59 +235,49 @@ public class DHKeyPairRawCodec implements IKeyPairCodec
*/
public byte[] encodePrivateKey(PrivateKey key)
{
- if (!(key instanceof GnuDHPrivateKey))
- {
- throw new IllegalArgumentException("key");
- }
-
+ if (! (key instanceof GnuDHPrivateKey))
+ throw new IllegalArgumentException("key");
GnuDHPrivateKey dhKey = (GnuDHPrivateKey) key;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_DH_PRIVATE_KEY[0]);
baos.write(Registry.MAGIC_RAW_DH_PRIVATE_KEY[1]);
baos.write(Registry.MAGIC_RAW_DH_PRIVATE_KEY[2]);
baos.write(Registry.MAGIC_RAW_DH_PRIVATE_KEY[3]);
-
// version
baos.write(0x01);
-
// q
byte[] buffer = dhKey.getQ().toByteArray();
int length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// p
buffer = dhKey.getParams().getP().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// g
buffer = dhKey.getParams().getG().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// x
buffer = dhKey.getX().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -320,51 +288,49 @@ public class DHKeyPairRawCodec implements IKeyPairCodec
|| k[1] != Registry.MAGIC_RAW_DH_PRIVATE_KEY[1]
|| k[2] != Registry.MAGIC_RAW_DH_PRIVATE_KEY[2]
|| k[3] != Registry.MAGIC_RAW_DH_PRIVATE_KEY[3])
- {
- throw new IllegalArgumentException("magic");
- }
-
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
+ throw new IllegalArgumentException("version");
int i = 5;
int l;
byte[] buffer;
-
// q
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger q = new BigInteger(1, buffer);
-
// p
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger p = new BigInteger(1, buffer);
-
// g
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger g = new BigInteger(1, buffer);
-
// x
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger x = new BigInteger(1, buffer);
-
return new GnuDHPrivateKey(q, p, g, x);
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/dh/DHKeyPairX509Codec.java b/libjava/classpath/gnu/javax/crypto/key/dh/DHKeyPairX509Codec.java
index 7e8688b..5da396a 100644
--- a/libjava/classpath/gnu/javax/crypto/key/dh/DHKeyPairX509Codec.java
+++ b/libjava/classpath/gnu/javax/crypto/key/dh/DHKeyPairX509Codec.java
@@ -97,6 +97,13 @@ public class DHKeyPairX509Codec
* q
,toByteArray()
method on the DH parameter q
,p
in internet order,toByteArray()
method on the DH parameter p
,g
,toByteArray()
method on the DH parameter g
,x
,toByteArray()
method on the DH parameter x
,q
,toByteArray()
method on the DH parameter q
,
+ * p
in internet order,toByteArray()
method on the DH parameter p
,
+ * g
,toByteArray()
method on the DH parameter g
,
+ * x
,toByteArray()
method on the DH parameter x
,
+ *
* DHPublicKey ::= INTEGER -- public key, y = g^x mod p
*
+ * null
for the q
+ * parameter. RFC-2631 DOES NOT allow for an optional value for that
+ * parameter, hence we replace such null values with 0
, and do
+ * the reverse in the corresponding decode method.
*
* @param key the {@link PublicKey} instance to encode. MUST be an instance of
* {@link GnuDHPublicKey}.
@@ -117,6 +124,8 @@ public class DHKeyPairX509Codec
BigInteger p = dhKey.getParams().getP();
BigInteger g = dhKey.getParams().getG();
BigInteger q = dhKey.getQ();
+ if (q == null)
+ q = BigInteger.ZERO;
BigInteger y = dhKey.getY();
DERValue derP = new DERValue(DER.INTEGER, p);
@@ -212,6 +221,8 @@ public class DHKeyPairX509Codec
val = der.read();
DerUtil.checkIsBigInteger(val, "Wrong Q field");
q = (BigInteger) val.getValue();
+ if (q.compareTo(BigInteger.ZERO) == 0)
+ q = null;
val = der.read();
if (! (val.getValue() instanceof BitString))
diff --git a/libjava/classpath/gnu/javax/crypto/key/dh/DiffieHellmanKeyAgreement.java b/libjava/classpath/gnu/javax/crypto/key/dh/DiffieHellmanKeyAgreement.java
index 5b1caa7..2443950 100644
--- a/libjava/classpath/gnu/javax/crypto/key/dh/DiffieHellmanKeyAgreement.java
+++ b/libjava/classpath/gnu/javax/crypto/key/dh/DiffieHellmanKeyAgreement.java
@@ -49,78 +49,63 @@ import java.math.BigInteger;
import javax.crypto.interfaces.DHPrivateKey;
/**
- *
- *
- *
- *
- * "In Static-Static mode, both the sender and the recipient have a
- static (and certified) key pair. Since the sender's and recipient's
- keys are therefore the same for each message, ZZ will be the same for
- each message. Thus, partyAInfo MUST be used (and different for each
- message) in order to ensure that different messages use different
- KEKs. Implementations MAY implement Static-Static mode."
+ * "In Static-Static mode, both the sender and the recipient have a
+ * static (and certified) key pair. Since the sender's and recipient's
+ * keys are therefore the same for each message, ZZ will be the same for
+ * each message. Thus, partyAInfo MUST be used (and different for each
+ * message) in order to ensure that different messages use different
+ * KEKs. Implementations MAY implement Static-Static mode."
*
- *
- *
- *
*/
-public abstract class DiffieHellmanKeyAgreement extends BaseKeyAgreementParty
+public abstract class DiffieHellmanKeyAgreement
+ extends BaseKeyAgreementParty
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.dh.ka.prng";
-
- public static final String KA_DIFFIE_HELLMAN_OWNER_PRIVATE_KEY = "gnu.crypto.dh.ka.owner.private.key";
-
+ public static final String KA_DIFFIE_HELLMAN_OWNER_PRIVATE_KEY =
+ "gnu.crypto.dh.ka.owner.private.key";
/** The key agreement party's private key. */
protected DHPrivateKey ownerKey;
-
/** The shared secret key. */
protected BigInteger ZZ;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
protected DiffieHellmanKeyAgreement()
{
super(Registry.DH_KA);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // implementation of common abstract methods in BaseKeyAGreementParty ------
-
protected byte[] engineSharedSecret() throws KeyAgreementException
{
return Util.trim(ZZ);
diff --git a/libjava/classpath/gnu/javax/crypto/key/dh/DiffieHellmanReceiver.java b/libjava/classpath/gnu/javax/crypto/key/dh/DiffieHellmanReceiver.java
index 4a3664d..ab1023a 100644
--- a/libjava/classpath/gnu/javax/crypto/key/dh/DiffieHellmanReceiver.java
+++ b/libjava/classpath/gnu/javax/crypto/key/dh/DiffieHellmanReceiver.java
@@ -51,50 +51,30 @@ import java.util.Map;
import javax.crypto.interfaces.DHPrivateKey;
/**
- *
- * Eric Rescorla.
- * CRC Press, Inc. ISBN 0-8493-8523-7, 1997
- * Menezes, A., van Oorschot, P. and S. Vanstone.
+ * Eric Rescorla.
+ * CRC Press, Inc. ISBN 0-8493-8523-7, 1997
+ * Menezes, A., van Oorschot, P. and S. Vanstone.
- *
- *
- *
- * "In Ephemeral-Static mode, the recipient has a static (and certified)
- * key pair, but the sender generates a new key pair for each message
- * and sends it using the originatorKey production. If the sender's key
- * is freshly generated for each message, the shared secret ZZ will be
- * similarly different for each message and partyAInfo MAY be omitted,
- * since it serves merely to decouple multiple KEKs generated by the
- * same set of pairwise keys. If, however, the same ephemeral sender key
- * is used for multiple messages (e.g. it is cached as a performance
- * optimization) then a separate partyAInfo MUST be used for each
- * message. All implementations of this standard MUST implement
- * Ephemeral-Static mode."
+ * "In Ephemeral-Static mode, the recipient has a static (and certified)
+ * key pair, but the sender generates a new key pair for each message
+ * and sends it using the originatorKey production. If the sender's key
+ * is freshly generated for each message, the shared secret ZZ will be
+ * similarly different for each message and partyAInfo MAY be omitted,
+ * since it serves merely to decouple multiple KEKs generated by the
+ * same set of pairwise keys. If, however, the same ephemeral sender key
+ * is used for multiple messages (e.g. it is cached as a performance
+ * optimization) then a separate partyAInfo MUST be used for each
+ * message. All implementations of this standard MUST implement
+ * Ephemeral-Static mode."
*
- *
- *
- *
*/
-public abstract class ElGamalKeyAgreement extends BaseKeyAgreementParty
+public abstract class ElGamalKeyAgreement
+ extends BaseKeyAgreementParty
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.elgamal.ka.prng";
-
- public static final String KA_ELGAMAL_RECIPIENT_PRIVATE_KEY = "gnu.crypto.elgamal.ka.recipient.private.key";
-
- public static final String KA_ELGAMAL_RECIPIENT_PUBLIC_KEY = "gnu.crypto.elgamal.ka.recipient.public.key";
-
+ public static final String KA_ELGAMAL_RECIPIENT_PRIVATE_KEY =
+ "gnu.crypto.elgamal.ka.recipient.private.key";
+ public static final String KA_ELGAMAL_RECIPIENT_PUBLIC_KEY =
+ "gnu.crypto.elgamal.ka.recipient.public.key";
/** The shared secret key. */
protected BigInteger ZZ;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
protected ElGamalKeyAgreement()
{
super(Registry.ELGAMAL_KA);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // implementation of common abstract methods in BaseKeyAGreementParty ------
-
protected byte[] engineSharedSecret() throws KeyAgreementException
{
return Util.trim(ZZ);
diff --git a/libjava/classpath/gnu/javax/crypto/key/dh/ElGamalReceiver.java b/libjava/classpath/gnu/javax/crypto/key/dh/ElGamalReceiver.java
index 24776cb..bf9b4fb 100644
--- a/libjava/classpath/gnu/javax/crypto/key/dh/ElGamalReceiver.java
+++ b/libjava/classpath/gnu/javax/crypto/key/dh/ElGamalReceiver.java
@@ -49,33 +49,19 @@ import java.util.Map;
import javax.crypto.interfaces.DHPrivateKey;
/**
- *
- * Eric Rescorla.
- * CRC Press, Inc. ISBN 0-8493-8523-7, 1997
- * Menezes, A., van Oorschot, P. and S. Vanstone.
+ * Eric Rescorla.
+ * CRC Press, Inc. ISBN 0-8493-8523-7, 1997
+ * Menezes, A., van Oorschot, P. and S. Vanstone.p
, and g
.p
, and g
.
+ * getEncoded()
methods of each of the private and
- * public keys.getEncoded()
methods of each of the private and
+ * public keys.
+ *
- *
*/
-public abstract class GnuDHKey implements Key, DHKey
+public abstract class GnuDHKey
+ implements Key, DHKey
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** The public prime q. A prime divisor of p-1. */
protected BigInteger q;
-
/** The public prime p. */
protected BigInteger p;
-
/** The generator g. */
protected BigInteger g;
-
/**
- * Identifier of the default encoding format to use when externalizing the
- * key material.
+ * Identifier of the default encoding format to use when externalizing the key
+ * material.
*/
protected final int defaultFormat;
-
- // Constructor(s)
- // -------------------------------------------------------------------------
+ /** String representation of this key. Cached for speed. */
+ private transient String str;
/**
* Trivial protected constructor.
@@ -109,28 +104,13 @@ public abstract class GnuDHKey implements Key, DHKey
this.g = g;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // javax.crypto.interfaces.DHKey interface implementation ------------------
-
public DHParameterSpec getParams()
{
if (q == null)
- {
- return new DHParameterSpec(p, g);
- }
- else
- {
- return new DHParameterSpec(p, g, q.bitLength());
- }
+ return new DHParameterSpec(p, g);
+ return new DHParameterSpec(p, g, q.bitLength());
}
- // java.security.Key interface implementation ------------------------------
-
public String getAlgorithm()
{
return Registry.DH_KPG;
@@ -147,38 +127,48 @@ public abstract class GnuDHKey implements Key, DHKey
return FormatUtil.getEncodingShortName(defaultFormat);
}
- // Other instance methods --------------------------------------------------
-
public BigInteger getQ()
{
return q;
}
/**
- *
- * Eric Rescorla.
+ * Eric Rescorla.true
if the designated object is an instance of
- * {@link DHKey} and has the same Diffie-Hellman parameter values as this
- * one.true
if the designated object is an instance of
+ * {@link DHKey} and has the same Diffie-Hellman parameter values as this one.
+ *
* @param obj the other non-null DH key to compare to.
- * @return true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(Object obj)
{
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof DHKey))
- {
- return false;
- }
+ return false;
+ if (! (obj instanceof DHKey))
+ return false;
DHKey that = (DHKey) obj;
return p.equals(that.getParams().getP())
&& g.equals(that.getParams().getG());
}
- // abstract methods to be implemented by subclasses ------------------------
+ public String toString()
+ {
+ if (str == null)
+ {
+ String ls = (String) AccessController.doPrivileged
+ (new GetPropertyAction("line.separator"));
+ StringBuilder sb = new StringBuilder(ls)
+ .append("defaultFormat=").append(defaultFormat).append(",").append(ls);
+ if (q == null)
+ sb.append("q=null,");
+ else
+ sb.append("q=0x").append(q.toString(16)).append(",");
+ sb.append(ls).append("p=0x").append(p.toString(16)).append(",").append(ls)
+ .append("g=0x").append(g.toString(16));
+ str = sb.toString();
+ }
+ return str;
+ }
public abstract byte[] getEncoded(int format);
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java b/libjava/classpath/gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java
index 5626a29..13cfd90 100644
--- a/libjava/classpath/gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java
+++ b/libjava/classpath/gnu/javax/crypto/key/dh/GnuDHKeyPairGenerator.java
@@ -38,132 +38,84 @@ exception statement from your version. */
package gnu.javax.crypto.key.dh;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.hash.Sha160;
import gnu.java.security.key.IKeyPairGenerator;
import gnu.java.security.util.PRNG;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.Map;
+import java.util.logging.Logger;
import javax.crypto.spec.DHGenParameterSpec;
import javax.crypto.spec.DHParameterSpec;
/**
- *
- *
*/
-public class GnuDHKeyPairGenerator implements IKeyPairGenerator
+public class GnuDHKeyPairGenerator
+ implements IKeyPairGenerator
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "dh";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(GnuDHKeyPairGenerator.class.getName());
/**
* Property name of an optional {@link SecureRandom} instance to use. The
* default is to use a classloader singleton from {@link PRNG}.
*/
public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.dh.prng";
-
/**
* Property name of an optional {@link DHGenParameterSpec} or
* {@link DHParameterSpec} instance to use for this generator.
*/
public static final String DH_PARAMETERS = "gnu.crypto.dh.params";
-
/** Property name of the size in bits (Integer) of the public prime (p). */
public static final String PRIME_SIZE = "gnu.crypto.dh.L";
-
/** Property name of the size in bits (Integer) of the private exponent (x). */
public static final String EXPONENT_SIZE = "gnu.crypto.dh.m";
-
/**
* Property name of the preferred encoding format to use when externalizing
* generated instance of key-pairs from this generator. The property is taken
* to be an {@link Integer} that encapsulates an encoding format identifier.
*/
public static final String PREFERRED_ENCODING_FORMAT = "gnu.crypto.dh.encoding";
-
/** Default value for the size in bits of the public prime (p). */
- // private static final int DEFAULT_PRIME_SIZE = 1024;
public static final int DEFAULT_PRIME_SIZE = 512;
-
/** Default value for the size in bits of the private exponent (x). */
public static final int DEFAULT_EXPONENT_SIZE = 160;
-
/** Default encoding format to use when none was specified. */
private static final int DEFAULT_ENCODING_FORMAT = Registry.RAW_ENCODING_ID;
-
/** The SHA instance to use. */
private Sha160 sha = new Sha160();
-
/** The optional {@link SecureRandom} instance to use. */
private SecureRandom rnd = null;
-
/** The desired size in bits of the public prime (p). */
private int l;
-
/** The desired size in bits of the private exponent (x). */
private int m;
-
private BigInteger seed;
-
private BigInteger counter;
-
private BigInteger q;
-
private BigInteger p;
-
private BigInteger j;
-
private BigInteger g;
-
/** Our default source of randomness. */
private PRNG prng = null;
-
/** Preferred encoding format of generated keys. */
private int preferredFormat;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // gnu.crypto.keys.IKeyPairGenerator interface implementation ---------------
-
public String name()
{
return Registry.DH_KPG;
@@ -173,11 +125,9 @@ public class GnuDHKeyPairGenerator implements IKeyPairGenerator
{
// do we have a SecureRandom, or should we use our own?
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
-
// are we given a set of Diffie-Hellman generation parameters or we shall
// use our own?
Object params = attributes.get(DH_PARAMETERS);
-
// find out the desired sizes
if (params instanceof DHGenParameterSpec)
{
@@ -195,7 +145,6 @@ public class GnuDHKeyPairGenerator implements IKeyPairGenerator
g = jceSpec.getG();
l = p.bitLength();
m = jceSpec.getL();
-
// If no exponent size was given, generate an exponent as
// large as the prime.
if (m == 0)
@@ -208,21 +157,12 @@ public class GnuDHKeyPairGenerator implements IKeyPairGenerator
bi = (Integer) attributes.get(EXPONENT_SIZE);
m = (bi == null ? DEFAULT_EXPONENT_SIZE : bi.intValue());
}
-
- // if ((L % 256) != 0 || L < 1024) {
if ((l % 256) != 0 || l < DEFAULT_PRIME_SIZE)
- {
- throw new IllegalArgumentException("invalid modulus size");
- }
+ throw new IllegalArgumentException("invalid modulus size");
if ((m % 8) != 0 || m < DEFAULT_EXPONENT_SIZE)
- {
- throw new IllegalArgumentException("invalid exponent size");
- }
+ throw new IllegalArgumentException("invalid exponent size");
if (m > l)
- {
- throw new IllegalArgumentException("exponent size > modulus size");
- }
-
+ throw new IllegalArgumentException("exponent size > modulus size");
// what is the preferred encoding format
Integer formatID = (Integer) attributes.get(PREFERRED_ENCODING_FORMAT);
preferredFormat = formatID == null ? DEFAULT_ENCODING_FORMAT
@@ -240,22 +180,20 @@ public class GnuDHKeyPairGenerator implements IKeyPairGenerator
p = params[RFC2631.DH_PARAMS_P];
j = params[RFC2631.DH_PARAMS_J];
g = params[RFC2631.DH_PARAMS_G];
- if (DEBUG && debuglevel > 0)
+ if (Configuration.DEBUG)
{
- debug("seed: 0x" + seed.toString(16));
- debug("counter: " + counter.intValue());
- debug("q: 0x" + q.toString(16));
- debug("p: 0x" + p.toString(16));
- debug("j: 0x" + j.toString(16));
- debug("g: 0x" + g.toString(16));
+ log.fine("seed: 0x" + seed.toString(16));
+ log.fine("counter: " + counter.intValue());
+ log.fine("q: 0x" + q.toString(16));
+ log.fine("p: 0x" + p.toString(16));
+ log.fine("j: 0x" + j.toString(16));
+ log.fine("g: 0x" + g.toString(16));
}
}
-
// generate a private number x of length m such as: 1 < x < q - 1
BigInteger q_minus_1 = null;
if (q != null)
q_minus_1 = q.subtract(BigInteger.ONE);
-
// We already check if m is modulo 8 in `setup.' This could just
// be m >>> 3.
byte[] mag = new byte[(m + 7) / 8];
@@ -266,31 +204,23 @@ public class GnuDHKeyPairGenerator implements IKeyPairGenerator
x = new BigInteger(1, mag);
if (x.bitLength() == m && x.compareTo(BigInteger.ONE) > 0
&& (q_minus_1 == null || x.compareTo(q_minus_1) < 0))
- {
- break;
- }
+ break;
}
BigInteger y = g.modPow(x, p);
-
PrivateKey secK = new GnuDHPrivateKey(preferredFormat, q, p, g, x);
PublicKey pubK = new GnuDHPublicKey(preferredFormat, q, p, g, y);
-
return new KeyPair(pubK, secK);
}
- // other methods -----------------------------------------------------------
-
/**
- *
- * Eric Rescorla.
+ * Eric Rescorla.
- *
*/
-public class GnuDHPrivateKey extends GnuDHKey implements DHPrivateKey
+public class GnuDHPrivateKey
+ extends GnuDHKey
+ implements DHPrivateKey
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** The private exponent. */
private final BigInteger x;
-
- // Constructor(s)
- // -------------------------------------------------------------------------
+ /** String representation of this key. Cached for speed. */
+ private transient String str;
/**
* Convenience constructor. Calls the constructor with five arguments passing
@@ -92,31 +92,27 @@ public class GnuDHPrivateKey extends GnuDHKey implements DHPrivateKey
* @param g the generator of the group.
* @param x the private value x.
*/
- public GnuDHPrivateKey(int preferredFormat,
- BigInteger q, BigInteger p, BigInteger g, BigInteger x)
+ public GnuDHPrivateKey(int preferredFormat, BigInteger q, BigInteger p,
+ BigInteger g, BigInteger x)
{
super(preferredFormat == Registry.ASN1_ENCODING_ID ? Registry.PKCS8_ENCODING_ID
: preferredFormat,
q, p, g);
-
this.x = x;
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
- *
- * Eric Rescorla.
+ * Eric Rescorla.encodePrivateKey()
+ * A class method that takes the output of the encodePrivateKey()
* method of a DH keypair codec object (an instance implementing
* {@link IKeyPairCodec} for DH keys, and re-constructs an instance of this
- * object.k
, to represent a valid encoding of an instance of
- * this object.
- * @exception IllegalArgumentException if the byte sequence does not
- * represent a valid encoding of an instance of this object.
+ * @exception ArrayIndexOutOfBoundsException if there is not enough bytes, in
+ * k
, to represent a valid encoding of an
+ * instance of this object.
+ * @exception IllegalArgumentException if the byte sequence does not represent
+ * a valid encoding of an instance of this object.
*/
public static GnuDHPrivateKey valueOf(byte[] k)
{
@@ -129,32 +125,24 @@ public class GnuDHPrivateKey extends GnuDHKey implements DHPrivateKey
catch (IllegalArgumentException ignored)
{
}
-
// try PKCS#8 codec
return (GnuDHPrivateKey) new DHKeyPairPKCS8Codec().decodePrivateKey(k);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
- // javax.crypto.interfaces.DHPrivateKey interface implementation -----------
-
public BigInteger getX()
{
return x;
}
- // other methods -----------------------------------------------------------
-
/**
- *
- *
*/
-public class GnuDHPublicKey extends GnuDHKey implements DHPublicKey
+public class GnuDHPublicKey
+ extends GnuDHKey
+ implements DHPublicKey
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private BigInteger y;
-
- // Constructor(s)
- // -------------------------------------------------------------------------
+ /** String representation of this key. Cached for speed. */
+ private transient String str;
/**
* Convenience constructor. Calls the constructor with five arguments passing
@@ -91,31 +90,27 @@ public class GnuDHPublicKey extends GnuDHKey implements DHPublicKey
* @param g the generator of the group.
* @param y the public value y.
*/
- public GnuDHPublicKey(int preferredFormat,
- BigInteger q, BigInteger p, BigInteger g, BigInteger y)
+ public GnuDHPublicKey(int preferredFormat, BigInteger q, BigInteger p,
+ BigInteger g, BigInteger y)
{
super(preferredFormat == Registry.ASN1_ENCODING_ID ? Registry.X509_ENCODING_ID
: preferredFormat,
q, p, g);
-
this.y = y;
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
- *
- * Eric Rescorla.
+ * Eric Rescorla.encodePublicKey()
+ * A class method that takes the output of the encodePublicKey()
* method of a DH keypair codec object (an instance implementing
* {@link IKeyPairCodec} for DSS keys, and re-constructs an instance of this
- * object.k
, to represent a valid encoding of an instance of this
* object.
- * @exception IllegalArgumentException if the byte sequence does not
- * represent a valid encoding of an instance of this object.
+ *
+ * @param k the contents of a previously encoded instance of this object.
+ * @exception ArrayIndexOutOfBoundsException if there is not enough bytes, in
+ * k
, to represent a valid encoding of an
+ * instance of this object.
+ * @exception IllegalArgumentException if the byte sequence does not represent
+ * a valid encoding of an instance of this object.
*/
public static GnuDHPublicKey valueOf(byte[] k)
{
@@ -128,30 +123,22 @@ public class GnuDHPublicKey extends GnuDHKey implements DHPublicKey
catch (IllegalArgumentException ignored)
{
}
-
// try X.509 codec
return (GnuDHPublicKey) new DHKeyPairX509Codec().decodePublicKey(k);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
- // javax.crypto.interfaces.DHPublicKey interface implementation ------------
-
public BigInteger getY()
{
return y;
}
- // other methods -----------------------------------------------------------
-
/**
- *
- *
*/
public class RFC2631
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final int DH_PARAMS_SEED = 0;
-
public static final int DH_PARAMS_COUNTER = 1;
-
public static final int DH_PARAMS_Q = 2;
-
public static final int DH_PARAMS_P = 3;
-
public static final int DH_PARAMS_J = 4;
-
public static final int DH_PARAMS_G = 5;
-
private static final BigInteger TWO = BigInteger.valueOf(2L);
-
/** The SHA instance to use. */
private Sha160 sha = new Sha160();
-
/** Length of private modulus and of q. */
private int m;
-
/** Length of public modulus p. */
private int L;
-
/** The optional {@link SecureRandom} instance to use. */
private SecureRandom rnd = null;
-
/** Our default source of randomness. */
private PRNG prng = null;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public RFC2631(int m, int L, SecureRandom rnd)
{
super();
@@ -103,12 +84,6 @@ public class RFC2631
this.rnd = rnd;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
public BigInteger[] generateParameters()
{
int i, j, counter;
@@ -127,15 +102,16 @@ public class RFC2631
{
step4: while (true)
{
- // 4. Select an arbitrary bit string SEED such that length of SEED >= m
+ // 4. Select an arbitrary bit string SEED such that length of
+ // SEED >= m
nextRandomBytes(seedBytes);
SEED = new BigInteger(1, seedBytes).setBit(m - 1).setBit(0);
// 5. Set U = 0
U = BigInteger.ZERO;
// 6. For i = 0 to m' - 1
- // U = U + (SHA1[SEED + i] XOR SHA1[(SEED + m' + i)) * 2^(160 * i)
- // Note that for m=160, this reduces to the algorithm of [FIPS-186]
- // U = SHA1[SEED] XOR SHA1[(SEED+1) mod 2^160 ].
+ // U = U + (SHA1[SEED + i] XOR SHA1[(SEED + m' + i)) * 2^(160 * i)
+ // Note that for m=160, this reduces to the algorithm of FIPS-186
+ // U = SHA1[SEED] XOR SHA1[(SEED+1) mod 2^160 ].
for (i = 0; i < m_; i++)
{
u1 = SEED.add(BigInteger.valueOf(i)).toByteArray();
@@ -145,31 +121,27 @@ public class RFC2631
sha.update(u2, 0, u2.length);
u2 = sha.digest();
for (j = 0; j < u1.length; j++)
- {
- u1[j] ^= u2[j];
- }
+ u1[j] ^= u2[j];
U = U.add(new BigInteger(1, u1).multiply(TWO.pow(160 * i)));
}
// 5. Form q from U by computing U mod (2^m) and setting the most
- // significant bit (the 2^(m-1) bit) and the least significant bit to
- // 1. In terms of boolean operations, q = U OR 2^(m-1) OR 1. Note
- // that 2^(m-1) < q < 2^m
+ // significant bit (the 2^(m-1) bit) and the least significant
+ // bit to 1. In terms of boolean operations, q = U OR 2^(m-1) OR
+ // 1. Note that 2^(m-1) < q < 2^m
q = U.setBit(m - 1).setBit(0);
// 6. Use a robust primality algorithm to test whether q is prime.
// 7. If q is not prime then go to 4.
- if (Prime2.isProbablePrime(q))
- {
- break step4;
- }
+ if (q.isProbablePrime(80))
+ break step4;
}
// 8. Let counter = 0
counter = 0;
step9: while (true)
{
// 9. Set R = seed + 2*m' + (L' * counter)
- R = SEED.add(BigInteger.valueOf(2 * m_)).add(
- BigInteger.valueOf(L_
- * counter));
+ R = SEED
+ .add(BigInteger.valueOf(2 * m_))
+ .add(BigInteger.valueOf(L_ * counter));
// 10. Set V = 0
V = BigInteger.ZERO;
// 12. For i = 0 to L'-1 do: V = V + SHA1(R + i) * 2^(160 * i)
@@ -187,10 +159,10 @@ public class RFC2631
X = W.setBit(L - 1);
// 15. Set p = X - (X mod (2*q)) + 1
p = X.add(BigInteger.ONE).subtract(X.mod(TWO.multiply(q)));
- // 16. If p > 2^(L-1) use a robust primality test to test whether p is
- // prime. Else go to 18.
- //17. If p is prime output p, q, seed, counter and stop.
- if (Prime2.isProbablePrime(p))
+ // 16. If p > 2^(L-1) use a robust primality test to test whether p
+ // is prime. Else go to 18.
+ // 17. If p is prime output p, q, seed, counter and stop.
+ if (p.isProbablePrime(80))
{
break algorithm;
}
@@ -199,12 +171,9 @@ public class RFC2631
// 19. If counter < (4096 * N) then go to 8.
// 20. Output "failure"
if (counter >= 4096 * N_)
- {
- continue algorithm;
- }
+ continue algorithm;
}
}
-
// compute g. from FIPS-186, Appendix 4:
// 1. Generate p and q as specified in Appendix 2.
// 2. Let e = (p - 1) / q
@@ -219,28 +188,21 @@ public class RFC2631
// 4. Set g = h**e mod p
g = h.modPow(e, p);
// 5. If g = 1, go to step 3
- if (!g.equals(BigInteger.ONE))
- {
- break;
- }
+ if (! g.equals(BigInteger.ONE))
+ break;
}
-
return new BigInteger[] { SEED, BigInteger.valueOf(counter), q, p, e, g };
}
- // helper methods ----------------------------------------------------------
-
/**
- *
- * Eric Rescorla.
+ * Eric Rescorla.
- *
*/
-public class SRP6Host extends SRP6KeyAgreement
+public class SRP6Host
+ extends SRP6KeyAgreement
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** The user's ephemeral key pair. */
private KeyPair hostKeyPair;
/** The SRP password database. */
private SRPAuthInfoProvider passwordDB;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // implementation of abstract methods in base class ------------------------
-
protected void engineInit(final Map attributes) throws KeyAgreementException
{
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
N = (BigInteger) attributes.get(SHARED_MODULUS);
if (N == null)
- {
- throw new KeyAgreementException("missing shared modulus");
- }
+ throw new KeyAgreementException("missing shared modulus");
g = (BigInteger) attributes.get(GENERATOR);
if (g == null)
- {
- throw new KeyAgreementException("missing generator");
- }
-
+ throw new KeyAgreementException("missing generator");
final String md = (String) attributes.get(HASH_FUNCTION);
- if (md == null || "".equals(md.trim()))
- {
- throw new KeyAgreementException("missing hash function");
- }
+ if (md == null || md.trim().length() == 0)
+ throw new KeyAgreementException("missing hash function");
srp = SRP.instance(md);
-
passwordDB = (SRPAuthInfoProvider) attributes.get(HOST_PASSWORD_DB);
if (passwordDB == null)
- {
- throw new KeyAgreementException("missing SRP password database");
- }
+ throw new KeyAgreementException("missing SRP password database");
}
protected OutgoingMessage engineProcessMessage(final IncomingMessage in)
@@ -135,14 +111,11 @@ public class SRP6Host extends SRP6KeyAgreement
super.engineReset();
}
- // own methods -------------------------------------------------------------
-
private OutgoingMessage computeSharedSecret(final IncomingMessage in)
throws KeyAgreementException
{
final String I = in.readString();
final BigInteger A = in.readMPI();
-
// get s and v for user identified by I
// ----------------------------------------------------------------------
final Map credentials;
@@ -157,56 +130,31 @@ public class SRP6Host extends SRP6KeyAgreement
{
throw new KeyAgreementException("computeSharedSecret()", x);
}
-
final BigInteger s = new BigInteger(
- 1,
- Util.fromBase64((String) credentials.get(SRPRegistry.SALT_FIELD)));
+ 1,Util.fromBase64((String) credentials.get(SRPRegistry.SALT_FIELD)));
final BigInteger v = new BigInteger(
- 1,
- Util.fromBase64((String) credentials.get(SRPRegistry.USER_VERIFIER_FIELD)));
-
- // Map configuration = null;
- // try {
- // String mode = (String) credentials.get(SRPRegistry.CONFIG_NDX_FIELD);
- // configuration = passwordDB.getConfiguration(mode);
- // } catch (IOException x) {
- // throw new KeyAgreementException("computeSharedSecret()", x);
- // }
- //
- // BigInteger N = new BigInteger(1, Util.fromBase64(
- // (String) configuration.get(SRPRegistry.SHARED_MODULUS)));
- // BigInteger g = new BigInteger(1, Util.fromBase64(
- // (String) configuration.get(SRPRegistry.FIELD_GENERATOR)));
- // ----------------------------------------------------------------------
-
+ 1, Util.fromBase64((String) credentials.get(SRPRegistry.USER_VERIFIER_FIELD)));
final SRPKeyPairGenerator kpg = new SRPKeyPairGenerator();
final Map attributes = new HashMap();
if (rnd != null)
- {
- attributes.put(SRPKeyPairGenerator.SOURCE_OF_RANDOMNESS, rnd);
- }
+ attributes.put(SRPKeyPairGenerator.SOURCE_OF_RANDOMNESS, rnd);
attributes.put(SRPKeyPairGenerator.SHARED_MODULUS, N);
attributes.put(SRPKeyPairGenerator.GENERATOR, g);
attributes.put(SRPKeyPairGenerator.USER_VERIFIER, v);
kpg.setup(attributes);
hostKeyPair = kpg.generate();
-
final BigInteger B = ((SRPPublicKey) hostKeyPair.getPublic()).getY();
final BigInteger u = uValue(A, B); // u = H(A | B)
-
// compute S = (Av^u) ^ b
final BigInteger b = ((SRPPrivateKey) hostKeyPair.getPrivate()).getX();
final BigInteger S = A.multiply(v.modPow(u, N)).modPow(b, N);
-
final byte[] sBytes = Util.trim(S);
final IMessageDigest hash = srp.newDigest();
hash.update(sBytes, 0, sBytes.length);
K = new BigInteger(1, hash.digest());
-
final OutgoingMessage result = new OutgoingMessage();
result.writeMPI(s);
result.writeMPI(B);
-
complete = true;
return result;
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6KeyAgreement.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6KeyAgreement.java
index 63c981d..b426418 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6KeyAgreement.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6KeyAgreement.java
@@ -49,98 +49,72 @@ import gnu.javax.crypto.sasl.srp.SRP;
import java.math.BigInteger;
/**
- *
- * Thomas J. Wu.
+ * Thomas J. Wu.
- * N A large safe prime (N = 2q+1, where q is prime)
- * All arithmetic is done modulo N.
- * g A generator modulo N
- * s User's salt
- * I Username
- * p Cleartext Password
- * H() One-way hash function
- * ^ (Modular) Exponentiation
- * u Random scrambling parameter
- * a,b Secret ephemeral values
- * A,B Public ephemeral values
- * x Private key (derived from p and s)
- * v Password verifier
- *
- * The host stores passwords using the following formula:
- * x = H(s | H(I ":" p)) (s is chosen randomly)
- * v = g^x (computes password verifier)
- *
- * The host then keeps {I, s, v} in its password database.
- *
- * The authentication protocol itself goes as follows:
- * User -> Host: I, A = g^a (identifies self, a = random number)
- * Host -> User: s, B = 3v + g^b (sends salt, b = random number)
- *
- * Both: u = H(A, B)
- *
- * User: x = H(s, p) (user enters password)
- * User: S = (B - 3g^x) ^ (a + ux) (computes session key)
- * User: K = H(S)
- *
- * Host: S = (Av^u) ^ b (computes session key)
- * Host: K = H(S)
+ * N A large safe prime (N = 2q+1, where q is prime)
+ * All arithmetic is done modulo N.
+ * g A generator modulo N
+ * s User's salt
+ * I Username
+ * p Cleartext Password
+ * H() One-way hash function
+ * ˆ (Modular) Exponentiation
+ * u Random scrambling parameter
+ * a,b Secret ephemeral values
+ * A,B Public ephemeral values
+ * x Private key (derived from p and s)
+ * v Password verifier
+ *
+ * The host stores passwords using the following formula:
+ * x = H(s | H(I ":" p)) (s is chosen randomly)
+ * v = gˆx (computes password verifier)
+ *
+ * The host then keeps {I, s, v} in its password database.
+ *
+ * The authentication protocol itself goes as follows:
+ * User -> Host: I, A = gˆa (identifies self, a = random number)
+ * Host -> User: s, B = 3v + gˆb (sends salt, b = random number)
+ *
+ * Both: u = H(A, B)
+ *
+ * User: x = H(s, p) (user enters password)
+ * User: S = (B - 3gˆx) ˆ (a + ux) (computes session key)
+ * User: K = H(S)
+ *
+ * Host: S = (Avˆu) ˆ b (computes session key)
+ * Host: K = H(S)
*
- *
- *
- *
*/
-public abstract class SRP6KeyAgreement extends BaseKeyAgreementParty
+public abstract class SRP6KeyAgreement
+ extends BaseKeyAgreementParty
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.srp6.ka.prng";
-
public static final String SHARED_MODULUS = "gnu.crypto.srp6.ka.N";
-
public static final String GENERATOR = "gnu.crypto.srp6.ka.g";
-
public static final String HASH_FUNCTION = "gnu.crypto.srp6.ka.H";
-
public static final String USER_IDENTITY = "gnu.crypto.srp6.ka.I";
-
public static final String USER_PASSWORD = "gnu.crypto.srp6.ka.p";
-
public static final String HOST_PASSWORD_DB = "gnu.crypto.srp6.ka.password.db";
-
protected static final BigInteger THREE = BigInteger.valueOf(3L);
-
protected SRP srp;
-
protected BigInteger N;
-
protected BigInteger g;
-
/** The shared secret key. */
protected BigInteger K;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
protected SRP6KeyAgreement()
{
super(Registry.SRP6_KA);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // implementation of common abstract methods in BaseKeyAGreementParty ------
-
protected byte[] engineSharedSecret() throws KeyAgreementException
{
return Util.trim(K);
@@ -148,25 +122,20 @@ public abstract class SRP6KeyAgreement extends BaseKeyAgreementParty
protected void engineReset()
{
- // mda = null;
srp = null;
N = null;
g = null;
K = null;
}
- // helper methods ----------------------------------------------------------
-
protected BigInteger uValue(final BigInteger A, final BigInteger B)
{
- // IMessageDigest hash = (IMessageDigest) mda.clone();
final IMessageDigest hash = srp.newDigest();
byte[] b;
b = Util.trim(A);
hash.update(b, 0, b.length);
b = Util.trim(B);
hash.update(b, 0, b.length);
-
return new BigInteger(1, hash.digest());
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6SaslClient.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6SaslClient.java
index ef460b1..f5969f0 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6SaslClient.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6SaslClient.java
@@ -48,54 +48,43 @@ import gnu.javax.crypto.key.OutgoingMessage;
import java.math.BigInteger;
/**
- *
- * Thomas J. Wu.
+ * Thomas J. Wu.
- * C -> S: I (identifies self)
- * S -> C: N, g, s, B = 3v + g^b (sends salt, b = random number)
- * C -> S: A = g^a (a = random number)
+ * C -> S: I (identifies self)
+ * S -> C: N, g, s, B = 3v + gˆb (sends salt, b = random number)
+ * C -> S: A = gˆa (a = random number)
*
- *
- *
- *
*/
-public class SRP6SaslClient extends SRP6TLSClient
+public class SRP6SaslClient
+ extends SRP6TLSClient
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
protected OutgoingMessage computeSharedSecret(final IncomingMessage in)
throws KeyAgreementException
{
final OutgoingMessage result = super.computeSharedSecret(in);
-
final byte[] sBytes = Util.trim(K);
final IMessageDigest hash = srp.newDigest();
hash.update(sBytes, 0, sBytes.length);
K = new BigInteger(1, hash.digest());
-
return result;
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6SaslServer.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6SaslServer.java
index 5e75996..7e68c99 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6SaslServer.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6SaslServer.java
@@ -48,54 +48,43 @@ import gnu.javax.crypto.key.OutgoingMessage;
import java.math.BigInteger;
/**
- *
- * K. Burdis, R. Naffah.
- * Thomas J. Wu.
+ * K. Burdis, R. Naffah.
+ * Thomas J. Wu.
- * C -> S: I (identifies self)
- * S -> C: N, g, s, B = 3v + g^b (sends salt, b = random number)
- * C -> S: A = g^a (a = random number)
+ * C -> S: I (identifies self)
+ * S -> C: N, g, s, B = 3v + gˆb (sends salt, b = random number)
+ * C -> S: A = gˆa (a = random number)
*
- *
- *
- *
*/
-public class SRP6SaslServer extends SRP6TLSServer
+public class SRP6SaslServer
+ extends SRP6TLSServer
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
protected OutgoingMessage computeSharedSecret(final IncomingMessage in)
throws KeyAgreementException
{
super.computeSharedSecret(in);
-
final byte[] sBytes = Util.trim(K);
final IMessageDigest hash = srp.newDigest();
hash.update(sBytes, 0, sBytes.length);
K = new BigInteger(1, hash.digest());
-
return null;
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6TLSClient.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6TLSClient.java
index 5474a1e..af0be02 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6TLSClient.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6TLSClient.java
@@ -51,62 +51,38 @@ import java.util.HashMap;
import java.util.Map;
/**
- *
- * K. Burdis, R. Naffah.
- * Thomas J. Wu.
+ * K. Burdis, R. Naffah.
+ * Thomas J. Wu.S
and not
- * H(S)
.H(S)
.
*/
-public class SRP6TLSClient extends SRP6KeyAgreement
+public class SRP6TLSClient
+ extends SRP6KeyAgreement
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** The user's identity. */
private String I;
-
/** The user's cleartext password. */
private byte[] p;
-
/** The user's ephemeral key pair. */
private KeyPair userKeyPair;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // implementation of abstract methods in base class ------------------------
-
protected void engineInit(final Map attributes) throws KeyAgreementException
{
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
-
final String md = (String) attributes.get(HASH_FUNCTION);
- if (md == null || "".equals(md.trim()))
- {
- throw new KeyAgreementException("missing hash function");
- }
+ if (md == null || md.trim().length() == 0)
+ throw new KeyAgreementException("missing hash function");
srp = SRP.instance(md);
-
I = (String) attributes.get(USER_IDENTITY);
if (I == null)
- {
- throw new KeyAgreementException("missing user identity");
- }
+ throw new KeyAgreementException("missing user identity");
p = (byte[]) attributes.get(USER_PASSWORD);
if (p == null)
- {
- throw new KeyAgreementException("missing user password");
- }
+ throw new KeyAgreementException("missing user password");
}
protected OutgoingMessage engineProcessMessage(final IncomingMessage in)
@@ -131,14 +107,11 @@ public class SRP6TLSClient extends SRP6KeyAgreement
super.engineReset();
}
- // own methods -------------------------------------------------------------
-
private OutgoingMessage sendIdentity(final IncomingMessage in)
throws KeyAgreementException
{
final OutgoingMessage result = new OutgoingMessage();
result.writeString(I);
-
return result;
}
@@ -149,19 +122,15 @@ public class SRP6TLSClient extends SRP6KeyAgreement
g = in.readMPI();
final BigInteger s = in.readMPI();
final BigInteger B = in.readMPI();
-
// generate an ephemeral keypair
final SRPKeyPairGenerator kpg = new SRPKeyPairGenerator();
final Map attributes = new HashMap();
if (rnd != null)
- {
- attributes.put(SRPKeyPairGenerator.SOURCE_OF_RANDOMNESS, rnd);
- }
+ attributes.put(SRPKeyPairGenerator.SOURCE_OF_RANDOMNESS, rnd);
attributes.put(SRPKeyPairGenerator.SHARED_MODULUS, N);
attributes.put(SRPKeyPairGenerator.GENERATOR, g);
kpg.setup(attributes);
userKeyPair = kpg.generate();
-
final BigInteger A = ((SRPPublicKey) userKeyPair.getPublic()).getY();
final BigInteger u = uValue(A, B); // u = H(A | B)
final BigInteger x;
@@ -173,18 +142,13 @@ public class SRP6TLSClient extends SRP6KeyAgreement
{
throw new KeyAgreementException("computeSharedSecret()", e);
}
-
// compute S = (B - 3g^x) ^ (a + ux)
final BigInteger a = ((SRPPrivateKey) userKeyPair.getPrivate()).getX();
- final BigInteger S = B.subtract(THREE.multiply(g.modPow(x, N))).modPow(
- a.add(u.multiply(x)),
- N);
-
+ final BigInteger S = B.subtract(THREE.multiply(g.modPow(x, N)))
+ .modPow(a.add(u.multiply(x)), N);
K = S;
-
final OutgoingMessage result = new OutgoingMessage();
result.writeMPI(A);
-
complete = true;
return result;
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6TLSServer.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6TLSServer.java
index ecbe36f..f91cffd 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6TLSServer.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6TLSServer.java
@@ -55,54 +55,33 @@ import java.util.HashMap;
import java.util.Map;
/**
- * S
and not
- * H(S)
.H(S)
.
*/
-public class SRP6TLSServer extends SRP6KeyAgreement
+public class SRP6TLSServer
+ extends SRP6KeyAgreement
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** The user's ephemeral key pair. */
private KeyPair hostKeyPair;
-
/** The SRP password database. */
private SRPAuthInfoProvider passwordDB;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // implementation of abstract methods in base class ------------------------
-
protected void engineInit(final Map attributes) throws KeyAgreementException
{
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
-
final String md = (String) attributes.get(HASH_FUNCTION);
- if (md == null || "".equals(md.trim()))
- {
- throw new KeyAgreementException("missing hash function");
- }
+ if (md == null || md.trim().length() == 0)
+ throw new KeyAgreementException("missing hash function");
srp = SRP.instance(md);
-
passwordDB = (SRPAuthInfoProvider) attributes.get(HOST_PASSWORD_DB);
if (passwordDB == null)
- {
- throw new KeyAgreementException("missing SRP password database");
- }
+ throw new KeyAgreementException("missing SRP password database");
}
protected OutgoingMessage engineProcessMessage(final IncomingMessage in)
@@ -125,13 +104,10 @@ public class SRP6TLSServer extends SRP6KeyAgreement
super.engineReset();
}
- // own methods -------------------------------------------------------------
-
private OutgoingMessage sendParameters(final IncomingMessage in)
throws KeyAgreementException
{
final String I = in.readString();
-
// get s and v for user identified by I
// ----------------------------------------------------------------------
final Map credentials;
@@ -148,12 +124,9 @@ public class SRP6TLSServer extends SRP6KeyAgreement
}
final BigInteger s = new BigInteger(
- 1,
- Util.fromBase64((String) credentials.get(SRPRegistry.SALT_FIELD)));
+ 1, Util.fromBase64((String) credentials.get(SRPRegistry.SALT_FIELD)));
final BigInteger v = new BigInteger(
- 1,
- Util.fromBase64((String) credentials.get(SRPRegistry.USER_VERIFIER_FIELD)));
-
+ 1, Util.fromBase64((String) credentials.get(SRPRegistry.USER_VERIFIER_FIELD)));
final Map configuration;
try
{
@@ -164,36 +137,26 @@ public class SRP6TLSServer extends SRP6KeyAgreement
{
throw new KeyAgreementException("computeSharedSecret()", x);
}
-
N = new BigInteger(
- 1,
- Util.fromBase64((String) configuration.get(SRPRegistry.SHARED_MODULUS)));
+ 1, Util.fromBase64((String) configuration.get(SRPRegistry.SHARED_MODULUS)));
g = new BigInteger(
- 1,
- Util.fromBase64((String) configuration.get(SRPRegistry.FIELD_GENERATOR)));
- // ----------------------------------------------------------------------
-
+ 1, Util.fromBase64((String) configuration.get(SRPRegistry.FIELD_GENERATOR)));
// generate an ephemeral keypair
final SRPKeyPairGenerator kpg = new SRPKeyPairGenerator();
final Map attributes = new HashMap();
if (rnd != null)
- {
- attributes.put(SRPKeyPairGenerator.SOURCE_OF_RANDOMNESS, rnd);
- }
+ attributes.put(SRPKeyPairGenerator.SOURCE_OF_RANDOMNESS, rnd);
attributes.put(SRPKeyPairGenerator.SHARED_MODULUS, N);
attributes.put(SRPKeyPairGenerator.GENERATOR, g);
attributes.put(SRPKeyPairGenerator.USER_VERIFIER, v);
kpg.setup(attributes);
hostKeyPair = kpg.generate();
-
final BigInteger B = ((SRPPublicKey) hostKeyPair.getPublic()).getY();
-
final OutgoingMessage result = new OutgoingMessage();
result.writeMPI(N);
result.writeMPI(g);
result.writeMPI(s);
result.writeMPI(B);
-
return result;
}
@@ -201,17 +164,13 @@ public class SRP6TLSServer extends SRP6KeyAgreement
throws KeyAgreementException
{
final BigInteger A = in.readMPI();
-
final BigInteger B = ((SRPPublicKey) hostKeyPair.getPublic()).getY();
final BigInteger u = uValue(A, B); // u = H(A | B)
-
// compute S = (Av^u) ^ b
final BigInteger b = ((SRPPrivateKey) hostKeyPair.getPrivate()).getX();
final BigInteger v = ((SRPPrivateKey) hostKeyPair.getPrivate()).getV();
final BigInteger S = A.multiply(v.modPow(u, N)).modPow(b, N);
-
K = S;
-
complete = true;
return null;
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6User.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6User.java
index d300d6f..7c97e76 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6User.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRP6User.java
@@ -52,73 +52,45 @@ import java.util.HashMap;
import java.util.Map;
/**
- *
- *
*/
-public class SRP6User extends SRP6KeyAgreement
+public class SRP6User
+ extends SRP6KeyAgreement
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** The user's identity. */
private String I;
-
/** The user's cleartext password. */
private byte[] p;
-
/** The user's ephemeral key pair. */
private KeyPair userKeyPair;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // implementation of abstract methods in base class ------------------------
-
protected void engineInit(final Map attributes) throws KeyAgreementException
{
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
N = (BigInteger) attributes.get(SHARED_MODULUS);
if (N == null)
- {
- throw new KeyAgreementException("missing shared modulus");
- }
+ throw new KeyAgreementException("missing shared modulus");
g = (BigInteger) attributes.get(GENERATOR);
if (g == null)
- {
- throw new KeyAgreementException("missing generator");
- }
-
+ throw new KeyAgreementException("missing generator");
final String md = (String) attributes.get(HASH_FUNCTION);
- if (md == null || "".equals(md.trim()))
- {
- throw new KeyAgreementException("missing hash function");
- }
+ if (md == null || md.trim().length() == 0)
+ throw new KeyAgreementException("missing hash function");
srp = SRP.instance(md);
-
I = (String) attributes.get(USER_IDENTITY);
if (I == null)
- {
- throw new KeyAgreementException("missing user identity");
- }
+ throw new KeyAgreementException("missing user identity");
p = (byte[]) attributes.get(USER_PASSWORD);
if (p == null)
- {
- throw new KeyAgreementException("missing user password");
- }
+ throw new KeyAgreementException("missing user password");
}
protected OutgoingMessage engineProcessMessage(final IncomingMessage in)
@@ -143,8 +115,6 @@ public class SRP6User extends SRP6KeyAgreement
super.engineReset();
}
- // own methods -------------------------------------------------------------
-
private OutgoingMessage sendIdentity(final IncomingMessage in)
throws KeyAgreementException
{
@@ -152,18 +122,14 @@ public class SRP6User extends SRP6KeyAgreement
final SRPKeyPairGenerator kpg = new SRPKeyPairGenerator();
final Map attributes = new HashMap();
if (rnd != null)
- {
- attributes.put(SRPKeyPairGenerator.SOURCE_OF_RANDOMNESS, rnd);
- }
+ attributes.put(SRPKeyPairGenerator.SOURCE_OF_RANDOMNESS, rnd);
attributes.put(SRPKeyPairGenerator.SHARED_MODULUS, N);
attributes.put(SRPKeyPairGenerator.GENERATOR, g);
kpg.setup(attributes);
userKeyPair = kpg.generate();
-
final OutgoingMessage result = new OutgoingMessage();
result.writeString(I);
result.writeMPI(((SRPPublicKey) userKeyPair.getPublic()).getY());
-
return result;
}
@@ -172,10 +138,8 @@ public class SRP6User extends SRP6KeyAgreement
{
final BigInteger s = in.readMPI();
final BigInteger B = in.readMPI();
-
final BigInteger A = ((SRPPublicKey) userKeyPair.getPublic()).getY();
final BigInteger u = uValue(A, B); // u = H(A | B)
-
final BigInteger x;
try
{
@@ -185,18 +149,14 @@ public class SRP6User extends SRP6KeyAgreement
{
throw new KeyAgreementException("computeSharedSecret()", e);
}
-
// compute S = (B - 3g^x) ^ (a + ux)
final BigInteger a = ((SRPPrivateKey) userKeyPair.getPrivate()).getX();
- final BigInteger S = B.subtract(THREE.multiply(g.modPow(x, N))).modPow(
- a.add(u.multiply(x)),
- N);
-
+ final BigInteger S = B.subtract(THREE.multiply(g.modPow(x, N)))
+ .modPow(a.add(u.multiply(x)), N);
final byte[] sBytes = Util.trim(S);
final IMessageDigest hash = srp.newDigest();
hash.update(sBytes, 0, sBytes.length);
K = new BigInteger(1, hash.digest());
-
complete = true;
return null;
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPAlgorithm.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPAlgorithm.java
index b068863..85b3b11 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPAlgorithm.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPAlgorithm.java
@@ -38,15 +38,14 @@ exception statement from your version. */
package gnu.javax.crypto.key.srp6;
-import gnu.java.security.util.Prime2;
import gnu.javax.crypto.sasl.srp.SRPRegistry;
import java.math.BigInteger;
/**
- *
- * Thomas J. Wu.
+ * Thomas J. Wu.
*
* Thomas J. Wu.
- *
- *
- *
- *
*/
-public abstract class SRPKey implements Key, Serializable
+public abstract class SRPKey
+ implements Key, Serializable
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/** The public, Germaine prime, shared modulus. */
protected final BigInteger N;
-
/** The generator. */
protected final BigInteger g;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
protected SRPKey(BigInteger N, BigInteger g)
{
super();
@@ -85,17 +78,9 @@ public abstract class SRPKey implements Key, Serializable
this.g = g;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.security.Key interface implementation ------------------------------
-
/**
- *
- * Thomas J. Wu.
+ * Thomas J. Wu.N
.
*/
public BigInteger getN()
@@ -133,8 +116,8 @@ public abstract class SRPKey implements Key, Serializable
}
/**
- * g
.
*/
public BigInteger getG()
@@ -143,28 +126,22 @@ public abstract class SRPKey implements Key, Serializable
}
/**
- * true
if the designated object is an instance of
- * SRPKey
and has the same SRP parameter values as this one.true
if the designated object is an instance of
+ * SRPKey
and has the same SRP parameter values as this one.
+ *
* @param obj the other non-null SRP key to compare to.
- * @return true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(Object obj)
{
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof SRPKey))
- {
- return false;
- }
+ return false;
+ if (! (obj instanceof SRPKey))
+ return false;
SRPKey that = (SRPKey) obj;
return N.equals(that.getN()) && g.equals(that.getG());
}
- // abstract methods to be implemented by subclasses ------------------------
-
public abstract byte[] getEncoded(int format);
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java
index 2957fc3..8d50c9b 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPKeyPairGenerator.java
@@ -38,111 +38,64 @@ exception statement from your version. */
package gnu.javax.crypto.key.srp6;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.key.IKeyPairGenerator;
import gnu.java.security.util.PRNG;
-import gnu.java.security.util.Prime2;
-import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.util.Map;
+import java.util.logging.Logger;
/**
- *
- *
- *
- *
*/
-public class SRPKeyPairGenerator implements IKeyPairGenerator
+public class SRPKeyPairGenerator
+ implements IKeyPairGenerator
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "srp";
-
- private static final boolean DEBUG = false;
-
- private static final int debuglevel = 5;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String s)
- {
- err.println(">>> " + NAME + ": " + s);
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(SRPKeyPairGenerator.class.getName());
private static final BigInteger ZERO = BigInteger.ZERO;
-
private static final BigInteger ONE = BigInteger.ONE;
-
private static final BigInteger TWO = BigInteger.valueOf(2L);
-
private static final BigInteger THREE = BigInteger.valueOf(3L);
-
/** Property name of the length (Integer) of the modulus (N) of an SRP key. */
public static final String MODULUS_LENGTH = "gnu.crypto.srp.L";
-
/** Property name of the Boolean indicating wether or not to use defaults. */
public static final String USE_DEFAULTS = "gnu.crypto.srp.use.defaults";
-
/** Property name of the modulus (N) of an SRP key. */
public static final String SHARED_MODULUS = "gnu.crypto.srp.N";
-
/** Property name of the generator (g) of an SRP key. */
public static final String GENERATOR = "gnu.crypto.srp.g";
-
/** Property name of the user's verifier (v) for a Server SRP key. */
public static final String USER_VERIFIER = "gnu.crypto.srp.v";
-
/**
* Property name of an optional {@link SecureRandom} instance to use. The
* default is to use a classloader singleton from {@link PRNG}.
*/
public static final String SOURCE_OF_RANDOMNESS = "gnu.crypto.srp.prng";
-
/** Default value for the modulus length. */
private static final int DEFAULT_MODULUS_LENGTH = 1024;
-
/** The optional {@link SecureRandom} instance to use. */
private SecureRandom rnd = null;
-
/** Bit length of the shared modulus. */
private int l;
-
/** The shared public modulus. */
private BigInteger N;
-
/** The Field generator. */
private BigInteger g;
-
/** The user's verifier MPI. */
private BigInteger v;
-
/** Our default source of randomness. */
private PRNG prng = null;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// implicit 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // gnu.crypto.key.IKeyPairGenerator interface implementation ---------------
-
public String name()
{
return Registry.SRP_KPG;
@@ -152,25 +105,20 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
{
// do we have a SecureRandom, or should we use our own?
rnd = (SecureRandom) attributes.get(SOURCE_OF_RANDOMNESS);
-
N = (BigInteger) attributes.get(SHARED_MODULUS);
if (N != null)
{
l = N.bitLength();
g = (BigInteger) attributes.get(GENERATOR);
if (g == null)
- {
- g = TWO;
- }
+ g = TWO;
SRPAlgorithm.checkParams(N, g);
}
else
{ // generate or use default values for N and g
Boolean useDefaults = (Boolean) attributes.get(USE_DEFAULTS);
if (useDefaults == null)
- {
- useDefaults = Boolean.TRUE;
- }
+ useDefaults = Boolean.TRUE;
Integer L = (Integer) attributes.get(MODULUS_LENGTH);
l = DEFAULT_MODULUS_LENGTH;
if (useDefaults.equals(Boolean.TRUE))
@@ -203,26 +151,23 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
break;
default:
throw new IllegalArgumentException(
- "unknown default shared modulus bit length");
+ "unknown default shared modulus bit length");
}
g = TWO;
l = N.bitLength();
}
}
- else
- { // generate new N and g
+ else // generate new N and g
+ {
if (L != null)
{
l = L.intValue();
if ((l % 256) != 0 || l < 512 || l > 2048)
- {
- throw new IllegalArgumentException(
- "invalid shared modulus bit length");
- }
+ throw new IllegalArgumentException(
+ "invalid shared modulus bit length");
}
}
}
-
// are we using this generator on the server side, or the client side?
v = (BigInteger) attributes.get(USER_VERIFIER);
}
@@ -235,23 +180,20 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
BigInteger q = params[0];
N = params[1];
g = params[2];
- if (DEBUG && debuglevel > 0)
+ if (Configuration.DEBUG)
{
- debug("q: " + q.toString(16));
- debug("N: " + N.toString(16));
- debug("g: " + g.toString(16));
+ log.fine("q: " + q.toString(16));
+ log.fine("N: " + N.toString(16));
+ log.fine("g: " + g.toString(16));
}
}
-
return (v != null ? hostKeyPair() : userKeyPair());
}
- // helper methods ----------------------------------------------------------
-
private synchronized BigInteger[] generateParameters()
{
- // N A large safe prime (N = 2q+1, where q is prime)
- // g A generator modulo N
+ // N A large safe prime (N = 2q+1, where q is prime)
+ // g A generator modulo N
BigInteger q, p, g;
byte[] qBytes = new byte[l / 8];
do
@@ -262,11 +204,10 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
q = new BigInteger(1, qBytes);
q = q.setBit(0).setBit(l - 2).clearBit(l - 1);
}
- while (!Prime2.isProbablePrime(q));
+ while (! q.isProbablePrime(80));
p = q.multiply(TWO).add(ONE);
}
- while (p.bitLength() != l || !Prime2.isProbablePrime(p));
-
+ while (p.bitLength() != l || ! p.isProbablePrime(80));
// compute g. from FIPS-186, Appendix 4: e == 2
BigInteger p_minus_1 = p.subtract(ONE);
g = TWO;
@@ -277,12 +218,9 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
// Set g = h**2 mod p
g = h.modPow(TWO, p);
// If g = 1, go to step 3
- if (!g.equals(ONE))
- {
- break;
- }
+ if (! g.equals(ONE))
+ break;
}
-
return new BigInteger[] { q, p, g };
}
@@ -301,11 +239,8 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
B = THREE.multiply(v).add(g.modPow(b, N)).mod(N);
}
while (B.compareTo(ZERO) == 0 || B.compareTo(N) >= 0);
-
- KeyPair result = new KeyPair(
- new SRPPublicKey(new BigInteger[] { N, g, B }),
- new SRPPrivateKey(new BigInteger[] { N, g, b,
- v }));
+ KeyPair result = new KeyPair(new SRPPublicKey(new BigInteger[] { N, g, B }),
+ new SRPPrivateKey(new BigInteger[] { N, g, b, v }));
return result;
}
@@ -324,9 +259,7 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
A = g.modPow(a, N);
}
while (A.compareTo(ZERO) == 0 || A.compareTo(N) >= 0);
-
- KeyPair result = new KeyPair(
- new SRPPublicKey(new BigInteger[] { N, g, A }),
+ KeyPair result = new KeyPair(new SRPPublicKey(new BigInteger[] { N, g, A }),
new SRPPrivateKey(new BigInteger[] { N, g, a }));
return result;
}
@@ -334,9 +267,7 @@ public class SRPKeyPairGenerator implements IKeyPairGenerator
private void nextRandomBytes(byte[] buffer)
{
if (rnd != null)
- {
- rnd.nextBytes(buffer);
- }
+ rnd.nextBytes(buffer);
else
getDefaultPRNG().nextBytes(buffer);
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPKeyPairRawCodec.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPKeyPairRawCodec.java
index 39234b6..555dc23 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPKeyPairRawCodec.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPKeyPairRawCodec.java
@@ -47,116 +47,93 @@ import java.security.PrivateKey;
import java.security.PublicKey;
/**
- *
- * Thomas J. Wu.
+ * Thomas J. Wu.
- *
*/
-public class SRPKeyPairRawCodec implements IKeyPairCodec
+public class SRPKeyPairRawCodec
+ implements IKeyPairCodec
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// implicit 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // gnu.crypto.keys.IKeyPairCodec interface implementation ------------------
-
public int getFormatID()
{
return RAW_FORMAT;
}
/**
- *
- * Thomas J. Wu.
+ * Thomas J. Wu.
- *
- *
+ *
* @param key the key to encode.
* @return the Raw format encoding of the designated key.
* @throws IllegalArgumentException if the designated key is not an SRP one.
*/
public byte[] encodePublicKey(PublicKey key)
{
- if (!(key instanceof SRPPublicKey))
- {
- throw new IllegalArgumentException("key");
- }
-
+ if (! (key instanceof SRPPublicKey))
+ throw new IllegalArgumentException("key");
SRPPublicKey srpKey = (SRPPublicKey) key;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_SRP_PUBLIC_KEY[0]);
baos.write(Registry.MAGIC_RAW_SRP_PUBLIC_KEY[1]);
baos.write(Registry.MAGIC_RAW_SRP_PUBLIC_KEY[2]);
baos.write(Registry.MAGIC_RAW_SRP_PUBLIC_KEY[3]);
-
// version
baos.write(0x01);
-
// N
byte[] buffer = srpKey.getN().toByteArray();
int length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// g
buffer = srpKey.getG().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// y
buffer = srpKey.getY().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
return baos.toByteArray();
}
@@ -167,150 +144,133 @@ public class SRPKeyPairRawCodec implements IKeyPairCodec
|| k[1] != Registry.MAGIC_RAW_SRP_PUBLIC_KEY[1]
|| k[2] != Registry.MAGIC_RAW_SRP_PUBLIC_KEY[2]
|| k[3] != Registry.MAGIC_RAW_SRP_PUBLIC_KEY[3])
- {
- throw new IllegalArgumentException("magic");
- }
-
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
+ throw new IllegalArgumentException("version");
int i = 5;
-
int l;
byte[] buffer;
-
// N
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger N = new BigInteger(1, buffer);
-
// g
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger g = new BigInteger(1, buffer);
-
// y
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger y = new BigInteger(1, buffer);
-
return new SRPPublicKey(N, g, y);
}
/**
- * N
in internet order,toByteArray()
method on the SRP parameter
- * N
,g
,toByteArray()
method on the SRP parameter
- * g
,y
,toByteArray()
method on the SRP parameter
- * y
,N
in internet order,toByteArray()
method on the SRP parameter N
,
+ * g
,toByteArray()
method on the SRP parameter g
,
+ * y
,toByteArray()
method on the SRP parameter y
,
+ *
- *
- *
+ *
* @param key the key to encode.
* @return the Raw format encoding of the designated key.
* @throws IllegalArgumentException if the designated key is not an SRP one.
*/
public byte[] encodePrivateKey(PrivateKey key)
{
- if (!(key instanceof SRPPrivateKey))
- {
- throw new IllegalArgumentException("key");
- }
-
+ if (! (key instanceof SRPPrivateKey))
+ throw new IllegalArgumentException("key");
SRPPrivateKey srpKey = (SRPPrivateKey) key;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
// magic
baos.write(Registry.MAGIC_RAW_SRP_PRIVATE_KEY[0]);
baos.write(Registry.MAGIC_RAW_SRP_PRIVATE_KEY[1]);
baos.write(Registry.MAGIC_RAW_SRP_PRIVATE_KEY[2]);
baos.write(Registry.MAGIC_RAW_SRP_PRIVATE_KEY[3]);
-
// version
baos.write(0x01);
-
// N
byte[] buffer = srpKey.getN().toByteArray();
int length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// g
buffer = srpKey.getG().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// x
buffer = srpKey.getX().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
-
// v
if (srpKey.getV() != null)
{
baos.write(0x01);
-
buffer = srpKey.getV().toByteArray();
length = buffer.length;
- baos.write(length >>> 24);
+ baos.write( length >>> 24);
baos.write((length >>> 16) & 0xFF);
- baos.write((length >>> 8) & 0xFF);
- baos.write(length & 0xFF);
+ baos.write((length >>> 8) & 0xFF);
+ baos.write( length & 0xFF);
baos.write(buffer, 0, length);
}
else
- {
- baos.write(0x00);
- }
-
+ baos.write(0x00);
return baos.toByteArray();
}
@@ -321,60 +281,54 @@ public class SRPKeyPairRawCodec implements IKeyPairCodec
|| k[1] != Registry.MAGIC_RAW_SRP_PRIVATE_KEY[1]
|| k[2] != Registry.MAGIC_RAW_SRP_PRIVATE_KEY[2]
|| k[3] != Registry.MAGIC_RAW_SRP_PRIVATE_KEY[3])
- {
- throw new IllegalArgumentException("magic");
- }
-
+ throw new IllegalArgumentException("magic");
// version
if (k[4] != 0x01)
- {
- throw new IllegalArgumentException("version");
- }
+ throw new IllegalArgumentException("version");
int i = 5;
-
int l;
byte[] buffer;
-
// N
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger N = new BigInteger(1, buffer);
-
// g
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger g = new BigInteger(1, buffer);
-
// x
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger x = new BigInteger(1, buffer);
-
// v
l = k[i++];
if (l == 0x01)
{
- l = k[i++] << 24 | (k[i++] & 0xFF) << 16 | (k[i++] & 0xFF) << 8
- | (k[i++] & 0xFF);
+ l = k[i++] << 24
+ | (k[i++] & 0xFF) << 16
+ | (k[i++] & 0xFF) << 8
+ | (k[i++] & 0xFF);
buffer = new byte[l];
System.arraycopy(k, i, buffer, 0, l);
i += l;
BigInteger v = new BigInteger(1, buffer);
-
return new SRPPrivateKey(N, g, x, v);
}
- else
- {
- return new SRPPrivateKey(N, g, x);
- }
+ return new SRPPrivateKey(N, g, x);
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPPrivateKey.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPPrivateKey.java
index d9f7a19a6..d5ade07 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPPrivateKey.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPPrivateKey.java
@@ -45,39 +45,33 @@ import java.math.BigInteger;
import java.security.PrivateKey;
/**
- * N
in internet order,toByteArray()
method on the SRP parameter
- * N
,g
,toByteArray()
method on the SRP parameter
- * g
,x
,toByteArray()
method on the SRP parameter
- * x
,v
- * is included in this encoding (value 0x01
) or not
- * (value 0x00
).v
,toByteArray()
method on the SRP parameter
- * v
,N
in internet order,toByteArray()
method on the SRP parameter N
,
+ * g
,toByteArray()
method on the SRP parameter g
,
+ * x
,toByteArray()
method on the SRP parameter x
,
+ * v
is
+ * included in this encoding (value 0x01
) or not (value
+ * 0x00
).v
,toByteArray()
method on the SRP parameter v
,
+ *
- *
*/
-public class SRPPrivateKey extends SRPKey implements PrivateKey
+public class SRPPrivateKey
+ extends SRPKey
+ implements PrivateKey
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/**
- * The private exponent for either the server or the client engaged in the
- * SRP protocol exchange.
+ * The private exponent for either the server or the client engaged in the SRP
+ * protocol exchange.
*/
private final BigInteger X;
-
/**
- * The user's verifier (v) --for the server-- also computed at the client
- * side as g.modPow(x, N), where x is the hashed output of the user name and
+ * The user's verifier (v) --for the server-- also computed at the client side
+ * as g.modPow(x, N), where x is the hashed output of the user name and
* password .
*/
private final BigInteger v;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- *
- * Thomas J. Wu.
+ * Thomas J. Wu.
- *
+ * either v and X for the server, or just X for the client. Those
+ * values represent the following:
+ *
+ *
*/
SRPPrivateKey(BigInteger[] params)
{
@@ -130,31 +125,27 @@ public class SRPPrivateKey extends SRPKey implements PrivateKey
v = params[3];
}
else
- {
- throw new IllegalArgumentException("invalid number of SRP parameters");
- }
+ throw new IllegalArgumentException("invalid number of SRP parameters");
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
- * encodePrivateKey()
+ * A class method that takes the output of the encodePrivateKey()
* method of an SRP keypair codec object (an instance implementing
* {@link IKeyPairCodec} for DSS keys, and re-constructs an instance of this
- * object.k
, to represent a valid encoding of an instance of this object.
+ * k
, to represent a valid encoding of an instance
+ * of this object.
* @throws IllegalArgumentException if the byte sequence does not represent a
- * valid encoding of an instance of this object.
+ * valid encoding of an instance of this object.
*/
public static SRPPrivateKey valueOf(byte[] k)
{
// check magic...
// we should parse here enough bytes to know which codec to use, and
- // direct the byte array to the appropriate codec. since we only have one
+ // direct the byte array to the appropriate codec. since we only have one
// codec, we could have immediately tried it; nevertheless since testing
// one byte is cheaper than instatiating a codec that will fail we test
// the first byte before we carry on.
@@ -164,18 +155,12 @@ public class SRPPrivateKey extends SRPKey implements PrivateKey
IKeyPairCodec codec = new SRPKeyPairRawCodec();
return (SRPPrivateKey) codec.decodePrivateKey(k);
}
- else
- {
- throw new IllegalArgumentException("magic");
- }
+ throw new IllegalArgumentException("magic");
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
- * null
if this is a private SRP key
- * for a User.
+ * private key of a Host, or null
if this is a private
+ * SRP key for a User.
*/
public BigInteger getV()
{
return v;
}
- // Other instance methods --------------------------------------------------
-
/**
- * true
if the designated object is an instance of
+ * Returns true
if the designated object is an instance of
* SRPPrivateKey
and has the same SRP parameter values as this
- * one.true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(Object obj)
{
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof SRPPrivateKey))
- {
- return false;
- }
+ return false;
+ if (! (obj instanceof SRPPrivateKey))
+ return false;
SRPPrivateKey that = (SRPPrivateKey) obj;
boolean result = super.equals(that) && X.equals(that.getX());
if (v != null)
- {
- result = result && v.equals(that.getV());
- }
+ result = result && v.equals(that.getV());
return result;
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPPublicKey.java b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPPublicKey.java
index 7283fd3..04a9492 100644
--- a/libjava/classpath/gnu/javax/crypto/key/srp6/SRPPublicKey.java
+++ b/libjava/classpath/gnu/javax/crypto/key/srp6/SRPPublicKey.java
@@ -45,32 +45,27 @@ import java.math.BigInteger;
import java.security.PublicKey;
/**
- *
- *
*/
-public class SRPPublicKey extends SRPKey implements PublicKey
+public class SRPPublicKey
+ extends SRPKey
+ implements PublicKey
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/**
- * The public exponent for either the server or the client engaged in the
- * SRP protocol exchange.
+ * The public exponent for either the server or the client engaged in the SRP
+ * protocol exchange.
*/
private final BigInteger Y;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- *
- * Thomas J. Wu.
+ * Thomas J. Wu.encodePublicKey()
+ * A class method that takes the output of the encodePublicKey()
* method of an SRP keypair codec object (an instance implementing
* {@link IKeyPairCodec} for SRP keys, and re-constructs an instance of this
- * object.k
, to represent a valid encoding of an instance of this object.
+ * k
, to represent a valid encoding of an instance
+ * of this object.
* @throws IllegalArgumentException if the byte sequence does not represent a
- * valid encoding of an instance of this object.
+ * valid encoding of an instance of this object.
*/
public static SRPPublicKey valueOf(byte[] k)
{
// check magic...
// we should parse here enough bytes to know which codec to use, and
- // direct the byte array to the appropriate codec. since we only have one
+ // direct the byte array to the appropriate codec. since we only have one
// codec, we could have immediately tried it; nevertheless since testing
// one byte is cheaper than instatiating a codec that will fail we test
// the first byte before we carry on.
@@ -125,18 +118,12 @@ public class SRPPublicKey extends SRPKey implements PublicKey
IKeyPairCodec codec = new SRPKeyPairRawCodec();
return (SRPPublicKey) codec.decodePublicKey(k);
}
- else
- {
- throw new IllegalArgumentException("magic");
- }
+ throw new IllegalArgumentException("magic");
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
- * true
if the designated object is an instance of
- * SRPPublicKey
and has the same SRP parameter values as this one.
- * true
if the designated object is an instance of
+ * SRPPublicKey
and has the same SRP parameter values as this
+ * one.
+ *
* @param obj the other non-null SRP key to compare to.
- * @return true
if the designated object is of the same type and
- * value as this one.
+ * @return true
if the designated object is of the same type
+ * and value as this one.
*/
public boolean equals(Object obj)
{
if (obj == null)
- {
- return false;
- }
- if (!(obj instanceof SRPPublicKey))
- {
- return false;
- }
+ return false;
+ if (! (obj instanceof SRPPublicKey))
+ return false;
SRPPublicKey that = (SRPPublicKey) obj;
return super.equals(that) && Y.equals(that.getY());
}
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/AuthenticatedEntry.java b/libjava/classpath/gnu/javax/crypto/keyring/AuthenticatedEntry.java
index 22b42b3..cd2e586 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/AuthenticatedEntry.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/AuthenticatedEntry.java
@@ -38,46 +38,32 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.java.security.Registry;
+import gnu.javax.crypto.mac.IMac;
+import gnu.javax.crypto.mac.MacFactory;
+import gnu.javax.crypto.mac.MacOutputStream;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
-
import java.security.InvalidKeyException;
-
import java.util.Arrays;
-import java.util.Date;
-import java.util.Iterator;
import java.util.HashMap;
-import java.util.List;
-
-import gnu.java.security.Registry;
-import gnu.javax.crypto.mac.IMac;
-import gnu.javax.crypto.mac.MacFactory;
-import gnu.javax.crypto.mac.MacInputStream;
-import gnu.javax.crypto.mac.MacOutputStream;
+import java.util.Iterator;
-public final class AuthenticatedEntry extends MaskableEnvelopeEntry implements
- Registry
+public final class AuthenticatedEntry
+ extends MaskableEnvelopeEntry
+ implements Registry
{
-
- // Constants and fields.
- // ------------------------------------------------------------------------
-
public static final int TYPE = 2;
- // Constructor.
- // ------------------------------------------------------------------------
-
public AuthenticatedEntry(String mac, int macLen, Properties properties)
{
super(TYPE, properties);
-
if (macLen <= 0)
- {
- throw new IllegalArgumentException("invalid mac length");
- }
+ throw new IllegalArgumentException("invalid mac length");
this.properties.put("mac", mac);
this.properties.put("maclen", String.valueOf(macLen));
setMasked(false);
@@ -89,32 +75,22 @@ public final class AuthenticatedEntry extends MaskableEnvelopeEntry implements
setMasked(true);
}
- // Class methods.
- // ------------------------------------------------------------------------
-
public static AuthenticatedEntry decode(DataInputStream in)
throws IOException
{
AuthenticatedEntry entry = new AuthenticatedEntry();
entry.properties.decode(in);
- if (!entry.properties.containsKey("mac"))
- {
- throw new MalformedKeyringException("no mac specified");
- }
- if (!entry.properties.containsKey("maclen"))
- {
- throw new MalformedKeyringException("no mac length specified");
- }
+ if (! entry.properties.containsKey("mac"))
+ throw new MalformedKeyringException("no mac specified");
+ if (! entry.properties.containsKey("maclen"))
+ throw new MalformedKeyringException("no mac length specified");
return entry;
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
/**
* Computes the mac over this envelope's data. This method must be
* called before this entry in encoded.
- *
+ *
* @param key The key to authenticate with.
* @throws IOException If encoding fails.
* @throws InvalidKeyException If the supplied key is bad.
@@ -122,11 +98,8 @@ public final class AuthenticatedEntry extends MaskableEnvelopeEntry implements
public void authenticate(byte[] key) throws IOException, InvalidKeyException
{
if (isMasked())
- {
- throw new IllegalStateException("entry is masked");
- }
+ throw new IllegalStateException("entry is masked");
IMac m = getMac(key);
-
ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
MacOutputStream macout = new MacOutputStream(bout, m);
DataOutputStream out2 = new DataOutputStream(macout);
@@ -140,36 +113,28 @@ public final class AuthenticatedEntry extends MaskableEnvelopeEntry implements
}
/**
- * Verifies this entry's payload. This method will unmask this entry,
- * thus it must be called before accessing its contents.
- *
+ * Verifies this entry's payload. This method will unmask this entry, thus it
+ * must be called before accessing its contents.
+ *
* @param key The key to use to authenticate.
* @throws InvalidKeyException If the given key is improper.
*/
public void verify(byte[] key) throws InvalidKeyException
{
- if (!isMasked() || payload == null)
- {
- return;
- }
+ if (! isMasked() || payload == null)
+ return;
IMac m = getMac(key);
-
m.update(payload, 0, payload.length - m.macSize());
byte[] macValue = new byte[m.macSize()];
System.arraycopy(payload, payload.length - macValue.length, macValue, 0,
macValue.length);
- if (!Arrays.equals(macValue, m.digest()))
- {
- throw new IllegalArgumentException("MAC verification failed");
- }
+ if (! Arrays.equals(macValue, m.digest()))
+ throw new IllegalArgumentException("MAC verification failed");
try
{
- DataInputStream in = new DataInputStream(
- new ByteArrayInputStream(
- payload,
- 0,
- payload.length
- - m.macSize()));
+ int len = payload.length - m.macSize();
+ ByteArrayInputStream bais = new ByteArrayInputStream(payload, 0, len);
+ DataInputStream in = new DataInputStream(bais);
decodeEnvelope(in);
}
catch (IOException ioe)
@@ -183,27 +148,17 @@ public final class AuthenticatedEntry extends MaskableEnvelopeEntry implements
protected void encodePayload() throws IOException
{
if (payload == null)
- {
- throw new IllegalStateException("not authenticated");
- }
+ throw new IllegalStateException("not authenticated");
}
- // Own methods.
- // ------------------------------------------------------------------------
-
private IMac getMac(byte[] key) throws InvalidKeyException
{
IMac mac = MacFactory.getInstance(properties.get("mac"));
if (mac == null)
- {
- throw new IllegalArgumentException("no such mac: "
- + properties.get("mac"));
- }
+ throw new IllegalArgumentException("no such mac: " + properties.get("mac"));
int maclen = 0;
- if (!properties.containsKey("maclen"))
- {
- throw new IllegalArgumentException("no MAC length");
- }
+ if (! properties.containsKey("maclen"))
+ throw new IllegalArgumentException("no MAC length");
try
{
maclen = Integer.parseInt(properties.get("maclen"));
@@ -212,10 +167,9 @@ public final class AuthenticatedEntry extends MaskableEnvelopeEntry implements
{
throw new IllegalArgumentException("bad MAC length");
}
-
HashMap macAttr = new HashMap();
macAttr.put(IMac.MAC_KEY_MATERIAL, key);
- macAttr.put(IMac.TRUNCATED_SIZE, new Integer(maclen));
+ macAttr.put(IMac.TRUNCATED_SIZE, Integer.valueOf(maclen));
mac.init(macAttr);
return mac;
}
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/BaseKeyring.java b/libjava/classpath/gnu/javax/crypto/keyring/BaseKeyring.java
index 5fe7dbf..369507d 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/BaseKeyring.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/BaseKeyring.java
@@ -38,86 +38,58 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
-import java.io.InputStream;
+import gnu.java.security.Registry;
+
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
-
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
-import gnu.java.security.Registry;
-
-public abstract class BaseKeyring implements IKeyring
+public abstract class BaseKeyring
+ implements IKeyring
{
-
- // Fields.
- // ------------------------------------------------------------------------
-
- /**
- * The top-level keyring data.
- */
+ /** The top-level keyring data. */
protected PasswordAuthenticatedEntry keyring;
-
protected CompressedEntry keyring2;
- // Constructors.
- // ------------------------------------------------------------------------
-
public BaseKeyring()
{
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
public void load(Map attributes) throws IOException
{
InputStream in = (InputStream) attributes.get(KEYRING_DATA_IN);
if (in == null)
- {
- throw new IllegalArgumentException("no input stream");
- }
+ throw new IllegalArgumentException("no input stream");
char[] password = (char[]) attributes.get(KEYRING_PASSWORD);
if (password == null)
- {
- password = new char[0];
- }
+ password = new char[0];
if (in.read() != Registry.GKR_MAGIC[0]
|| in.read() != Registry.GKR_MAGIC[1]
|| in.read() != Registry.GKR_MAGIC[2]
|| in.read() != Registry.GKR_MAGIC[3])
- {
- throw new MalformedKeyringException("magic");
- }
+ throw new MalformedKeyringException("magic");
load(in, password);
-
List l = keyring.getEntries();
if (l.size() == 1 && (l.get(0) instanceof CompressedEntry))
- {
- keyring2 = (CompressedEntry) l.get(0);
- }
+ keyring2 = (CompressedEntry) l.get(0);
}
public void store(Map attributes) throws IOException
{
OutputStream out = (OutputStream) attributes.get(KEYRING_DATA_OUT);
if (out == null)
- {
- throw new IllegalArgumentException("no output stream");
- }
+ throw new IllegalArgumentException("no output stream");
char[] password = (char[]) attributes.get(KEYRING_PASSWORD);
if (password == null)
- {
- password = new char[0];
- }
+ password = new char[0];
if (keyring == null)
- {
- throw new IllegalStateException("empty keyring");
- }
+ throw new IllegalStateException("empty keyring");
out.write(Registry.GKR_MAGIC);
store(out, password);
@@ -131,45 +103,35 @@ public abstract class BaseKeyring implements IKeyring
public int size()
{
if (keyring == null)
- {
- throw new IllegalStateException ("keyring not loaded");
- }
+ throw new IllegalStateException("keyring not loaded");
return ((StringTokenizer) aliases()).countTokens();
}
public Enumeration aliases()
{
if (keyring == null)
- {
- throw new IllegalStateException ("keyring not loaded");
- }
+ throw new IllegalStateException("keyring not loaded");
return new StringTokenizer(keyring.getAliasList(), ";");
}
public boolean containsAlias(String alias)
{
if (keyring == null)
- {
- throw new IllegalStateException("keyring not loaded");
- }
+ throw new IllegalStateException("keyring not loaded");
return keyring.containsAlias(alias);
}
public List get(String alias)
{
if (keyring == null)
- {
- throw new IllegalStateException("keyring not loaded");
- }
+ throw new IllegalStateException("keyring not loaded");
return keyring.get(alias);
}
public void add(Entry entry)
{
if (keyring == null)
- {
- throw new IllegalStateException("keyring not loaded");
- }
+ throw new IllegalStateException("keyring not loaded");
if (keyring2 != null)
keyring2.add(entry);
else
@@ -179,9 +141,7 @@ public abstract class BaseKeyring implements IKeyring
public void remove(String alias)
{
if (keyring == null)
- {
- throw new IllegalStateException("keyring not loaded");
- }
+ throw new IllegalStateException("keyring not loaded");
keyring.remove(alias);
}
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/BinaryDataEntry.java b/libjava/classpath/gnu/javax/crypto/keyring/BinaryDataEntry.java
index 2dcd545..e694487 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/BinaryDataEntry.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/BinaryDataEntry.java
@@ -40,29 +40,22 @@ package gnu.javax.crypto.keyring;
import java.io.DataInputStream;
import java.io.IOException;
-
import java.util.Date;
/**
- * A binary data entry is a primitive entry that simply contains some amount
- * of arbitrary binary data and an optional content type.
+ * A binary data entry is a primitive entry that simply contains some amount of
+ * arbitrary binary data and an optional content type.
*/
-public class BinaryDataEntry extends PrimitiveEntry
+public class BinaryDataEntry
+ extends PrimitiveEntry
{
-
- // Fields.
- // ------------------------------------------------------------------------
-
public static final int TYPE = 9;
- // Constructors.
- // ------------------------------------------------------------------------
-
/**
* Creates a new binary data entry.
- *
- * @param contentType The content type of this entry. This parameter can
- * be null
if no content type is needed.
+ *
+ * @param contentType The content type of this entry. This parameter can be
+ * null
if no content type is needed.
* @param data The data.
* @param creationDate The creation date.
* @param properties This entry's properties.
@@ -72,14 +65,10 @@ public class BinaryDataEntry extends PrimitiveEntry
{
super(TYPE, creationDate, properties);
if (data == null)
- {
- throw new IllegalArgumentException("no data");
- }
+ throw new IllegalArgumentException("no data");
payload = (byte[]) data.clone();
if (contentType != null)
- {
- this.properties.put("content-type", contentType);
- }
+ this.properties.put("content-type", contentType);
}
private BinaryDataEntry()
@@ -87,9 +76,6 @@ public class BinaryDataEntry extends PrimitiveEntry
super(TYPE);
}
- // Class methods.
- // ------------------------------------------------------------------------
-
public static BinaryDataEntry decode(DataInputStream in) throws IOException
{
BinaryDataEntry entry = new BinaryDataEntry();
@@ -97,13 +83,10 @@ public class BinaryDataEntry extends PrimitiveEntry
return entry;
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
/**
* Returns the content type of this entry, or null
if this
* property is not set.
- *
+ *
* @return The content type.
*/
public String getContentType()
@@ -113,7 +96,7 @@ public class BinaryDataEntry extends PrimitiveEntry
/**
* Returns this object's data field.
- *
+ *
* @return The data.
*/
public byte[] getData()
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/CertPathEntry.java b/libjava/classpath/gnu/javax/crypto/keyring/CertPathEntry.java
index ef62347..32b8608 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/CertPathEntry.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/CertPathEntry.java
@@ -40,40 +40,28 @@ package gnu.javax.crypto.keyring;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
-import java.io.DataOutputStream;
import java.io.IOException;
-
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
-
import java.util.Date;
/**
* A primitive entry that contains a path of X.509 certificates.
*/
-public final class CertPathEntry extends PrimitiveEntry
+public final class CertPathEntry
+ extends PrimitiveEntry
{
-
- // Constants and fields.
- // ------------------------------------------------------------------------
-
public static final int TYPE = 8;
-
private Certificate[] path;
- // Constructor.
- // ------------------------------------------------------------------------
-
public CertPathEntry(Certificate[] path, Date creationDate,
Properties properties)
{
super(TYPE, creationDate, properties);
if (path == null || path.length == 0)
- {
- throw new IllegalArgumentException("no certificate path");
- }
+ throw new IllegalArgumentException("no certificate path");
this.path = (Certificate[]) path.clone();
}
@@ -82,9 +70,6 @@ public final class CertPathEntry extends PrimitiveEntry
super(TYPE);
}
- // Class method.
- // ------------------------------------------------------------------------
-
public static CertPathEntry decode(DataInputStream in) throws IOException
{
CertPathEntry entry = new CertPathEntry();
@@ -95,8 +80,7 @@ public final class CertPathEntry extends PrimitiveEntry
try
{
CertificateFactory fact = CertificateFactory.getInstance("X.509");
- entry.path = (Certificate[]) fact.generateCertificates(in2).toArray(
- new Certificate[0]);
+ entry.path = (Certificate[]) fact.generateCertificates(in2).toArray(new Certificate[0]);
}
catch (CertificateException ce)
{
@@ -105,9 +89,6 @@ public final class CertPathEntry extends PrimitiveEntry
return entry;
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
public Certificate[] getCertPath()
{
return path;
@@ -120,9 +101,7 @@ public final class CertPathEntry extends PrimitiveEntry
try
{
for (int i = 0; i < path.length; i++)
- {
- bout.write(path[i].getEncoded());
- }
+ bout.write(path[i].getEncoded());
}
catch (CertificateEncodingException cee)
{
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/CertificateEntry.java b/libjava/classpath/gnu/javax/crypto/keyring/CertificateEntry.java
index 95a708a..6617584 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/CertificateEntry.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/CertificateEntry.java
@@ -39,50 +39,38 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
import java.io.DataInputStream;
-import java.io.DataOutputStream;
import java.io.IOException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
import java.util.Date;
/**
- * true
if alias
was present and was
+ * successfully trmoved. Returns false
if
+ * alias
was not present in the list of aliases in this
+ * envelope.
*/
- public void remove(String alias)
+ public boolean remove(String alias)
{
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "remove", alias);
+ boolean result = false;
for (Iterator it = entries.iterator(); it.hasNext();)
{
Entry e = (Entry) it.next();
if (e instanceof EnvelopeEntry)
{
- ((EnvelopeEntry) e).remove(alias);
+ EnvelopeEntry ee = (EnvelopeEntry) e;
+ result = ee.remove(alias) || result;
}
else if (e instanceof PrimitiveEntry)
{
- if (((PrimitiveEntry) e).getAlias().equals(alias))
+ PrimitiveEntry pe = (PrimitiveEntry) e;
+ if (pe.getAlias().equals(alias))
{
it.remove();
+ result = true;
}
}
}
- payload = null;
- makeAliasList();
+ if (result)
+ {
+ if (Configuration.DEBUG)
+ log.fine("State before: " + this);
+ payload = null;
+ makeAliasList();
+ if (Configuration.DEBUG)
+ log.fine("State after: " + this);
+ }
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "remove", Boolean.valueOf(result));
+ return result;
+ }
+
+ public String toString()
+ {
+ return new StringBuilder("Envelope{")
+ .append(super.toString())
+ .append(", entries=").append(entries)
+ .append("}")
+ .toString();
}
// Protected methods.
@@ -308,22 +341,19 @@ public abstract class EnvelopeEntry extends Entry
ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
DataOutputStream out = new DataOutputStream(bout);
for (Iterator it = entries.iterator(); it.hasNext();)
- {
- ((Entry) it.next()).encode(out);
- }
+ ((Entry) it.next()).encode(out);
}
protected void setContainingEnvelope(EnvelopeEntry e)
{
if (containingEnvelope != null)
- {
- throw new IllegalArgumentException("envelopes may not be shared");
- }
+ throw new IllegalArgumentException("envelopes may not be shared");
containingEnvelope = e;
}
protected void decodeEnvelope(DataInputStream in) throws IOException
{
+ this.entries.clear();
while (true)
{
int type = in.read();
@@ -367,32 +397,43 @@ public abstract class EnvelopeEntry extends Entry
}
}
- // Own methods.
- // ------------------------------------------------------------------------
-
private void makeAliasList()
{
- if (entries.isEmpty())
- return;
- StringBuffer buf = new StringBuffer();
- for (Iterator it = entries.iterator(); it.hasNext();)
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "makeAliasList");
+ if (! entries.isEmpty())
{
- Entry entry = (Entry) it.next();
- if (entry instanceof EnvelopeEntry)
- {
- buf.append(((EnvelopeEntry) entry).getAliasList());
- }
- else if (entry instanceof PrimitiveEntry)
+ StringBuilder buf = new StringBuilder();
+ String aliasOrList;
+ for (Iterator it = entries.iterator(); it.hasNext();)
{
- buf.append(((PrimitiveEntry) entry).getAlias());
+ Entry entry = (Entry) it.next();
+ aliasOrList = null;
+ if (entry instanceof EnvelopeEntry)
+ aliasOrList = ((EnvelopeEntry) entry).getAliasList();
+ else if (entry instanceof PrimitiveEntry)
+ aliasOrList = ((PrimitiveEntry) entry).getAlias();
+ else if (Configuration.DEBUG)
+ log.fine("Entry with no Alias. Ignored: " + entry);
+ if (aliasOrList != null)
+ {
+ aliasOrList = aliasOrList.trim();
+ if (aliasOrList.trim().length() > 0)
+ {
+ buf.append(aliasOrList);
+ if (it.hasNext())
+ buf.append(';');
+ }
+ }
}
- if (it.hasNext())
- buf.append(';');
- }
- properties.put("alias-list", buf.toString());
- if (containingEnvelope != null)
- {
- containingEnvelope.makeAliasList();
+ String aliasList = buf.toString();
+ properties.put("alias-list", aliasList);
+ if (Configuration.DEBUG)
+ log.fine("alias-list=[" + aliasList + "]");
+ if (containingEnvelope != null)
+ containingEnvelope.makeAliasList();
}
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "makeAliasList");
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java b/libjava/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java
index c1fe30e..2ccdad6 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/GnuPrivateKeyring.java
@@ -38,6 +38,7 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
+import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import java.io.DataInputStream;
@@ -55,30 +56,21 @@ import java.util.logging.Level;
import java.util.logging.Logger;
/**
- * attributes
.attributes
.
+ *
* @param attributes the attributes that define where the contents of this
- * keyring will be stored.
+ * keyring will be stored.
* @throws IOException if an exception occurs during the process.
*/
void store(Map attributes) throws IOException;
/**
- * alias
, or null
if there no such entry
- * exists.alias
, or null
if no one {@link Entry} can
- * be found with the designated alias
.
+ * given alias
, or null
if no one
+ * {@link Entry} can be found with the designated alias
.
*/
List get(String alias);
/**
- * alias
from this
- * keyring. Does nothing if there was no such entry.alias
from this
+ * keyring. Does nothing if there was no such entry.
+ * alias
.alias
.
+ *
* @param alias The alias to check.
* @return true
if this keyring contains a private key with the
- * given alias
; false
otherwise.alias
; false
otherwise.
*/
boolean containsPrivateKey(String alias);
/**
- * alias
.alias
.
+ *
* @param alias The alias of the private key to find.
* @param password The password of the private key.
* @return The private, or secret, key if one is found; null
if
- * none were found.
+ * none were found.
* @throws UnrecoverableKeyException If the private key could not be
- * recovered, possibly due to a bad password.
+ * recovered, possibly due to a bad password.
*/
Key getPrivateKey(String alias, char[] password)
throws UnrecoverableKeyException;
/**
- * alias
.alias
.
+ *
* @param alias The alias to test.
- * @return true
if this keyring contains a public key entry with
- * the given alias
; false
otherwise.
+ * @return true
if this keyring contains a public key entry
+ * with the given alias
; false
+ * otherwise.
*/
boolean containsPublicKey(String alias);
/**
- * alias
, or
- * null
if there is no such entry.alias
, or
+ * null
if there is no such entry.
+ *
* @param alias The alias of the public key to find.
* @return The public key; or null
if none were found.
*/
PublicKey getPublicKey(String alias);
/**
- * alias
.alias
.
+ *
* @param alias The alias to check.
- * @return true
if this keyring contains a certificate path with
- * the given alias
; false
otherwise.
+ * @return true
if this keyring contains a certificate path
+ * with the given alias
; false
+ * otherwise.
*/
boolean containsCertPath(String alias);
/**
- * alias
, or
- * null
if there is no such entry.alias
, or
+ * null
if there is no such entry.
+ *
* @param alias The alias of the certificate path to find.
* @return The certificate path for the designated alias
; or
- * null
if none were found.
+ * null
if none were found.
*/
Certificate[] getCertPath(String alias);
/**
- * alias
.alias
.
+ *
* @param alias The alias of the certificate to check.
* @return true
if this keyring contains a certificate entry
- * that has the given alias
; false
otherwise.
+ * that has the given alias
; false
+ * otherwise.
*/
boolean containsCertificate(String alias);
/**
- * alias
, or
- * null
if this keyring has no such entry.alias
, or
+ * null
if this keyring has no such entry.
+ *
* @param alias The alias of the certificate to find.
* @return The certificate with the designated alias
, or
- * null
if none found.
+ * null
if none found.
*/
Certificate getCertificate(String alias);
/**
- * alias
.alias
.
+ * (name => value)
pairs used in keyring entries.
- * Keys and values are simple strings, with the key never being empty and
- * always treated case-insensitively.
+ * Keys and values are simple strings, with the key never being empty and always
+ * treated case-insensitively.
*/
-public class Properties implements Cloneable
+public class Properties
+ implements Cloneable
{
-
- // Field.
- // ------------------------------------------------------------------------
-
private HashMap props;
- // Constructor.
- // ------------------------------------------------------------------------
-
/**
* Creates a new properties object.
*/
@@ -71,9 +64,6 @@ public class Properties implements Cloneable
props = new HashMap();
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
/**
* Removes all properties from this object.
*/
@@ -84,7 +74,7 @@ public class Properties implements Cloneable
/**
* Creates a copy of this properties object.
- *
+ *
* @return The copy.
*/
public Object clone()
@@ -96,86 +86,75 @@ public class Properties implements Cloneable
/**
* Tests if this object contains a given property name.
- *
+ *
* @param key The key to test.
* @return True if this object contains the given key.
*/
public boolean containsKey(String key)
{
if (key == null || key.length() == 0)
- {
- return false;
- }
+ return false;
return props.containsKey(canonicalize(key));
}
/**
* Tests if this object contains a given property value.
- *
+ *
* @param value The value to test.
* @return True if this object contains the given value.
*/
public boolean containsValue(String value)
{
if (value == null)
- {
- return false;
- }
+ return false;
return props.containsValue(value);
}
/**
* Adds a new property to this object.
- *
+ *
* @param key The key, which can neither be null nor empty.
* @param value The value, which cannot be null.
* @return The old value mapped by the key, if any.
- * @throws IllegalArgumentException If either the key or value parameter
-
- * is null, or if the key is empty.
+ * @throws IllegalArgumentException If either the key or value parameter is
+ * null, or if the key is empty.
*/
public String put(String key, String value)
{
if (key == null || value == null || key.length() == 0)
- {
- throw new IllegalArgumentException("key nor value can be null");
- }
+ throw new IllegalArgumentException("key nor value can be null");
return (String) props.put(canonicalize(key), value);
}
/**
- * Returns the value mapped by the given key, or null if there is no
- * such mapping.
- *
+ * Returns the value mapped by the given key, or null if there is no such
+ * mapping.
+ *
* @param key
*/
public String get(String key)
{
if (key == null || key.length() == 0)
- {
- return null;
- }
+ return null;
return (String) props.get(canonicalize(key));
}
/**
* Removes a key and its value from this object.
- *
+ *
* @param key The key of the property to remove.
* @return The old value mapped by the key, if any.
*/
public String remove(String key)
{
if (key == null || key.length() == 0)
- {
- return null;
- }
+ return null;
return (String) props.remove(canonicalize(key));
}
/**
* Decodes a set of properties from the given input stream.
- *
+ *
* @param in The input stream.
* @throws IOException If an I/O error occurs.
*/
@@ -184,7 +163,7 @@ public class Properties implements Cloneable
int len = in.readInt();
MeteredInputStream min = new MeteredInputStream(in, len);
DataInputStream in2 = new DataInputStream(min);
- while (!min.limitReached())
+ while (! min.limitReached())
{
String name = in2.readUTF();
String value = in2.readUTF();
@@ -194,7 +173,7 @@ public class Properties implements Cloneable
/**
* Encodes this set of properties to the given output stream.
- *
+ *
* @param out The output stream to encode to.
* @throws IOException If an I/O error occurs.
*/
@@ -217,9 +196,6 @@ public class Properties implements Cloneable
return props.toString();
}
- // Own methods.
- // ------------------------------------------------------------------------
-
private String canonicalize(String key)
{
return key.toLowerCase();
diff --git a/libjava/classpath/gnu/javax/crypto/keyring/PublicKeyEntry.java b/libjava/classpath/gnu/javax/crypto/keyring/PublicKeyEntry.java
index 528e70c..3e7f54d 100644
--- a/libjava/classpath/gnu/javax/crypto/keyring/PublicKeyEntry.java
+++ b/libjava/classpath/gnu/javax/crypto/keyring/PublicKeyEntry.java
@@ -38,43 +38,30 @@ exception statement from your version. */
package gnu.javax.crypto.keyring;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-import java.security.PublicKey;
-import java.security.KeyFactory;
-import java.security.spec.X509EncodedKeySpec;
-
-import java.util.Date;
-
import gnu.java.security.key.IKeyPairCodec;
import gnu.java.security.key.KeyPairCodecFactory;
import gnu.java.security.key.dss.DSSPublicKey;
import gnu.java.security.key.rsa.GnuRSAPublicKey;
import gnu.javax.crypto.key.dh.GnuDHPublicKey;
-public final class PublicKeyEntry extends PrimitiveEntry
-{
-
- // Constants and fields.
- // ------------------------------------------------------------------------
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.security.KeyFactory;
+import java.security.PublicKey;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Date;
+public final class PublicKeyEntry
+ extends PrimitiveEntry
+{
public static final int TYPE = 6;
-
private PublicKey key;
- // Constructor.
- // ------------------------------------------------------------------------
-
public PublicKeyEntry(PublicKey key, Date creationDate, Properties properties)
{
super(TYPE, creationDate, properties);
-
if (key == null)
- {
- throw new IllegalArgumentException("no key specified");
- }
+ throw new IllegalArgumentException("no key specified");
this.key = key;
}
@@ -83,18 +70,13 @@ public final class PublicKeyEntry extends PrimitiveEntry
super(TYPE);
}
- // Class method.
- // ------------------------------------------------------------------------
-
public static PublicKeyEntry decode(DataInputStream in) throws IOException
{
PublicKeyEntry entry = new PublicKeyEntry();
entry.defaultDecode(in);
String type = entry.properties.get("type");
if (type == null)
- {
- throw new MalformedKeyringException("no key type");
- }
+ throw new MalformedKeyringException("no key type");
if (type.equalsIgnoreCase("RAW-DSS"))
{
IKeyPairCodec coder = KeyPairCodecFactory.getInstance("dss");
@@ -125,33 +107,23 @@ public final class PublicKeyEntry extends PrimitiveEntry
try
{
KeyFactory kf = KeyFactory.getInstance("DSA");
- entry.key = kf.generatePublic(new X509EncodedKeySpec(
- entry.payload));
+ entry.key = kf.generatePublic(new X509EncodedKeySpec(entry.payload));
}
catch (Exception x)
{
}
if (entry.key == null)
- {
- throw new MalformedKeyringException(
- "could not decode X.509 key");
- }
+ throw new MalformedKeyringException("could not decode X.509 key");
}
}
else
- {
- throw new MalformedKeyringException("unsupported public key type: "
- + type);
- }
+ throw new MalformedKeyringException("unsupported public key type: " + type);
return entry;
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
/**
* Returns the public key.
- *
+ *
* @return The public key.
*/
public PublicKey getKey()
@@ -185,8 +157,6 @@ public final class PublicKeyEntry extends PrimitiveEntry
payload = key.getEncoded();
}
else
- {
- throw new IllegalArgumentException("cannot encode public key");
- }
+ throw new IllegalArgumentException("cannot encode public key");
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/kwa/AESKeyWrap.java b/libjava/classpath/gnu/javax/crypto/kwa/AESKeyWrap.java
new file mode 100644
index 0000000..bb86c54
--- /dev/null
+++ b/libjava/classpath/gnu/javax/crypto/kwa/AESKeyWrap.java
@@ -0,0 +1,168 @@
+/* AESWrap.java -- An implementation of RFC-3394 AES Key Wrap Algorithm
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.kwa;
+
+import gnu.java.security.Registry;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.cipher.Rijndael;
+
+import java.security.InvalidKeyException;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The GNU implementation of the AES Key Wrap Algorithm as described in [1].
+ *
+ *
+ */
+public class AESKeyWrap
+ extends BaseKeyWrappingAlgorithm
+{
+ private static final byte[] DEFAULT_IV = new byte[] {
+ (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6,
+ (byte) 0xA6, (byte) 0xA6, (byte) 0xA6, (byte) 0xA6 };
+
+ private Rijndael aes;
+ private byte[] iv;
+
+ public AESKeyWrap()
+ {
+ super(Registry.AES_KWA);
+
+ aes = new Rijndael();
+ }
+
+ protected void engineInit(Map attributes) throws InvalidKeyException
+ {
+ Map cipherAttributes = new HashMap();
+ cipherAttributes.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(16));
+ cipherAttributes.put(IBlockCipher.KEY_MATERIAL,
+ attributes.get(KEY_ENCRYPTION_KEY_MATERIAL));
+ aes.reset();
+ aes.init(cipherAttributes);
+ byte[] initialValue = (byte[]) attributes.get(INITIAL_VALUE);
+ iv = initialValue == null ? DEFAULT_IV : (byte[]) initialValue.clone();
+ }
+
+ protected byte[] engineWrap(byte[] in, int inOffset, int length)
+ {
+ // TODO: handle input length which is not a multiple of 8 as suggested by
+ // section 2.2.3.2 of RFC-3394
+ if (length % 8 != 0)
+ throw new IllegalArgumentException("Input length MUST be a multiple of 8");
+ int n = length / 8;
+ // output is always one block larger than input
+ byte[] result = new byte[length + 8];
+
+ // 1. init variables: we'll use out buffer for our work buffer;
+ // A will be the first block in out, while R will be the rest
+ System.arraycopy(iv, 0, result, 0, 8);
+ System.arraycopy(in, inOffset, result, 8, length);
+ byte[] B = new byte[2 * 8];
+ // 2. compute intermediate values
+ long t;
+ for (int j = 0; j < 6; j++)
+ for (int i = 1; i <= n; i++)
+ {
+ System.arraycopy(result, 0, B, 0, 8);
+ System.arraycopy(result, i * 8, B, 8, 8);
+ aes.encryptBlock(B, 0, B, 0);
+ t = (n * j) + i;
+ result[0] = (byte)(B[0] ^ (t >>> 56));
+ result[1] = (byte)(B[1] ^ (t >>> 48));
+ result[2] = (byte)(B[2] ^ (t >>> 40));
+ result[3] = (byte)(B[3] ^ (t >>> 32));
+ result[4] = (byte)(B[4] ^ (t >>> 24));
+ result[5] = (byte)(B[5] ^ (t >>> 16));
+ result[6] = (byte)(B[6] ^ (t >>> 8));
+ result[7] = (byte)(B[7] ^ t );
+ System.arraycopy(B, 8, result, i * 8, 8);
+ }
+ return result;
+ }
+
+ protected byte[] engineUnwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException
+ {
+ // TODO: handle input length which is not a multiple of 8 as suggested by
+ // section 2.2.3.2 of RFC-3394
+ if (length % 8 != 0)
+ throw new IllegalArgumentException("Input length MUST be a multiple of 8");
+ // output is always one block shorter than input
+ byte[] result = new byte[length - 8];
+
+ // 1. init variables: we'll use out buffer for our R work buffer
+ byte[] A = new byte[8];
+ System.arraycopy(in, inOffset, A, 0, 8);
+ System.arraycopy(in, inOffset + 8, result, 0, result.length);
+ byte[] B = new byte[2 * 8];
+ // 2. compute intermediate values
+ int n = length / 8 - 1;
+ long t;
+ for (int j = 5; j >= 0; j--)
+ for (int i = n; i >= 1; i--)
+ {
+ t = (n * j) + i;
+ B[0] = (byte)(A[0] ^ (t >>> 56));
+ B[1] = (byte)(A[1] ^ (t >>> 48));
+ B[2] = (byte)(A[2] ^ (t >>> 40));
+ B[3] = (byte)(A[3] ^ (t >>> 32));
+ B[4] = (byte)(A[4] ^ (t >>> 24));
+ B[5] = (byte)(A[5] ^ (t >>> 16));
+ B[6] = (byte)(A[6] ^ (t >>> 8));
+ B[7] = (byte)(A[7] ^ t );
+ System.arraycopy(result, (i - 1) * 8, B, 8, 8);
+ aes.decryptBlock(B, 0, B, 0);
+ System.arraycopy(B, 0, A, 0, 8);
+ System.arraycopy(B, 8, result, (i - 1) * 8, 8);
+ }
+ if (! Arrays.equals(A, iv))
+ throw new KeyUnwrappingException();
+
+ return result;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/crypto/kwa/BaseKeyWrappingAlgorithm.java b/libjava/classpath/gnu/javax/crypto/kwa/BaseKeyWrappingAlgorithm.java
new file mode 100644
index 0000000..206e01d
--- /dev/null
+++ b/libjava/classpath/gnu/javax/crypto/kwa/BaseKeyWrappingAlgorithm.java
@@ -0,0 +1,145 @@
+/* BaseKeyWrappingAlgorithm.java -- FIXME: briefly describe file purpose
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.kwa;
+
+import gnu.java.security.util.PRNG;
+
+import java.security.InvalidKeyException;
+import java.util.Collections;
+import java.util.Map;
+
+import javax.crypto.ShortBufferException;
+
+/**
+ * A base class to facilitate implementation of concrete Key Wrapping
+ * Algorithms.
+ */
+public abstract class BaseKeyWrappingAlgorithm
+ implements IKeyWrappingAlgorithm
+{
+ /** The canonical name of the key wrapping algorithm. */
+ protected String name;
+ /** A source of randomness if/when needed by concrete implementations. */
+ private PRNG prng;
+
+ /**
+ * Protected constructor.
+ *
+ * @param name the key wrapping algorithm canonical name.
+ */
+ protected BaseKeyWrappingAlgorithm(String name)
+ {
+ super();
+ }
+
+ public String name()
+ {
+ return this.name;
+ }
+
+ public void init(Map attributes) throws InvalidKeyException
+ {
+ if (attributes == null)
+ attributes = Collections.EMPTY_MAP;
+
+ engineInit(attributes);
+ }
+
+ public int wrap(byte[] in, int inOffset, int length, byte[] out, int outOffset)
+ throws ShortBufferException
+ {
+ if (outOffset < 0)
+ throw new IllegalArgumentException("Output offset MUST NOT be negative");
+ byte[] result = wrap(in, inOffset, length);
+ if (outOffset + result.length > out.length)
+ throw new ShortBufferException();
+ System.arraycopy(result, 0, out, outOffset, result.length);
+ return result.length;
+ }
+
+ public byte[] wrap(byte[] in, int inOffset, int length)
+ {
+ if (inOffset < 0)
+ throw new IllegalArgumentException("Input offset MUST NOT be negative");
+ if (length < 0)
+ throw new IllegalArgumentException("Input length MUST NOT be negative");
+
+ return engineWrap(in, inOffset, length);
+ }
+
+ public int unwrap(byte[] in, int inOffset, int length,
+ byte[] out, int outOffset)
+ throws ShortBufferException, KeyUnwrappingException
+ {
+ if (outOffset < 0)
+ throw new IllegalArgumentException("Output offset MUST NOT be negative");
+ byte[] result = engineUnwrap(in, inOffset, length);
+ if (outOffset + result.length > out.length)
+ throw new ShortBufferException();
+ System.arraycopy(result, 0, out, outOffset, result.length);
+ return result.length;
+ }
+
+ public byte[] unwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException
+ {
+ if (inOffset < 0)
+ throw new IllegalArgumentException("Input offset MUST NOT be negative");
+ if (length < 0)
+ throw new IllegalArgumentException("Input length MUST NOT be negative");
+
+ return engineUnwrap(in, inOffset, length);
+ }
+
+ protected abstract void engineInit(Map attributes) throws InvalidKeyException;
+
+ protected abstract byte[] engineWrap(byte[] in, int inOffset, int length);
+
+ protected abstract byte[] engineUnwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException;
+
+ /** @return a strong pseudo-random number generator if/when needed. */
+ protected PRNG getDefaultPRNG()
+ {
+ if (prng == null)
+ prng = PRNG.getInstance();
+
+ return prng;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/crypto/kwa/IKeyWrappingAlgorithm.java b/libjava/classpath/gnu/javax/crypto/kwa/IKeyWrappingAlgorithm.java
new file mode 100644
index 0000000..d9c2bed
--- /dev/null
+++ b/libjava/classpath/gnu/javax/crypto/kwa/IKeyWrappingAlgorithm.java
@@ -0,0 +1,160 @@
+/* IKeyWrappingAlgorithm.java -- FIXME: briefly describe file purpose
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.kwa;
+
+import java.security.InvalidKeyException;
+import java.security.SecureRandom;
+import java.util.Map;
+
+import javax.crypto.ShortBufferException;
+
+/**
+ * Constants and visible methods available to all GNU Key Wrapping Algorithm
+ * implementations.
+ */
+public interface IKeyWrappingAlgorithm
+{
+ /**
+ * Name of the property, in the attributes map, that references the Key
+ * Wrapping Algorithm KEK (Key Encryption Key) material. The object referenced
+ * by this property is a byte array containing the keying material for the
+ * underlying block cipher.
+ */
+ String KEY_ENCRYPTION_KEY_MATERIAL = "gnu.crypto.kwa.kek";
+ /**
+ * Name of the property, in the attributes map, that references the Initial
+ * Value (IV) material. The object referenced by this property is a byte array
+ * containing the initial integrity check register value.
+ */
+ String INITIAL_VALUE = "gnu.crypto.kwa.iv";
+ /**
+ * Property name of an optional {@link SecureRandom} instance to use. The
+ * default is to use a {@link gnu.java.security.util.PRNG} instance.
+ */
+ String SOURCE_OF_RANDOMNESS = "gnu.crypto.kwa.prng";
+
+ /**
+ * Returns the canonical name of this Key Wrapping Algorithm.
+ *
+ * @return the canonical name of this Key Wrapping Algorithm.
+ */
+ String name();
+
+ /**
+ * Initializes this instance with the designated algorithm specific
+ * attributes.
+ *
+ * @param attributes a map of name-to-value pairs the Key Wrapping Algorithm
+ * must use for its setup.
+ * @throws InvalidKeyException if an exception is encountered while seting up
+ * the Key Wrapping Algorithm keying material (KEK).
+ */
+ void init(Map attributes) throws InvalidKeyException;
+
+ /**
+ * Wraps the designated plain text bytes.
+ *
+ * @param in the input byte array containing the plain text.
+ * @param inOffset the offset into in
where the first byte of
+ * the plain text (key material) to wrap is located.
+ * @param length the number of bytes to wrap.
+ * @param out the output byte array where the wrapped key material will be
+ * stored.
+ * @param outOffset the offset into out
of the first wrapped
+ * byte.
+ * @return the number of bytes of the wrapped key material; i.e. the length,
+ * in out
, starting from outOffset
+ * where the cipher text (wrapped key material) are stored.
+ * @throws ShortBufferException if the output buffer is not long enough to
+ * accomodate the number of bytes resulting from wrapping the plain
+ * text.
+ */
+ int wrap(byte[] in, int inOffset, int length, byte[] out, int outOffset)
+ throws ShortBufferException;
+
+ /**
+ * Wraps the designated plain text bytes.
+ *
+ * @param in the input byte array containing the plain text.
+ * @param inOffset the offset into in
where the first byte of
+ * the plain text (key material) to wrap is located.
+ * @param length the number of bytes to wrap.
+ * @return a newly allocated byte array containing the cipher text.
+ */
+ byte[] wrap(byte[] in, int inOffset, int length);
+
+ /**
+ * Unwraps the designated cipher text bytes.
+ *
+ * @param in the input byte array containing the cipher text.
+ * @param inOffset the offset into in
where the first byte of
+ * the cipher text (already wrapped key material) to unwrap is
+ * located.
+ * @param length the number of bytes to unwrap.
+ * @param out the output byte array where the unwrapped key material will be
+ * stored.
+ * @param outOffset the offset into out
of the first unwrapped
+ * byte.
+ * @return the number of bytes of the unwrapped key material; i.e. the length,
+ * in out
, starting from outOffset
+ * where the plain text (unwrapped key material) are stored.
+ * @throws ShortBufferException if the output buffer is not long enough to
+ * accomodate the number of bytes resulting from unwrapping the
+ * cipher text.
+ * @throws KeyUnwrappingException if after unwrapping the cipher text, the
+ * bytes at the begining did not match the initial value.
+ */
+ int unwrap(byte[] in, int inOffset, int length, byte[] out, int outOffset)
+ throws ShortBufferException, KeyUnwrappingException;
+
+ /**
+ * Unwraps the designated cipher text bytes.
+ *
+ * @param in the input byte array containing the cipher text.
+ * @param inOffset the offset into in
where the first byte of
+ * the cipher text (already wrapped key material) to unwrap is
+ * located.
+ * @param length the number of bytes to unwrap.
+ * @return a newly allocated byte array containing the plain text.
+ * @throws KeyUnwrappingException if after unwrapping the cipher text, the
+ * bytes at the begining did not match the initial value.
+ */
+ byte[] unwrap(byte[] in, int inOffset, int length)
+ throws KeyUnwrappingException;
+}
diff --git a/libjava/classpath/gnu/javax/crypto/kwa/KeyUnwrappingException.java b/libjava/classpath/gnu/javax/crypto/kwa/KeyUnwrappingException.java
new file mode 100644
index 0000000..54b4aff
--- /dev/null
+++ b/libjava/classpath/gnu/javax/crypto/kwa/KeyUnwrappingException.java
@@ -0,0 +1,67 @@
+/* KeyUnwrappingException.java -- FIXME: briefly describe file purpose
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.kwa;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * A checked security exception to denote an unexpected problem while unwrapping
+ * key material with a Key Wrapping Algorithm.
+ */
+public class KeyUnwrappingException
+ extends GeneralSecurityException
+{
+ /**
+ * Create a new instance with no descriptive error message.
+ */
+ public KeyUnwrappingException()
+ {
+ super();
+ }
+
+ /**
+ * Create a new instance with a descriptive error message.
+ *
+ * @param msg the descriptive error message
+ */
+ public KeyUnwrappingException(String msg)
+ {
+ super(msg);
+ }
+}
diff --git a/libjava/classpath/gnu/javax/crypto/kwa/KeyWrappingAlgorithmFactory.java b/libjava/classpath/gnu/javax/crypto/kwa/KeyWrappingAlgorithmFactory.java
new file mode 100644
index 0000000..6f6cd12
--- /dev/null
+++ b/libjava/classpath/gnu/javax/crypto/kwa/KeyWrappingAlgorithmFactory.java
@@ -0,0 +1,110 @@
+/* KeyWrappingAlgorithmFactory.java -- FIXME: briefly describe file purpose
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.kwa;
+
+import gnu.java.security.Registry;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A Factory class for the Key Wrapping Algorithm implementations.
+ */
+public class KeyWrappingAlgorithmFactory
+{
+ /** Names of Key Wrapping Algorihms cached for speed. */
+ private static Set names;
+
+ /** Trivial constructor to enforce Singleton pattern. */
+ private KeyWrappingAlgorithmFactory()
+ {
+ super();
+ }
+
+ /**
+ * Returns an instance of a key-wrapping algorithm given its name.
+ *
+ * @param name the case-insensitive name of the key-wrapping algorithm.
+ * @return an instance of the designated key-wrapping algorithm, or
+ * null
if none was found.
+ * @exception InternalError if the implementation does not pass its self-test.
+ */
+ public static final IKeyWrappingAlgorithm getInstance(String name)
+ {
+ if (name == null)
+ return null;
+ name = name.trim();
+ IKeyWrappingAlgorithm result = null;
+ if (name.equalsIgnoreCase(Registry.AES_KWA)
+ || name.equalsIgnoreCase(Registry.AES128_KWA)
+ || name.equalsIgnoreCase(Registry.AES192_KWA)
+ || name.equalsIgnoreCase(Registry.AES256_KWA)
+ || name.equalsIgnoreCase(Registry.RIJNDAEL_KWA))
+ result = new AESKeyWrap();
+ else if (name.equalsIgnoreCase(Registry.TRIPLEDES_KWA)
+ || name.equalsIgnoreCase(Registry.DESEDE_KWA))
+ result = new TripleDESKeyWrap();
+
+ return result;
+ }
+
+ /**
+ * Returns a {@link Set} of key wrapping algorithm names supported by this
+ * Factory.
+ *
+ * @return a {@link Set} of key wrapping algorithm names (Strings).
+ */
+ public static synchronized final Set getNames()
+ {
+ if (names == null)
+ {
+ HashSet hs = new HashSet();
+ hs.add(Registry.AES_KWA);
+ hs.add(Registry.AES128_KWA);
+ hs.add(Registry.AES192_KWA);
+ hs.add(Registry.AES256_KWA);
+ hs.add(Registry.RIJNDAEL_KWA);
+ hs.add(Registry.TRIPLEDES_KWA);
+ hs.add(Registry.DESEDE_KWA);
+ names = Collections.unmodifiableSet(hs);
+ }
+ return names;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/crypto/kwa/TripleDESKeyWrap.java b/libjava/classpath/gnu/javax/crypto/kwa/TripleDESKeyWrap.java
new file mode 100644
index 0000000..71562bd
--- /dev/null
+++ b/libjava/classpath/gnu/javax/crypto/kwa/TripleDESKeyWrap.java
@@ -0,0 +1,292 @@
+/* TripleDESKeyWrap.java -- FIXME: briefly describe file purpose
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.kwa;
+
+import gnu.java.security.Registry;
+import gnu.java.security.hash.Sha160;
+import gnu.javax.crypto.assembly.Assembly;
+import gnu.javax.crypto.assembly.Cascade;
+import gnu.javax.crypto.assembly.Direction;
+import gnu.javax.crypto.assembly.Stage;
+import gnu.javax.crypto.assembly.Transformer;
+import gnu.javax.crypto.assembly.TransformerException;
+import gnu.javax.crypto.cipher.IBlockCipher;
+import gnu.javax.crypto.cipher.TripleDES;
+import gnu.javax.crypto.mode.IMode;
+import gnu.javax.crypto.mode.ModeFactory;
+
+import java.security.InvalidKeyException;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The GNU implementation of the Triple DES Key Wrap Algorithm as described in
+ * [1].
+ *
- *
- *
- *
- *
*/
-public class HMac extends BaseMac implements Cloneable
+public class HMac
+ extends BaseMac
+ implements Cloneable
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String USE_WITH_PKCS5_V2 = "gnu.crypto.hmac.pkcs5";
-
private static final byte IPAD_BYTE = 0x36;
-
private static final byte OPAD_BYTE = 0x5C;
-
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
-
protected int macSize;
-
protected int blockSize;
-
protected IMessageDigest ipadHash;
-
protected IMessageDigest opadHash;
-
protected byte[] ipad;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/**
- *
- * H. Krawczyk, M. Bellare, and R. Canetti.
+ * H. Krawczyk, M. Bellare, and R. Canetti.null
if
- * none can be constructed.
+ * as the concatenation of a literal prefix (see
+ * {@link Registry#HMAC_NAME_PREFIX}) and the name of the underlying
+ * hash algorithm.
+ * @return an instance of the HMAC algorithm, or null
+ * if none can be constructed.
* @exception InternalError if the implementation does not pass its self-test.
*/
public static IMac getInstance(String name)
{
if (name == null)
- {
- return null;
- }
+ return null;
name = name.trim();
name = name.toLowerCase();
- if (!name.startsWith(HMAC_NAME_PREFIX))
- {
- return null;
- }
+ if (! name.startsWith(HMAC_NAME_PREFIX))
+ return null;
// strip the prefix
name = name.substring(HMAC_NAME_PREFIX.length()).trim();
IMac result = new HMac(HashFactory.getInstance(name));
- if (result != null && !result.selfTest())
- {
- throw new InternalError(result.name());
- }
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
return result;
}
/**
- *
- *
- *
- *
- *
*/
public interface IMac
{
-
- // Constants
- // -------------------------------------------------------------------------
-
/**
* Property name of the user-supplied key material. The value associated to
* this property name is taken to be a byte array.
*/
String MAC_KEY_MATERIAL = "gnu.crypto.mac.key.material";
-
/**
- *
- * H. Krawczyk, M. Bellare, and R. Canetti.
- * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.
+ * H. Krawczyk, M. Bellare, and R. Canetti.
+ * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.
- * We recommend that the output length t be not less than half the
- * length of the hash output (to match the birthday attack bound)
- * and not less than 80 bits (a suitable lower bound on the number
- * of bits that need to be predicted by an attacker).
+ * We recommend that the output length t be not less than half the
+ * length of the hash output (to match the birthday attack bound)
+ * and not less than 80 bits (a suitable lower bound on the number
+ * of bits that need to be predicted by an attacker).
*
*/
String TRUNCATED_SIZE = "gnu.crypto.mac.truncated.size";
- // Methods
- // -------------------------------------------------------------------------
-
/**
- * true
if the implementation passes a basic self-test.
- * Returns false
otherwise.
+ * Returns false
otherwise.
*/
boolean selfTest();
/**
- * null
if
- * none can be constructed.
+ * none can be constructed.
* @exception InternalError if the implementation does not pass its self-test.
*/
public static IMac getInstance(String name)
{
if (name == null)
- {
- return null;
- }
+ return null;
name = name.trim();
name = name.toLowerCase();
if (name.startsWith(HMAC_NAME_PREFIX))
- {
- return HMacFactory.getInstance(name);
- }
+ return HMacFactory.getInstance(name);
if (name.startsWith(OMAC_PREFIX))
{
name = name.substring(OMAC_PREFIX.length());
IBlockCipher cipher = CipherFactory.getInstance(name);
if (cipher == null)
- {
- return null;
- }
+ return null;
return new OMAC(cipher);
}
-
IMac result = null;
if (name.equalsIgnoreCase(UHASH32))
- {
- result = new UHash32();
- }
+ result = new UHash32();
else if (name.equalsIgnoreCase(UMAC32))
- {
- result = new UMac32();
- }
+ result = new UMac32();
else if (name.equalsIgnoreCase(TMMH16))
- {
- result = new TMMH16();
- }
- // else if (name.equalsIgnoreCase(TMMH32)) {
- // result = new TMMH32();
- // }
+ result = new TMMH16();
- if (result != null && !result.selfTest())
- {
- throw new InternalError(result.name());
- }
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
return result;
}
/**
- * MacOutputStream
. The stream is initially set
+ * Creates a new MacOutputStream
. The stream is initially set
* to digest data written, the mac
argument must have already
- * been initialized, and the mac
argument is not cloned.mac
argument is not
+ * cloned.
+ *
* @param out The underlying output stream.
* @param mac The mac instance to use.
*/
@@ -73,19 +67,14 @@ public class MacOutputStream extends FilterOutputStream
{
super(out);
if (mac == null)
- {
- throw new NullPointerException();
- }
+ throw new NullPointerException();
this.mac = mac;
digesting = true;
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
- *
*
*/
-public class OMAC implements IMac
+public class OMAC
+ implements IMac
{
-
- // Constants and fields.
- // ------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
-
- private static void debug(String msg)
- {
- System.out.print(">>> OMAC: ");
- System.out.println(msg);
- }
-
+ private static final Logger log = Logger.getLogger(OMAC.class.getName());
private static final byte C1 = (byte) 0x87;
-
private static final byte C2 = 0x1b;
-
// Test key for OMAC-AES-128
- private static final byte[] KEY0 = Util.toBytesFromString("2b7e151628aed2a6abf7158809cf4f3c");
-
+ private static final byte[] KEY0 =
+ Util.toBytesFromString("2b7e151628aed2a6abf7158809cf4f3c");
// Test MAC for zero-length input.
- private static final byte[] DIGEST0 = Util.toBytesFromString("bb1d6929e95937287fa37d129b756746");
-
+ private static final byte[] DIGEST0 =
+ Util.toBytesFromString("bb1d6929e95937287fa37d129b756746");
private static Boolean valid;
-
private final IBlockCipher cipher;
-
private final String name;
-
private IMode mode;
-
private int blockSize;
-
private int outputSize;
-
private byte[] Lu, Lu2;
-
private byte[] M;
-
private byte[] Y;
-
private boolean init;
-
private int index;
- // Constructor.
- // ------------------------------------------------------------------------
-
public OMAC(IBlockCipher cipher)
{
this.cipher = cipher;
this.name = "OMAC-" + cipher.name();
}
- // Instance methods.
- // ------------------------------------------------------------------------
-
public Object clone()
{
return new OMAC(cipher);
@@ -141,135 +113,89 @@ public class OMAC implements IMac
attrib2.put(IBlockCipher.KEY_MATERIAL, attrib.get(MAC_KEY_MATERIAL));
cipher.reset();
cipher.init(attrib2);
-
blockSize = cipher.currentBlockSize();
Integer os = (Integer) attrib.get(TRUNCATED_SIZE);
if (os != null)
{
outputSize = os.intValue();
if (outputSize < 0 || outputSize > blockSize)
- {
- throw new IllegalArgumentException("truncated size out of range");
- }
+ throw new IllegalArgumentException("truncated size out of range");
}
else
- {
- outputSize = blockSize;
- }
+ outputSize = blockSize;
byte[] L = new byte[blockSize];
cipher.encryptBlock(L, 0, L, 0);
-
- if (DEBUG)
- {
- debug("L = " + Util.toString(L).toLowerCase());
- }
-
+ if (Configuration.DEBUG)
+ log.fine("L = " + Util.toString(L).toLowerCase());
if (Lu != null)
{
Arrays.fill(Lu, (byte) 0);
if (Lu.length != blockSize)
- {
- Lu = new byte[blockSize];
- }
+ Lu = new byte[blockSize];
}
else
- {
- Lu = new byte[blockSize];
- }
+ Lu = new byte[blockSize];
if (Lu2 != null)
{
Arrays.fill(Lu2, (byte) 0);
if (Lu2.length != blockSize)
- {
- Lu2 = new byte[blockSize];
- }
+ Lu2 = new byte[blockSize];
}
else
- {
- Lu2 = new byte[blockSize];
- }
+ Lu2 = new byte[blockSize];
boolean msb = (L[0] & 0x80) != 0;
for (int i = 0; i < blockSize; i++)
{
- Lu[i] = (byte) (L[i] << 1 & 0xFF);
+ Lu[i] = (byte)(L[i] << 1 & 0xFF);
if (i + 1 < blockSize)
- {
- Lu[i] |= (byte) ((L[i + 1] & 0x80) >> 7);
- }
+ Lu[i] |= (byte)((L[i + 1] & 0x80) >> 7);
}
if (msb)
{
if (blockSize == 16)
- {
- Lu[Lu.length - 1] ^= C1;
- }
+ Lu[Lu.length - 1] ^= C1;
else if (blockSize == 8)
- {
- Lu[Lu.length - 1] ^= C2;
- }
+ Lu[Lu.length - 1] ^= C2;
else
- {
- throw new IllegalArgumentException(
- "unsupported cipher block size: "
- + blockSize);
- }
- }
- if (DEBUG)
- {
- debug("Lu = " + Util.toString(Lu).toLowerCase());
+ throw new IllegalArgumentException("unsupported cipher block size: "
+ + blockSize);
}
-
+ if (Configuration.DEBUG)
+ log.fine("Lu = " + Util.toString(Lu).toLowerCase());
msb = (Lu[0] & 0x80) != 0;
for (int i = 0; i < blockSize; i++)
{
- Lu2[i] = (byte) (Lu[i] << 1 & 0xFF);
+ Lu2[i] = (byte)(Lu[i] << 1 & 0xFF);
if (i + 1 < blockSize)
- {
- Lu2[i] |= (byte) ((Lu[i + 1] & 0x80) >> 7);
- }
+ Lu2[i] |= (byte)((Lu[i + 1] & 0x80) >> 7);
}
if (msb)
{
if (blockSize == 16)
- {
- Lu2[Lu2.length - 1] ^= C1;
- }
+ Lu2[Lu2.length - 1] ^= C1;
else
- {
- Lu2[Lu2.length - 1] ^= C2;
- }
- }
- if (DEBUG)
- {
- debug("Lu2 = " + Util.toString(Lu2).toLowerCase());
+ Lu2[Lu2.length - 1] ^= C2;
}
-
+ if (Configuration.DEBUG)
+ log.fine("Lu2 = " + Util.toString(Lu2).toLowerCase());
if (M != null)
{
Arrays.fill(M, (byte) 0);
if (M.length != blockSize)
- {
- M = new byte[blockSize];
- }
+ M = new byte[blockSize];
}
else
- {
- M = new byte[blockSize];
- }
+ M = new byte[blockSize];
if (Y != null)
{
Arrays.fill(Y, (byte) 0);
if (Y.length != blockSize)
- {
- Y = new byte[blockSize];
- }
+ Y = new byte[blockSize];
}
else
- {
- Y = new byte[blockSize];
- }
+ Y = new byte[blockSize];
index = 0;
init = true;
@@ -277,10 +203,8 @@ public class OMAC implements IMac
public void update(byte b)
{
- if (!init)
- {
- throw new IllegalStateException("not initialized");
- }
+ if (! init)
+ throw new IllegalStateException("not initialized");
if (index == M.length)
{
process();
@@ -291,15 +215,11 @@ public class OMAC implements IMac
public void update(byte[] buf, int off, int len)
{
- if (!init)
- {
- throw new IllegalStateException("not initialized");
- }
+ if (! init)
+ throw new IllegalStateException("not initialized");
if (off < 0 || len < 0 || off + len > buf.length)
- {
- throw new IndexOutOfBoundsException("size=" + buf.length + "; off="
- + off + "; len=" + len);
- }
+ throw new IndexOutOfBoundsException("size=" + buf.length + "; off=" + off
+ + "; len=" + len);
for (int i = 0; i < len;)
{
if (index == blockSize)
@@ -323,30 +243,22 @@ public class OMAC implements IMac
public void digest(byte[] out, int off)
{
- if (!init)
- {
- throw new IllegalStateException("not initialized");
- }
+ if (! init)
+ throw new IllegalStateException("not initialized");
if (off < 0 || off + outputSize > out.length)
- {
- throw new IndexOutOfBoundsException("size=" + out.length + "; off="
- + off + "; len=" + outputSize);
- }
+ throw new IndexOutOfBoundsException("size=" + out.length + "; off=" + off
+ + "; len=" + outputSize);
byte[] T = new byte[blockSize];
byte[] L = Lu;
if (index < blockSize)
{
M[index++] = (byte) 0x80;
while (index < blockSize)
- {
- M[index++] = 0;
- }
+ M[index++] = 0;
L = Lu2;
}
for (int i = 0; i < blockSize; i++)
- {
- T[i] = (byte) (M[i] ^ Y[i] ^ L[i]);
- }
+ T[i] = (byte)(M[i] ^ Y[i] ^ L[i]);
cipher.encryptBlock(T, 0, T, 0);
System.arraycopy(T, 0, out, off, outputSize);
reset();
@@ -356,13 +268,9 @@ public class OMAC implements IMac
{
index = 0;
if (Y != null)
- {
- Arrays.fill(Y, (byte) 0);
- }
+ Arrays.fill(Y, (byte) 0);
if (M != null)
- {
- Arrays.fill(M, (byte) 0);
- }
+ Arrays.fill(M, (byte) 0);
}
public boolean selfTest()
@@ -382,21 +290,14 @@ public class OMAC implements IMac
return false;
}
if (digest == null)
- {
- return false;
- }
+ return false;
return Arrays.equals(DIGEST0, digest);
}
- // Own methods.
- // ------------------------------------------------------------------------
-
private void process()
{
for (int i = 0; i < blockSize; i++)
- {
- M[i] = (byte) (M[i] ^ Y[i]);
- }
+ M[i] = (byte)(M[i] ^ Y[i]);
cipher.encryptBlock(M, 0, Y, 0);
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/mac/TMMH16.java b/libjava/classpath/gnu/javax/crypto/mac/TMMH16.java
index af6e78f..0a7b4a6 100644
--- a/libjava/classpath/gnu/javax/crypto/mac/TMMH16.java
+++ b/libjava/classpath/gnu/javax/crypto/mac/TMMH16.java
@@ -46,91 +46,63 @@ import java.security.InvalidKeyException;
import java.util.Map;
/**
- * KEY_LENGTH
,
- * MESSAGE_LENGTH
, and TAG_LENGTH
, respectively. The
- * values of KEY_LENGTH
and TAG_LENGTH
+ * MESSAGE_LENGTH
, and TAG_LENGTH
, respectively.
+ * The values of KEY_LENGTH
and TAG_LENGTH
* MAX_HASH_LENGTH
, which denotes the maximum
+ * must obey the alignment restrictions described below.
+ * MAX_HASH_LENGTH
, which denotes the maximum
* value which MESSAGE_LENGTH
may take, is equal to
- * KEY_LENGTH - TAG_LENGTH
.KEY_LENGTH - TAG_LENGTH
.
+ *
- *
*/
-public class TMMH16 extends BaseMac implements Cloneable
+public class TMMH16
+ extends BaseMac
+ implements Cloneable
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
public static final String TAG_LENGTH = "gnu.crypto.mac.tmmh.tag.length";
-
public static final String KEYSTREAM = "gnu.crypto.mac.tmmh.keystream";
-
public static final String PREFIX = "gnu.crypto.mac.tmmh.prefix";
-
private static final int P = (1 << 16) + 1; // the TMMH/16 prime
-
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
-
private int tagWords = 0; // the tagLength expressed in words
-
private IRandom keystream = null; // the keystream generator
-
private byte[] prefix; // mask to use when operating as an authentication f.
-
private long keyWords; // key words counter
-
private long msgLength; // in bytes
-
private long msgWords; // should be = msgLength * WORD_LENGTH
-
private int[] context; // the tmmh running context; length == TAG_WORDS
-
private int[] K0; // the first TAG_WORDS words of the keystream
-
private int[] Ki; // the sliding TAG_WORDS words of the keystream
-
private int Mi; // current message word being constructed
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public TMMH16()
{
super(Registry.TMMH16);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // gnu.crypto.mac.IMac interface implementation ----------------------------
-
public int macSize()
{
return tagWords * 2;
@@ -143,22 +115,17 @@ public class TMMH16 extends BaseMac implements Cloneable
Integer tagLength = (Integer) attributes.get(TAG_LENGTH); // get tag length
if (tagLength == null)
{
- if (tagWords == 0)
- { // was never set
- throw new IllegalArgumentException(TAG_LENGTH);
- } // else re-use
+ if (tagWords == 0) // was never set
+ throw new IllegalArgumentException(TAG_LENGTH);
+ // else re-use
}
- else
- { // check if positive and is divisible by WORD_LENGTH
+ else // check if positive and is divisible by WORD_LENGTH
+ {
wantTagLength = tagLength.intValue();
if (wantTagLength < 2 || (wantTagLength % 2 != 0))
- {
- throw new IllegalArgumentException(TAG_LENGTH);
- }
- else if (wantTagLength > (512 / 8))
- { // 512-bits is our maximum
- throw new IllegalArgumentException(TAG_LENGTH);
- }
+ throw new IllegalArgumentException(TAG_LENGTH);
+ else if (wantTagLength > (512 / 8)) // 512-bits is our maximum
+ throw new IllegalArgumentException(TAG_LENGTH);
tagWords = wantTagLength / 2; // init local vars
K0 = new int[tagWords];
@@ -167,36 +134,27 @@ public class TMMH16 extends BaseMac implements Cloneable
}
prefix = (byte[]) attributes.get(PREFIX);
- if (prefix == null)
- { // default to all-zeroes
- prefix = new byte[tagWords * 2];
- }
- else
- { // ensure it's as long as it should
+ if (prefix == null) // default to all-zeroes
+ prefix = new byte[tagWords * 2];
+ else // ensure it's as long as it should
+ {
if (prefix.length != tagWords * 2)
- {
- throw new IllegalArgumentException(PREFIX);
- }
+ throw new IllegalArgumentException(PREFIX);
}
IRandom prng = (IRandom) attributes.get(KEYSTREAM); // get keystream
if (prng == null)
{
if (keystream == null)
- {
- throw new IllegalArgumentException(KEYSTREAM);
- } // else reuse
+ throw new IllegalArgumentException(KEYSTREAM);
+ // else reuse
}
else
- {
- keystream = prng;
- }
+ keystream = prng;
reset(); // reset context variables
- for (int i = 0; i < tagWords; i++)
- { // init starting key words
- Ki[i] = K0[i] = getNextKeyWord(keystream);
- }
+ for (int i = 0; i < tagWords; i++) // init starting key words
+ Ki[i] = K0[i] = getNextKeyWord(keystream);
}
// The words of the key are denoted as K[1], K[2], ..., K[KEY_WORDS], and the
@@ -206,12 +164,12 @@ public class TMMH16 extends BaseMac implements Cloneable
//
// If MESSAGE_LENGTH is greater than MAX_HASH_LENGTH, then the value of
// TMMH/16 is undefined. Implementations MUST indicate an error if asked to
- // hash a message with such a length. Otherwise, the hash value is defined
+ // hash a message with such a length. Otherwise, the hash value is defined
// to be the length TAG_WORDS sequence of words in which the j-th word in the
// sequence is defined as
//
// [ [ K[j] * MESSAGE_LENGTH +32 K[j+1] * M[1] +32 K[j+2] * M[2]
- // +32 ... K[j+MSG_WORDS] * M[MSG_WORDS] ] modulo p ] modulo 2^16
+ // +32 ... K[j+MSG_WORDS] * M[MSG_WORDS] ] modulo p ] modulo 2^16
//
// where j ranges from 1 to TAG_WORDS.
public void update(byte b)
@@ -222,23 +180,21 @@ public class TMMH16 extends BaseMac implements Cloneable
public void update(byte[] b, int offset, int len)
{
for (int i = 0; i < len; i++)
- {
- this.update(b[offset + i], keystream);
- }
+ this.update(b[offset + i], keystream);
}
// For TMMH/16, KEY_LENGTH and TAG_LENGTH MUST be a multiple of two. The key,
// message, and hash value are treated as a sequence of unsigned sixteen bit
- // integers in network byte order. (In this section, we call such an integer
- // a word.) If MESSAGE_LENGTH is odd, then a zero byte is appended to the
+ // integers in network byte order. (In this section, we call such an integer
+ // a word.) If MESSAGE_LENGTH is odd, then a zero byte is appended to the
// message to align it on a word boundary, though this process does not
// change the value of MESSAGE_LENGTH.
//
- // ... Otherwise, the hash value is defined to be the length TAG_WORDS
+ // ... Otherwise, the hash value is defined to be the length TAG_WORDS
// sequence of words in which the j-th word in the sequence is defined as
//
// [ [ K[j] * MESSAGE_LENGTH +32 K[j+1] * M[1] +32 K[j+2] * M[2]
- // +32 ... K[j+MSG_WORDS] * M[MSG_WORDS] ] modulo p ] modulo 2^16
+ // +32 ... K[j+MSG_WORDS] * M[MSG_WORDS] ] modulo p ] modulo 2^16
//
// where j ranges from 1 to TAG_WORDS.
//
@@ -255,9 +211,7 @@ public class TMMH16 extends BaseMac implements Cloneable
msgLength = msgWords = keyWords = 0L;
Mi = 0;
for (int i = 0; i < tagWords; i++)
- {
- context[i] = 0;
- }
+ context[i] = 0;
}
public boolean selfTest()
@@ -265,42 +219,31 @@ public class TMMH16 extends BaseMac implements Cloneable
if (valid == null)
{
// TODO: compute and test equality with one known vector
-
valid = Boolean.TRUE;
}
return valid.booleanValue();
}
- // Cloneable interface implementation ---------------------------------------
-
public Object clone() throws CloneNotSupportedException
{
TMMH16 result = (TMMH16) super.clone();
-
if (this.keystream != null)
result.keystream = (IRandom) this.keystream.clone();
-
if (this.prefix != null)
result.prefix = (byte[]) this.prefix.clone();
-
if (this.context != null)
result.context = (int[]) this.context.clone();
-
if (this.K0 != null)
result.K0 = (int[]) this.K0.clone();
-
if (this.Ki != null)
result.Ki = (int[]) this.Ki.clone();
-
return result;
}
- // own methods -------------------------------------------------------------
-
/**
- * b
to start considering
- * the bytes to process.
+ * the bytes to process.
* @param len the number of bytes in b
starting from
- * offset
to process.
+ * offset
to process.
* @param prng the source of randomness to use.
*/
public void update(byte[] b, int offset, int len, IRandom prng)
{
for (int i = 0; i < len; i++)
- {
- this.update(b[offset + i], prng);
- }
+ this.update(b[offset + i], prng);
}
/**
- * NH
is used to compress input messages into strings which are
* typically many times smaller than the input message. Second, the compressed
* message is hashed with an optimized polynomial hash function into a
* fixed-length 16-byte string. Finally, the 16-byte string is hashed using an
- * inner-product hash into a string of length WORD-LEN bytes. These three
- * layers are repeated (with a modified key) until the outputs total
- * UMAC-OUTPUT-LEN bytes.
- *
*/
-public class UHash32 extends BaseMac
+public class UHash32
+ extends BaseMac
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
// UMAC prime values
private static final BigInteger PRIME_19 = BigInteger.valueOf(0x7FFFFL);
-
private static final BigInteger PRIME_32 = BigInteger.valueOf(0xFFFFFFFBL);
-
private static final BigInteger PRIME_36 = BigInteger.valueOf(0xFFFFFFFFBL);
-
- private static final BigInteger PRIME_64 = new BigInteger(
- 1,
- new byte[] {
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xC5 });
-
- private static final BigInteger PRIME_128 = new BigInteger(
- 1,
- new byte[] {
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0xFF,
- (byte) 0x61 });
-
+ private static final BigInteger PRIME_64 = new BigInteger(1, new byte[] {
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC5 });
+ private static final BigInteger PRIME_128 = new BigInteger(1, new byte[] {
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
+ (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0x61 });
static final BigInteger TWO = BigInteger.valueOf(2L);
-
static final long BOUNDARY = TWO.shiftLeft(17).longValue();
-
// 2**64 - 2**32
static final BigInteger LOWER_RANGE = TWO.pow(64).subtract(TWO.pow(32));
-
// 2**128 - 2**96
static final BigInteger UPPER_RANGE = TWO.pow(128).subtract(TWO.pow(96));
-
static final byte[] ALL_ZEROES = new byte[32];
-
int streams;
-
L1Hash32[] l1hash;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public UHash32()
{
@@ -155,7 +114,7 @@ public class UHash32 extends BaseMac
}
/**
- *
- * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.
+ * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.
* +-----+--------------------+---------------------------------------+
* | x | prime(x) [Decimal] | prime(x) [Hexadecimal] |
@@ -219,18 +169,11 @@ public class UHash32 extends BaseMac
}
}
- // Instance methods
- // -------------------------------------------------------------------------
-
- // java.lang.Cloneable interface implementation ----------------------------
-
public Object clone()
{
return new UHash32(this);
}
- // gnu.crypto.mac.IMac interface implementation ----------------------------
-
public int macSize()
{
return UMac32.OUTPUT_LEN;
@@ -241,18 +184,12 @@ public class UHash32 extends BaseMac
{
byte[] K = (byte[]) attributes.get(MAC_KEY_MATERIAL);
if (K == null)
- {
- throw new InvalidKeyException("Null Key");
- }
+ throw new InvalidKeyException("Null Key");
if (K.length != UMac32.KEY_LEN)
- {
- throw new InvalidKeyException("Invalid Key length: "
- + String.valueOf(K.length));
- }
-
+ throw new InvalidKeyException("Invalid Key length: "
+ + String.valueOf(K.length));
// Calculate iterations needed to make UMAC-OUTPUT-LEN bytes
streams = (UMac32.OUTPUT_LEN + 3) / 4;
-
// Define total key needed for all iterations using UMacGenerator.
// L1Key and L3Key1 both reuse most key between iterations.
IRandom kdf1 = new UMacGenerator();
@@ -261,15 +198,14 @@ public class UHash32 extends BaseMac
IRandom kdf4 = new UMacGenerator();
Map map = new HashMap();
map.put(IBlockCipher.KEY_MATERIAL, K);
- map.put(UMacGenerator.INDEX, new Integer(0));
+ map.put(UMacGenerator.INDEX, Integer.valueOf(0));
kdf1.init(map);
- map.put(UMacGenerator.INDEX, new Integer(1));
+ map.put(UMacGenerator.INDEX, Integer.valueOf(1));
kdf2.init(map);
- map.put(UMacGenerator.INDEX, new Integer(2));
+ map.put(UMacGenerator.INDEX, Integer.valueOf(2));
kdf3.init(map);
- map.put(UMacGenerator.INDEX, new Integer(3));
+ map.put(UMacGenerator.INDEX, Integer.valueOf(3));
kdf4.init(map);
-
// need to generate all bytes for use later in a Toepliz construction
byte[] L1Key = new byte[UMac32.L1_KEY_LEN + (streams - 1) * 16];
try
@@ -297,7 +233,6 @@ public class UHash32 extends BaseMac
x.printStackTrace(System.err);
throw new RuntimeException("KDF for L2Key reached limit");
}
-
byte[] k31 = new byte[64];
try
{
@@ -308,7 +243,6 @@ public class UHash32 extends BaseMac
x.printStackTrace(System.err);
throw new RuntimeException("KDF for L3Key1 reached limit");
}
-
byte[] k32 = new byte[4];
try
{
@@ -319,7 +253,6 @@ public class UHash32 extends BaseMac
x.printStackTrace(System.err);
throw new RuntimeException("KDF for L3Key2 reached limit");
}
-
L1Hash32 mac = new L1Hash32();
mac.init(k1, k2, k31, k32);
l1hash[i] = mac;
@@ -329,17 +262,13 @@ public class UHash32 extends BaseMac
public void update(byte b)
{
for (int i = 0; i < streams; i++)
- {
- l1hash[i].update(b);
- }
+ l1hash[i].update(b);
}
public void update(byte[] b, int offset, int len)
{
for (int i = 0; i < len; i++)
- {
- this.update(b[offset + i]);
- }
+ this.update(b[offset + i]);
}
public byte[] digest()
@@ -357,9 +286,7 @@ public class UHash32 extends BaseMac
public void reset()
{
for (int i = 0; i < streams; i++)
- {
- l1hash[i].reset();
- }
+ l1hash[i].reset();
}
public boolean selfTest()
@@ -367,38 +294,20 @@ public class UHash32 extends BaseMac
return true;
}
- // helper methods ----------------------------------------------------------
-
- // Inner classes
- // =========================================================================
-
/**
* First hash stage of the UHash32 algorithm.
*/
- class L1Hash32 implements Cloneable
+ class L1Hash32
+ implements Cloneable
{
-
- // Constants and variables
- // ----------------------------------------------------------------------
-
private int[] key; // key material as an array of 32-bit ints
-
private byte[] buffer; // work buffer L1_KEY_LEN long
-
private int count; // meaningful bytes in buffer
-
private ByteArrayOutputStream Y;
-
- // private byte[] y;
private long totalCount;
-
private L2Hash32 l2hash;
-
private L3Hash32 l3hash;
- // Constructor(s)
- // ----------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
L1Hash32()
{
@@ -412,7 +321,7 @@ public class UHash32 extends BaseMac
}
/**
- *
- *
*/
- class L2Hash32 implements Cloneable
+ class L2Hash32
+ implements Cloneable
{
-
- // Constants and variables
- // ----------------------------------------------------------------------
-
private BigInteger k64, k128;
-
private BigInteger y;
-
private boolean highBound;
-
private long bytesSoFar;
-
private ByteArrayOutputStream buffer;
- // Constructor(s)
- // ----------------------------------------------------------------------
-
L2Hash32(byte[] K)
{
super();
if (K.length != 24)
- {
- throw new ExceptionInInitializerError("K length is not 24");
- }
-
+ throw new ExceptionInInitializerError("K length is not 24");
// Extract keys and restrict to special key-sets
// Mask64 = uint2str(0x01FFFFFF01FFFFFF, 8);
// Mask128 = uint2str(0x01FFFFFF01FFFFFF01FFFFFF01FFFFFF, 16);
// k64 = str2uint(K[1..8] and Mask64);
// k128 = str2uint(K[9..24] and Mask128);
int i = 0;
- k64 = new BigInteger(1, new byte[] { (byte) (K[i++] & 0x01),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0x01),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF) });
- k128 = new BigInteger(1, new byte[] { (byte) (K[i++] & 0x01),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0x01),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0x01),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0x01),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF),
- (byte) (K[i++] & 0xFF) });
-
+ k64 = new BigInteger(1, new byte[] {
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF) });
+ k128 = new BigInteger(1, new byte[] {
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0x01), (byte)(K[i++] & 0xFF),
+ (byte)(K[i++] & 0xFF), (byte)(K[i++] & 0xFF) });
y = BigInteger.ONE;
highBound = false;
bytesSoFar = 0L;
@@ -694,36 +549,24 @@ public class UHash32 extends BaseMac
}
}
- // Class methods
- // ----------------------------------------------------------------------
-
- // Instance methods
- // ----------------------------------------------------------------------
-
- // java.lang.Cloneable interface implementation -------------------------
-
public Object clone()
{
return new L2Hash32(this);
}
- // other instance methods -----------------------------------------------
-
// this is called with either 8-bytes or 16-bytes
void update(byte[] b, int offset, int len)
{
if (len == 0)
- {
- return;
- }
+ return;
- if (!highBound)
- { // do the first (only?) 8-bytes
+ if (! highBound) // do the first (only?) 8-bytes
+ {
poly(64, LOWER_RANGE, k64, b, offset, 8);
bytesSoFar += 8L;
highBound = (bytesSoFar > BOUNDARY);
- if (highBound)
- { // if we just crossed the limit then process y
+ if (highBound) // if we just crossed the limit then process y
+ {
poly(128, UPPER_RANGE, k128, yTo16bytes(), 0, 16);
buffer = new ByteArrayOutputStream();
}
@@ -739,9 +582,7 @@ public class UHash32 extends BaseMac
byte[] bb = buffer.toByteArray();
poly(128, UPPER_RANGE, k128, bb, 0, 16);
if (bb.length > 16)
- {
- buffer.write(bb, 16, bb.length - 16);
- }
+ buffer.write(bb, 16, bb.length - 16);
}
}
}
@@ -751,19 +592,18 @@ public class UHash32 extends BaseMac
// If M no more than 2^17 bytes, hash under 64-bit prime,
// otherwise, hash first 2^17 bytes under 64-bit prime and
// remainder under 128-bit prime.
- if (!highBound)
- { // y is up-to-date
+ if (! highBound) // y is up-to-date
+ {
// do nothing
}
- else
- { // we may have some bytes in buffer
+ else // we may have some bytes in buffer
+ {
byte[] bb = buffer.toByteArray();
byte[] lastBlock = new byte[16];
System.arraycopy(bb, 0, lastBlock, 0, bb.length);
lastBlock[bb.length] = (byte) 0x80;
poly(128, UPPER_RANGE, k128, lastBlock, 0, 16);
}
-
byte[] result = yTo16bytes();
reset();
return result;
@@ -775,38 +615,29 @@ public class UHash32 extends BaseMac
highBound = false;
bytesSoFar = 0L;
if (buffer != null)
- {
- buffer.reset();
- }
+ buffer.reset();
}
- // helper methods -------------------------------------------------------
-
private byte[] yTo16bytes()
{
byte[] yy = y.toByteArray();
byte[] result = new byte[16];
if (yy.length > 16)
- {
- System.arraycopy(yy, yy.length - 16, result, 0, 16);
- }
+ System.arraycopy(yy, yy.length - 16, result, 0, 16);
else
- {
- System.arraycopy(yy, 0, result, 16 - yy.length, yy.length);
- }
+ System.arraycopy(yy, 0, result, 16 - yy.length, yy.length);
return result;
}
/**
- * 5.3 POLY: Polynomial hash
- * Function Name: POLY
- *
+ * 5.3 POLY: Polynomial hash Function Name: POLY
+ *
* @param wordbits positive integer divisible by 8: called with 64 or 128.
* @param maxwordrange positive integer less than 2**wordbits.
* @param k integer in the range 0 .. prime(wordbits) - 1.
- * @param M string with length divisible by (wordbits / 8) bytes.
- * return y, integer in the range 0 .. prime(wordbits) - 1.
+ * @param M string with length divisible by (wordbits / 8) bytes. return y,
+ * integer in the range 0 .. prime(wordbits) - 1.
*/
private void poly(int wordbits, BigInteger maxwordrange, BigInteger k,
byte[] M, int off, int len)
@@ -814,12 +645,9 @@ public class UHash32 extends BaseMac
byte[] mag = new byte[len];
System.arraycopy(M, off, mag, 0, len);
// Define constants used for fixing out-of-range words
- // int wordbytes = wordbits / 8;
-
BigInteger p = prime(wordbits);
BigInteger offset = TWO.pow(wordbits).subtract(p); // 2^wordbits - p;
BigInteger marker = p.subtract(BigInteger.ONE);
-
// Break M into chunks of length wordbytes bytes
// long n = M.length / wordbytes;
// Let M_1, M_2, ..., M_n be strings of length wordbytes bytes
@@ -829,48 +657,34 @@ public class UHash32 extends BaseMac
// then hash the words 'marker' and (m - offset), both in range.
// for (int i = 0; i < n; i++) {
BigInteger m = new BigInteger(1, mag);
- if (m.compareTo(maxwordrange) >= 0)
- { // m >= maxwordrange
+ if (m.compareTo(maxwordrange) >= 0) // m >= maxwordrange
+ {
y = y.multiply(k).add(marker).mod(p); // (k * y + marker) % p;
y = y.multiply(k).add(m.subtract(offset)).mod(p); // (k * y + (m - offset)) % p;
}
else
- {
- y = y.multiply(k).add(m).mod(p); // (k * y + m) % p;
- }
- // }
-
- // return y;
+ y = y.multiply(k).add(m).mod(p); // (k * y + m) % p;
}
}
- // =========================================================================
-
/**
* Third hash stage of the UHash32 algorithm.
- *
- * Input:
- * K1 string of length 64 bytes.
- * K2 string of length 4 bytes.
- * M string of length 16 bytes.
- * Returns:
- * Y, string of length 4 bytes.
+ *
- * K string of length 24 bytes.
- * M string of length less than 2^64 bytes.
- * Y, string of length 16 bytes.
+ * K string of length 24 bytes.
+ * M string of length less than 2^64 bytes.
+ * Y, string of length 16 bytes.
+ *
*/
- class L3Hash32 implements Cloneable
+ class L3Hash32
+ implements Cloneable
{
-
- // Constants and variables
- // ----------------------------------------------------------------------
-
private static final long PRIME_36 = 0x0000000FFFFFFFFBL;
-
private int[] k = new int[9];
- // Constructor(s)
- // ----------------------------------------------------------------------
-
/**
- *
* @param K1 string of length 64 bytes.
* @param K2 string of length 4 bytes.
*/
@@ -880,29 +694,26 @@ public class UHash32 extends BaseMac
// pre-conditions
if (K1.length != 64)
- {
- throw new ExceptionInInitializerError("K1 length is not 64");
- }
+ throw new ExceptionInInitializerError("K1 length is not 64");
if (K2.length != 4)
- {
- throw new ExceptionInInitializerError("K2 length is not 4");
- }
-
+ throw new ExceptionInInitializerError("K2 length is not 4");
// Break K1 into 8 chunks and convert to integers
- // int i = 0;
- // for (int j = 0; i < 8; ) {
for (int i = 0, j = 0; i < 8; i++)
{
- long kk = (K1[j++] & 0xFFL) << 56 | (K1[j++] & 0xFFL) << 48
- | (K1[j++] & 0xFFL) << 40 | (K1[j++] & 0xFFL) << 32
- | (K1[j++] & 0xFFL) << 24 | (K1[j++] & 0xFFL) << 16
- | (K1[j++] & 0xFFL) << 8 | (K1[j++] & 0xFFL);
- // k[i++] = (int)(kk % PRIME_36);
- k[i] = (int) (kk % PRIME_36);
+ long kk = (K1[j++] & 0xFFL) << 56
+ | (K1[j++] & 0xFFL) << 48
+ | (K1[j++] & 0xFFL) << 40
+ | (K1[j++] & 0xFFL) << 32
+ | (K1[j++] & 0xFFL) << 24
+ | (K1[j++] & 0xFFL) << 16
+ | (K1[j++] & 0xFFL) << 8
+ | (K1[j++] & 0xFFL);
+ k[i] = (int)(kk % PRIME_36);
}
- // k[i] = K2[0] << 24 | (K2[1] & 0xFF) << 16 | (K2[2] & 0xFF) << 8 | (K2[3] & 0xFF);
- k[8] = K2[0] << 24 | (K2[1] & 0xFF) << 16 | (K2[2] & 0xFF) << 8
- | (K2[3] & 0xFF);
+ k[8] = K2[0] << 24
+ | (K2[1] & 0xFF) << 16
+ | (K2[2] & 0xFF) << 8
+ | (K2[3] & 0xFF);
}
private L3Hash32(int[] k)
@@ -912,21 +723,11 @@ public class UHash32 extends BaseMac
this.k = k;
}
- // Class methods
- // ----------------------------------------------------------------------
-
- // Instance methods
- // ----------------------------------------------------------------------
-
- // java.lang.Cloneable interface implementation -------------------------
-
public Object clone()
{
return new L3Hash32((int[]) k.clone());
}
- // other instance methods -----------------------------------------------
-
/**
* @param M string of length 16 bytes.
* @return Y, string of length 4 bytes.
@@ -934,24 +735,24 @@ public class UHash32 extends BaseMac
byte[] digest(byte[] M)
{
if (M.length != 16)
- {
- throw new IllegalArgumentException("M length is not 16");
- }
+ throw new IllegalArgumentException("M length is not 16");
long m, y = 0L;
for (int i = 0, j = 0; i < 8; i++)
{
// Break M into 8 chunks and convert to integers
m = (M[j++] & 0xFFL) << 8 | (M[j++] & 0xFFL);
-
// Inner-product hash, extract last 32 bits and affine-translate
// y = (m_1 * k_1 + ... + m_8 * k_8) mod prime(36);
// y = y mod 2^32;
y += (m * (k[i] & 0xFFFFFFFFL)) % PRIME_36;
}
int Y = ((int) y) ^ k[8];
- return new byte[] { (byte) (Y >>> 24), (byte) (Y >>> 16),
- (byte) (Y >>> 8), (byte) Y };
+ return new byte[] {
+ (byte)(Y >>> 24),
+ (byte)(Y >>> 16),
+ (byte)(Y >>> 8),
+ (byte) Y };
}
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/mac/UMac32.java b/libjava/classpath/gnu/javax/crypto/mac/UMac32.java
index 0138888..8e913db 100644
--- a/libjava/classpath/gnu/javax/crypto/mac/UMac32.java
+++ b/libjava/classpath/gnu/javax/crypto/mac/UMac32.java
@@ -53,123 +53,105 @@ import java.util.HashMap;
import java.util.Map;
/**
- *
+ * K1 string of length 64 bytes.
+ * K2 string of length 4 bytes.
+ * M string of length 16 bytes.
+ * Y, string of length 4 bytes.Msg
, one first applies the
+ * entire message being authenticated were available at once.
+ * Msg
, one first applies the
* universal hash function, resulting in a string which is typically much
- * shorter than the original message. The pseudorandom function is applied to a
+ * shorter than the original message. The pseudorandom function is applied to a
* nonce, and the result is used in the manner of a Vernam cipher: the
* authentication tag is the xor of the output from the hash function and the
* output from the pseudorandom function. Thus, an authentication tag is
- * generated as
- * AuthTag = f(Nonce) xor h(Msg)
+ * AuthTag = f(Nonce) xor h(Msg)
*
- *
- * f
is the pseudorandom function shared between the sender
+ * f
is the pseudorandom function shared between the sender
* and the receiver, and h is a universal hash function shared by the sender and
* the receiver. In UMAC, a shared key is used to key the pseudorandom
* function f
, and then f
is used for both tag
* generation and internally to generate all of the bits needed by the universal
- * hash function.UHASH
. It
+ * hash function.
+ * UHASH
. It
* combines several software-optimized algorithms into a multi-layered
* structure. The algorithm is moderately complex. Some of this complexity comes
- * from extensive speed optimizations.
- * UMAC32
- * ------
- * WORD-LEN 4
- * UMAC-OUTPUT-LEN 8
- * L1-KEY-LEN 1024
- * UMAC-KEY-LEN 16
- * ENDIAN-FAVORITE BIG *
- * L1-OPERATIONS-SIGN UNSIGNED
+ * UMAC32
+ * ------
+ * WORD-LEN 4
+ * UMAC-OUTPUT-LEN 8
+ * L1-KEY-LEN 1024
+ * UMAC-KEY-LEN 16
+ * ENDIAN-FAVORITE BIG *
+ * L1-OPERATIONS-SIGN UNSIGNED
*
- *
- *
- *
*/
-public class UMac32 extends BaseMac
+public class UMac32
+ extends BaseMac
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
/**
* Property name of the user-supplied Nonce. The value associated to
* this property name is taken to be a byte array.
*/
public static final String NONCE_MATERIAL = "gnu.crypto.umac.nonce.material";
-
/** Known test vector. */
- // private static final String TV1 = "3E5A0E09198B0F94";
- // private static final String TV1 = "5FD764A6D3A9FD9D";
- // private static final String TV1 = "48658DE1D9A70304";
+ // private static final String TV1 = "3E5A0E09198B0F94";
+ // private static final String TV1 = "5FD764A6D3A9FD9D";
+ // private static final String TV1 = "48658DE1D9A70304";
private static final String TV1 = "455ED214A6909F20";
-
private static final BigInteger MAX_NONCE_ITERATIONS = BigInteger.ONE.shiftLeft(16 * 8);
-
// UMAC32 parameters
static final int OUTPUT_LEN = 8;
-
static final int L1_KEY_LEN = 1024;
-
static final int KEY_LEN = 16;
-
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
-
private byte[] nonce;
-
private UHash32 uhash32;
-
private BigInteger nonceReuseCount;
-
/** The authentication key for this instance. */
private transient byte[] K;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public UMac32()
{
@@ -177,8 +159,8 @@ public class UMac32 extends BaseMac
}
/**
- *
- * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.
+ * T. Krovetz, J. Black, S. Halevi, A. Hevia, H. Krawczyk, and P. Rogaway.
- *
- *
- *
- *
- *
- * init()
methods, a Mode instance would operate with
* the same block size as its underlying block cipher. As mentioned earlier,
- * the block size of the underlying block cipher itself is specified in one
- * of the method(s) available in the factory class.
- * - *Ci = EK(Pi ^ - * Ci-1
Similarly, decrypting is:
- * - *+ * The Cipher Block Chaining mode. This mode introduces feedback into the cipher + * by XORing the previous ciphertext block with the plaintext block before + * encipherment. That is, encrypting looks like this: + * + *Pi = Ci-1 ^ - * DK(Ci)
+ * Ci = EK(Piˆ Ci-1) + *+ *
+ * Similarly, decrypting is: + *
+ * Pi = Ci-1 ˆ DK(Ci) + **/ -public class CBC extends BaseMode implements Cloneable +public class CBC + extends BaseMode + implements Cloneable { - - // Constants and Variables - //------------------------------------------------------------------ - /** The last (de|en)crypted block */ private byte[] lastBlock; - /** An intermediate buffer. */ private byte[] scratch; - // Constructors - // ----------------------------------------------------------------- - /** * Package-private constructor for the factory class. - * + * * @param underlyingCipher The cipher implementation. * @param cipherBlockSize The cipher's block size. */ @@ -86,31 +81,20 @@ public class CBC extends BaseMode implements Cloneable this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize); } - // Cloneable interface implementation - // ----------------------------------------------------------------- - public Object clone() { return new CBC(this); } - // Implementation of abstract methods in BaseMode - // ----------------------------------------------------------------- - public void setup() { if (modeBlockSize != cipherBlockSize) - { - throw new IllegalArgumentException(); - } + throw new IllegalArgumentException(); scratch = new byte[cipherBlockSize]; lastBlock = new byte[cipherBlockSize]; - // lastBlock gets initialized to the initialization vector. for (int i = 0; i < lastBlock.length && i < iv.length; i++) - { - lastBlock[i] = iv[i]; - } + lastBlock[i] = iv[i]; } public void teardown() @@ -122,9 +106,7 @@ public class CBC extends BaseMode implements Cloneable public void encryptBlock(byte[] in, int i, byte[] out, int o) { for (int k = 0; k < scratch.length; k++) - { - scratch[k] = (byte) (lastBlock[k] ^ in[k + i]); - } + scratch[k] = (byte)(lastBlock[k] ^ in[k + i]); cipher.encryptBlock(scratch, 0, out, o); System.arraycopy(out, o, lastBlock, 0, cipherBlockSize); } @@ -135,9 +117,7 @@ public class CBC extends BaseMode implements Cloneable System.arraycopy(in, i, buf, 0, cipherBlockSize); cipher.decryptBlock(in, i, scratch, 0); for (int k = 0; k < scratch.length; k++) - { - out[o + k] = (byte) (lastBlock[k] ^ scratch[k]); - } + out[o + k] = (byte)(lastBlock[k] ^ scratch[k]); System.arraycopy(buf, 0, lastBlock, 0, cipherBlockSize); } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/mode/CFB.java b/libjava/classpath/gnu/javax/crypto/mode/CFB.java index fef2b63..6fc0063 100644 --- a/libjava/classpath/gnu/javax/crypto/mode/CFB.java +++ b/libjava/classpath/gnu/javax/crypto/mode/CFB.java @@ -42,58 +42,48 @@ import gnu.java.security.Registry; import gnu.javax.crypto.cipher.IBlockCipher; /** - * The cipher feedback mode. CFB mode is a stream mode that operates on - * s bit blocks, where 1 <= s <= b, if - * b is the underlying cipher's block size. Encryption is: - * -
- I[1] = IV - I[j] = LSB(b-s, I[j-1]) | C[j-1] for j = 2...n - O[j] = CIPH(K, I[j]) for j = 1,2...n - C[j] = P[j] ^ MSB(s, O[j]) for j = 1,2...n -- * - *
And decryption is:
- * -- I[1] = IV - I[j] = LSB(b-s, I[j-1]) | C[j-1] for j = 2...n - O[j] = CIPH(K, I[j]) for j = 1,2...n - P[j] = C[j] ^ MSB(s, O[j]) for j = 1,2...n -- * - *
CFB mode requires an initialization vector, which need not be kept - * secret.
- * - *References:
+ * The cipher feedback mode. CFB mode is a stream mode that operates on s + * bit blocks, where 1 <= s <= b, if b is the + * underlying cipher's block size. Encryption is: + *+ * I[1] = IV + * I[j] = LSB(b-s, I[j-1]) | C[j-1] for j = 2...n + * O[j] = CIPH(K, I[j]) for j = 1,2...n + * C[j] = P[j] ˆ MSB(s, O[j]) for j = 1,2...n + *+ *
+ * And decryption is: + *
+ * I[1] = IV + * I[j] = LSB(b-s, I[j-1]) | C[j-1] for j = 2...n + * O[j] = CIPH(K, I[j]) for j = 1,2...n + * P[j] = C[j] ˆ MSB(s, O[j]) for j = 1,2...n + *+ *
+ * CFB mode requires an initialization vector, which need not be kept secret. + *
+ * References: *
The implementation of the Counter Mode.
- * - *The algorithm steps are formally described as follows:
- * + * The implementation of the Counter Mode. + *+ * The algorithm steps are formally described as follows: + * *
- * CTR Encryption: O[j] = E(K)(T[j]); for j = 1, 2...n; - * C[j] = P[j] ^ O[j]; for j = 1, 2...n. - * CTR Decryption: O[j] = E(K)(T[j]); for j = 1, 2...n; - * P[j] = C[j] ^ O[j]; for j = 1, 2...n. + * CTR Encryption: O[j] = E(K)(T[j]); for j = 1, 2...n; + * C[j] = P[j] ˆ O[j]; for j = 1, 2...n. + * CTR Decryption: O[j] = E(K)(T[j]); for j = 1, 2...n; + * P[j] = C[j] ˆ O[j]; for j = 1, 2...n. *- * - *
where P
is the plaintext, C
is the ciphertext,
+ *
+ *
+ * where P
is the plaintext, C
is the ciphertext,
* E(K)
is the underlying block cipher encryption function
- * parametrised with the session key K
, and T
is the
- * Counter.
This implementation, uses a standard incrementing function with a step of - * 1, and an initial value similar to that described in the NIST document.
- * - *References:
- * + * parametrised with the session keyK
, and T
is
+ * the Counter.
+ * + * This implementation, uses a standard incrementing function with a step of 1, + * and an initial value similar to that described in the NIST document. + *
+ * References: *
Trivial package-private constructor for use by the Factory class.
- * + * Trivial package-private constructor for use by the Factory class. + * * @param underlyingCipher the underlying cipher implementation. * @param cipherBlockSize the underlying cipher block size to use. */ @@ -102,8 +93,8 @@ public class CTR extends BaseMode implements Cloneable } /** - *Private constructor for cloning purposes.
- * + * Private constructor for cloning purposes. + * * @param that the instance to clone. */ private CTR(CTR that) @@ -111,61 +102,31 @@ public class CTR extends BaseMode implements Cloneable this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize); } - // Class methods - // ------------------------------------------------------------------------- - - // Cloneable interface implementation - // ------------------------------------------------------------------------- - public Object clone() { return new CTR(this); } - // Implementation of abstract methods in BaseMode - // ------------------------------------------------------------------------- - public void setup() { if (modeBlockSize > cipherBlockSize) - { - throw new IllegalArgumentException( - "mode size exceeds cipher block size"); - } + throw new IllegalArgumentException("mode size exceeds cipher block size"); off = 0; counter = new byte[cipherBlockSize]; int i = cipherBlockSize - 1; int j = iv.length - 1; while (i >= 0 && j >= 0) - { - counter[i--] = iv[j--]; - } + counter[i--] = iv[j--]; enc = new byte[cipherBlockSize]; cipher.encryptBlock(counter, 0, enc, 0); - // if (modeBlockSize != cipherBlockSize) { - // throw new IllegalArgumentException(); - // } - - // byte[] tBytes = new byte[modeBlockSize+1]; - // tBytes[0] = (byte) 0x80; - // for (int i = 0; i < modeBlockSize; i++) { - // tBytes[i+1] = (byte)(256 - modeBlockSize + i); - // } - - // T = new BigInteger(1, tBytes); } public void teardown() { if (counter != null) - { - Arrays.fill(counter, (byte) 0); - } + Arrays.fill(counter, (byte) 0); if (enc != null) - { - Arrays.fill(enc, (byte) 0); - } - // T = null; + Arrays.fill(enc, (byte) 0); } public void encryptBlock(byte[] in, int i, byte[] out, int o) @@ -183,21 +144,11 @@ public class CTR extends BaseMode implements Cloneable return new Sequence(1, cipherBlockSize).iterator(); } - // own methods - // ------------------------------------------------------------------------- - private void ctr(byte[] in, int inOffset, byte[] out, int outOffset) { - // T = T.add(BigInteger.ONE); - // byte[] O = T.toByteArray(); - // int ndx = O.length - modeBlockSize; - // cipher.encryptBlock(O, ndx, O, ndx); - // for (int i = 0; i < modeBlockSize; i++) { - // out[outOffset++] = (byte)(in[inOffset++] ^ O[ndx++]); - // } for (int i = 0; i < modeBlockSize; i++) { - out[outOffset++] = (byte) (in[inOffset++] ^ enc[off++]); + out[outOffset++] = (byte)(in[inOffset++] ^ enc[off++]); if (off == cipherBlockSize) { int j; @@ -205,17 +156,13 @@ public class CTR extends BaseMode implements Cloneable { counter[j]++; if ((counter[j] & 0xFF) != 0) - { - break; - } + break; } if (j == 0) - { - counter[cipherBlockSize - 1]++; - } + counter[cipherBlockSize - 1]++; off = 0; cipher.encryptBlock(counter, 0, enc, 0); } } } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/mode/EAX.java b/libjava/classpath/gnu/javax/crypto/mode/EAX.java index bf26098..401616b 100644 --- a/libjava/classpath/gnu/javax/crypto/mode/EAX.java +++ b/libjava/classpath/gnu/javax/crypto/mode/EAX.java @@ -39,13 +39,11 @@ exception statement from your version. */ package gnu.javax.crypto.mode; import gnu.java.security.Registry; - import gnu.javax.crypto.cipher.IBlockCipher; import gnu.javax.crypto.mac.IMac; import gnu.javax.crypto.mac.MacFactory; import java.security.InvalidKeyException; - import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -53,64 +51,48 @@ import java.util.Iterator; import java.util.Map; /** - *A conventional two-pass authenticated-encrypted mode, EAX. EAX is a + * A conventional two-pass authenticated-encrypted mode, EAX. EAX is a * Authenticated Encryption with Additional Data (AEAD) scheme, * which provides protection and authentication for the message, and provides * authentication of an (optional) header. EAX is composed of the counter mode * (CTR) and the one-key CBC MAC (OMAC). - * - *
This class makes full use of the {@link IAuthenticatedMode} interface, - * that is, all methods of both {@link IMode} and {@link IMac} can be used - * as specified in the {@link IAuthenticatedMode} interface. - * - *
References:
+ *+ * This class makes full use of the {@link IAuthenticatedMode} interface, that + * is, all methods of both {@link IMode} and {@link IMac} can be used as + * specified in the {@link IAuthenticatedMode} interface. + *
+ * References: *
The implementation of the Electronic Codebook mode.
- * - *The Electronic Codebook (ECB) mode is a confidentiality mode that is - * defined as follows:
- * + * The implementation of the Electronic Codebook mode. + *+ * The Electronic Codebook (ECB) mode is a confidentiality mode that is defined + * as follows: *
In ECB encryption, the forward cipher function is applied directly, and + *
+ * In ECB encryption, the forward cipher function is applied directly, and * independently, to each block of the plaintext. The resulting sequence of - * output blocks is the ciphertext.
- * - *In ECB decryption, the inverse cipher function is applied directly, and + * output blocks is the ciphertext. + *
+ * In ECB decryption, the inverse cipher function is applied directly, and * independently, to each block of the ciphertext. The resulting sequence of - * output blocks is the plaintext.
- * - *References:
- * + * output blocks is the plaintext. + *+ * References: *
Trivial package-private constructor for use by the Factory class.
- * + * Trivial package-private constructor for use by the Factory class. + * * @param underlyingCipher the underlying cipher implementation. * @param cipherBlockSize the underlying cipher block size to use. */ @@ -89,8 +85,8 @@ public class ECB extends BaseMode implements Cloneable } /** - *Private constructor for cloning purposes.
- * + * Private constructor for cloning purposes. + * * @param that the mode to clone. */ private ECB(ECB that) @@ -98,27 +94,15 @@ public class ECB extends BaseMode implements Cloneable this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // java.lang.Cloneable interface implementation ---------------------------- - public Object clone() { return new ECB(this); } - // Implementation of abstract methods in BaseMode -------------------------- - public void setup() { if (modeBlockSize != cipherBlockSize) - { - throw new IllegalArgumentException(IMode.MODE_BLOCK_SIZE); - } + throw new IllegalArgumentException(IMode.MODE_BLOCK_SIZE); } public void teardown() @@ -134,4 +118,4 @@ public class ECB extends BaseMode implements Cloneable { cipher.decryptBlock(in, i, out, o); } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/mode/IAuthenticatedMode.java b/libjava/classpath/gnu/javax/crypto/mode/IAuthenticatedMode.java index 989e3ed..703679d 100644 --- a/libjava/classpath/gnu/javax/crypto/mode/IAuthenticatedMode.java +++ b/libjava/classpath/gnu/javax/crypto/mode/IAuthenticatedMode.java @@ -43,16 +43,14 @@ import gnu.javax.crypto.mac.IMac; /** * The interface for encryption modes that also produce a message authentication * tag. - * - *This interface is merely the conjuction of the {@link IMode} and - * {@link IMac} interfaces. Encryption and decryption is done via the - * {@link IMode#update(byte[],int,byte[],int)} method, tag generation - * is done via the {@link IMac#digest()} method, and header updating - * (if supported by the mode) is done via the {@link - * IMac#update(byte[],int,int)} method. + *
+ * This interface is merely the conjuction of the {@link IMode} and {@link IMac} + * interfaces. Encryption and decryption is done via the + * {@link IMode#update(byte[],int,byte[],int)} method, tag generation is done + * via the {@link IMac#digest()} method, and header updating (if supported by + * the mode) is done via the {@link IMac#update(byte[],int,int)} method. */ -public interface IAuthenticatedMode extends IMode, IMac +public interface IAuthenticatedMode + extends IMode, IMac { - - // Trivial conjunction of IMode and IMac. } diff --git a/libjava/classpath/gnu/javax/crypto/mode/ICM.java b/libjava/classpath/gnu/javax/crypto/mode/ICM.java index d37908b..833ddb1 100644 --- a/libjava/classpath/gnu/javax/crypto/mode/ICM.java +++ b/libjava/classpath/gnu/javax/crypto/mode/ICM.java @@ -44,75 +44,66 @@ import gnu.javax.crypto.cipher.IBlockCipher; import java.math.BigInteger; /** - *
An implementation of David McGrew Integer Counter Mode (ICM) as an - * {@link IMode}.
- * - *ICM is a way to define a pseudorandom keystream generator using a block - * cipher. The keystream can be used for additive encryption, key derivation, - * or any other application requiring pseudorandom data. In the case of this - * class, it is used as additive encryption, XOR-ing the keystream with the - * input text --for both encryption and decryption.
- * - *In ICM, the keystream is logically broken into segments. Each segment is + * An implementation of David McGrew Integer Counter Mode (ICM) as an + * {@link IMode}. + *
+ * ICM is a way to define a pseudorandom keystream generator using a block + * cipher. The keystream can be used for additive encryption, key derivation, or + * any other application requiring pseudorandom data. In the case of this class, + * it is used as additive encryption, XOR-ing the keystream with the input text + * --for both encryption and decryption. + *
+ * In ICM, the keystream is logically broken into segments. Each segment is * identified with a segment index, and the segments have equal lengths. This * segmentation makes ICM especially appropriate for securing packet-based * protocols. ICM also allows a variety of configurations based, among other - * things, on two parameters: the block index length and the - * segment index length. A constraint on those two values exists: The sum - * of segment index length and block index length must not - * half the block size of the underlying cipher. This requirement protects - * the ICM keystream generator from potentially failing to be pseudorandom.
- * - *For simplicity, this implementation, fixes these two values to the - * following:
- * + * things, on two parameters: the block index length and the segment + * index length. A constraint on those two values exists: The sum of + * segment index length and block index length must not + * half the block size of the underlying cipher. This requirement + * protects the ICM keystream generator from potentially failing to be + * pseudorandom. + *+ * For simplicity, this implementation, fixes these two values to the following: *
For a 128-bit block cipher, the above values imply a maximum keystream
- * length of 295,147,905,179,352,825,856 octets, since in ICM, each segment must
- * not exceed the value (256 ^ block index length) * block length
- * octets.
Finally, for this implementation of the ICM, the IV placeholder will be - * used to pass the value of the Offset in the keystream segment.
- * - *References:
- * + *
+ * For a 128-bit block cipher, the above values imply a maximum keystream length
+ * of 295,147,905,179,352,825,856 octets, since in ICM, each segment must not
+ * exceed the value
+ * (256 ^ block index length) * block length
+ * octets.
+ *
+ * Finally, for this implementation of the ICM, the IV placeholder will be used + * to pass the value of the Offset in the keystream segment. + *
+ * References: *
Trivial package-private constructor for use by the Factory class.
- * + * Trivial package-private constructor for use by the Factory class. + * * @param underlyingCipher the underlying cipher implementation. * @param cipherBlockSize the underlying cipher block size to use. */ @@ -122,8 +113,8 @@ public class ICM extends BaseMode implements Cloneable } /** - *Private constructor for cloning purposes.
- * + * Private constructor for cloning purposes. + * * @param that the instance to clone. */ private ICM(ICM that) @@ -131,27 +122,15 @@ public class ICM extends BaseMode implements Cloneable this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize); } - // Class methods - // ------------------------------------------------------------------------- - - // Cloneable interface implementation - // ------------------------------------------------------------------------- - public Object clone() { return new ICM(this); } - // Implementation of abstract methods in BaseMode - // ------------------------------------------------------------------------- - public void setup() { if (modeBlockSize != cipherBlockSize) - { - throw new IllegalArgumentException(); - } - + throw new IllegalArgumentException(); counterRange = TWO_FIFTY_SIX.pow(cipherBlockSize); maxBlocksPerSegment = TWO_FIFTY_SIX.pow(cipherBlockSize / 2); BigInteger r = new BigInteger(1, iv); @@ -177,35 +156,13 @@ public class ICM extends BaseMode implements Cloneable icm(in, i, out, o); } - // Instance methods - // ------------------------------------------------------------------------- - private void icm(byte[] in, int inOffset, byte[] out, int outOffset) { if (blockNdx.compareTo(maxBlocksPerSegment) >= 0) throw new RuntimeException("Maximum blocks for segment reached"); - - // encrypt the counter for the current blockNdx - // C[i] = (C[0] + i) modulo (256^BLOCK_LENGTH). - BigInteger Ci = C0.add(blockNdx).modPow(BigInteger.ONE, counterRange); byte[] result = Ci.toByteArray(); int limit = result.length; - // if (limit < cipherBlockSize) { - // byte[] data = new byte[cipherBlockSize]; - // System.arraycopy(result, 0, data, cipherBlockSize-limit, limit); - // result = data; - // } else if (limit > cipherBlockSize) { - // byte[] data = new byte[cipherBlockSize]; - // System.arraycopy(result, limit-cipherBlockSize, data, 0, cipherBlockSize); - // result = data; - // } - // - // cipher.encryptBlock(result, 0, result, 0); - // blockNdx = blockNdx.add(BigInteger.ONE); // increment blockNdx - // for (int i = 0; i < modeBlockSize; ) { // xor result with input block - // out[outOffset++] = (byte)(in[inOffset++] ^ result[i++]); - // } int ndx = 0; if (limit < cipherBlockSize) { @@ -214,15 +171,11 @@ public class ICM extends BaseMode implements Cloneable result = data; } else if (limit > cipherBlockSize) - { - ndx = limit - cipherBlockSize; - } + ndx = limit - cipherBlockSize; cipher.encryptBlock(result, ndx, result, ndx); blockNdx = blockNdx.add(BigInteger.ONE); // increment blockNdx - for (int i = 0; i < modeBlockSize; i++) - { // xor result with input block - out[outOffset++] = (byte) (in[inOffset++] ^ result[ndx++]); - } + for (int i = 0; i < modeBlockSize; i++) // xor result with input block + out[outOffset++] = (byte)(in[inOffset++] ^ result[ndx++]); } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/mode/IMode.java b/libjava/classpath/gnu/javax/crypto/mode/IMode.java index 4cb6ca6..30485117 100644 --- a/libjava/classpath/gnu/javax/crypto/mode/IMode.java +++ b/libjava/classpath/gnu/javax/crypto/mode/IMode.java @@ -41,105 +41,83 @@ package gnu.javax.crypto.mode; import gnu.javax.crypto.cipher.IBlockCipher; /** - *
The basic visible methods of any block cipher mode.
- * - *Block ciphers encrypt plaintext in fixed size n-bit blocks. For messages + * The basic visible methods of any block cipher mode. + *
+ * Block ciphers encrypt plaintext in fixed size n-bit blocks. For messages * larger than n bits, the simplest approach is to segment the message into * n-bit blocks and process (encrypt and/or decrypt) each one separately * (Electronic Codebook or ECB mode). But this approach has disadvantages in * most applications. The block cipher modes of operations are one way of - * working around those disadvantages.
- * - *A Mode always employs an underlying block cipher for processing its + * working around those disadvantages. + *
+ * A Mode always employs an underlying block cipher for processing its * input. For all intents and purposes, a Mode appears to behave as any - * other block cipher with the following differences:
- * + * other block cipher with the following differences: *Possible additional initialisation values for an instance of that type - * are:
- * + *+ * Possible additional initialisation values for an instance of that type are: *
reset()
is invoked on the
- * instance.reset()
is invoked on the instance.Property name of the state in which to operate this mode. The value
+ * Property name of the state in which to operate this mode. The value
* associated to this property name is taken to be an {@link Integer} which
- * value is either ENCRYPTION
or DECRYPTION
.
ENCRYPTION
or DECRYPTION
.
*/
String STATE = "gnu.crypto.mode.state";
-
/**
- * Property name of the block size in which to operate this mode. The - * value associated with this property name is taken to be an {@link Integer}. - * If it is not specified, the value of the block size of the underlying - * block cipher, used to construct the mode instance, shall be used.
+ * Property name of the block size in which to operate this mode. The value + * associated with this property name is taken to be an {@link Integer}. If + * it is not specified, the value of the block size of the underlying block + * cipher, used to construct the mode instance, shall be used. */ String MODE_BLOCK_SIZE = "gnu.crypto.mode.block.size"; - /** - *Property name of the initialisation vector to use, if required, with - * this instance. The value associated with this property name is taken to - * be a byte array. If the concrete instance needs such a parameter, and it - * has not been specified as part of the initialissation parameters, an - * all-zero byte array of the appropriate size shall be used.
+ * Property name of the initialisation vector to use, if required, with this + * instance. The value associated with this property name is taken to be a + * byte array. If the concrete instance needs such a parameter, and it has not + * been specified as part of the initialissation parameters, an all-zero byte + * array of the appropriate size shall be used. */ String IV = "gnu.crypto.mode.iv"; - - /** - *Constant indicating the instance is being used for encryption.
- */ + /** Constant indicating the instance is being used for encryption. */ int ENCRYPTION = 1; - - /** - *Constant indicating the instance is being used for decryption.
- */ + /** Constant indicating the instance is being used for decryption. */ int DECRYPTION = 2; - // Methods - // ------------------------------------------------------------------------- - /** - *A convenience method. Effectively invokes the encryptBlock()
+ * A convenience method. Effectively invokes the encryptBlock()
* or decryptBlock()
method depending on the operational state
- * of the instance.
in
from which to start considering
- * data.
+ * data.
* @param out the ciphertext.
* @param outOffset index of out
from which to store result.
* @exception IllegalStateException if the instance is not initialised.
*/
void update(byte[] in, int inOffset, byte[] out, int outOffset)
throws IllegalStateException;
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/mode/ModeFactory.java b/libjava/classpath/gnu/javax/crypto/mode/ModeFactory.java
index 0e949ed..d1acdf4 100644
--- a/libjava/classpath/gnu/javax/crypto/mode/ModeFactory.java
+++ b/libjava/classpath/gnu/javax/crypto/mode/ModeFactory.java
@@ -49,16 +49,12 @@ import java.util.Iterator;
import java.util.Set;
/**
- * A Factory to instantiate block cipher modes of operations.
+ * A Factory to instantiate block cipher modes of operations. */ -public class ModeFactory implements Registry +public class ModeFactory + implements Registry { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- + private static Set names; /** Trivial constructor to enforce Singleton pattern. */ private ModeFactory() @@ -66,37 +62,29 @@ public class ModeFactory implements Registry super(); } - // Class methods - // ------------------------------------------------------------------------- - /** - *Returns an instance of a block cipher mode of operations given its name - * and characteristics of the underlying block cipher.
- * + * Returns an instance of a block cipher mode of operations given its name and + * characteristics of the underlying block cipher. + * * @param mode the case-insensitive name of the mode of operations. * @param cipher the case-insensitive name of the block cipher. * @param cipherBlockSize the block size, in bytes, of the underlying cipher. * @return an instance of the block cipher algorithm, operating in a given - * mode of operations, ornull
if none found.
+ * mode of operations, or null
if none found.
* @exception InternalError if either the mode or the underlying block cipher
- * implementation does not pass its self-test.
+ * implementation does not pass its self-test.
*/
public static IMode getInstance(String mode, String cipher,
int cipherBlockSize)
{
if (mode == null || cipher == null)
- {
- return null;
- }
+ return null;
mode = mode.trim();
cipher = cipher.trim();
-
IBlockCipher cipherImpl = CipherFactory.getInstance(cipher);
if (cipherImpl == null)
- {
- return null;
- }
+ return null;
return getInstance(mode, cipherImpl, cipherBlockSize);
}
@@ -110,59 +98,36 @@ public class ModeFactory implements Registry
{
ok = (cipherBlockSize == ((Integer) it.next()).intValue());
if (ok)
- {
- break;
- }
- }
-
- if (!ok)
- {
- throw new IllegalArgumentException("cipherBlockSize");
+ break;
}
-
+ if (! ok)
+ throw new IllegalArgumentException("cipherBlockSize");
IMode result = null;
if (mode.equalsIgnoreCase(ECB_MODE))
- {
- result = new ECB(cipher, cipherBlockSize);
- }
+ result = new ECB(cipher, cipherBlockSize);
else if (mode.equalsIgnoreCase(CTR_MODE))
- {
- result = new CTR(cipher, cipherBlockSize);
- }
+ result = new CTR(cipher, cipherBlockSize);
else if (mode.equalsIgnoreCase(ICM_MODE))
- {
- result = new ICM(cipher, cipherBlockSize);
- }
+ result = new ICM(cipher, cipherBlockSize);
else if (mode.equalsIgnoreCase(OFB_MODE))
- {
- result = new OFB(cipher, cipherBlockSize);
- }
+ result = new OFB(cipher, cipherBlockSize);
else if (mode.equalsIgnoreCase(CBC_MODE))
- {
- result = new CBC(cipher, cipherBlockSize);
- }
+ result = new CBC(cipher, cipherBlockSize);
else if (mode.equalsIgnoreCase(CFB_MODE))
- {
- result = new CFB(cipher, cipherBlockSize);
- }
+ result = new CFB(cipher, cipherBlockSize);
else if (mode.equalsIgnoreCase(EAX_MODE))
- {
- result = new EAX(cipher, cipherBlockSize);
- }
+ result = new EAX(cipher, cipherBlockSize);
- if (result != null && !result.selfTest())
- {
- throw new InternalError(result.name());
- }
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
return result;
}
/**
- * Returns a {@link java.util.Set} of names of mode supported by this - * Factory.
- * - * @return a {@link java.util.Set} of mode names (Strings). + * Returns a {@link Set} of names of mode supported by this Factory. + * + * @return a {@link Set} of mode names (Strings). */ public static final Set getNames() { @@ -178,15 +143,9 @@ public class ModeFactory implements Registry hs.add(CBC_MODE); hs.add(CFB_MODE); hs.add(EAX_MODE); - names = Collections.unmodifiableSet(hs); } } return names; } - - private static Set names; - - // Instance methods - // ------------------------------------------------------------------------- -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/mode/OFB.java b/libjava/classpath/gnu/javax/crypto/mode/OFB.java index 68065d1..c8b6d7e 100644 --- a/libjava/classpath/gnu/javax/crypto/mode/OFB.java +++ b/libjava/classpath/gnu/javax/crypto/mode/OFB.java @@ -39,33 +39,33 @@ exception statement from your version. */ package gnu.javax.crypto.mode; import gnu.java.security.Registry; - import gnu.javax.crypto.cipher.IBlockCipher; /** - *The Output Feedback (OFB) mode is a confidentiality mode that requires a
+ * The Output Feedback (OFB) mode is a confidentiality mode that requires a
* unique IV
for every message that is ever encrypted under the
- * given key. The OFB mode is defined as follows:
In OFB encryption, the IV
is transformed by the forward
- * cipher function to produce the first output block. The first output block is
+ *
+ *
+ * In OFB encryption, the IV
is transformed by the forward cipher
+ * function to produce the first output block. The first output block is
* exclusive-ORed with the first plaintext block to produce the first ciphertext
* block. The first output block is then transformed by the forward cipher
* function to produce the second output block. The second output block is
@@ -74,9 +74,9 @@ import gnu.javax.crypto.cipher.IBlockCipher;
* cipher function to produce the third output block. Thus, the successive
* output blocks are produced from enciphering the previous output blocks, and
* the output blocks are exclusive-ORed with the corresponding plaintext blocks
- * to produce the ciphertext blocks.
In OFB decryption, the IV
is transformed by the forward cipher
+ * to produce the ciphertext blocks.
+ *
+ * In OFB decryption, the IV
is transformed by the forward cipher
* function to produce the first output block. The first output block is
* exclusive-ORed with the first ciphertext block to recover the first plaintext
* block. The first output block is then transformed by the forward cipher
@@ -86,51 +86,46 @@ import gnu.javax.crypto.cipher.IBlockCipher;
* forward cipher function to produce the third output block. Thus, the
* successive output blocks are produced from enciphering the previous output
* blocks, and the output blocks are exclusive-ORed with the corresponding
- * ciphertext blocks to recover the plaintext blocks.
In both OFB encryption and OFB decryption, each forward cipher function + * ciphertext blocks to recover the plaintext blocks. + *
+ * In both OFB encryption and OFB decryption, each forward cipher function
* (except the first) depends on the results of the previous forward cipher
- * function; therefore, multiple forward cipher functions cannot be performed
- * in parallel. However, if the IV
is known, the output blocks can
- * be generated prior to the availability of the plaintext or ciphertext data.
The OFB mode requires a unique IV
for every message that is
+ * function; therefore, multiple forward cipher functions cannot be performed in
+ * parallel. However, if the IV
is known, the output blocks can
+ * be generated prior to the availability of the plaintext or ciphertext data.
+ *
+ * The OFB mode requires a unique IV
for every message that is
* ever encrypted under the given key. If, contrary to this requirement, the
* same IV
is used for the encryption of more than one message,
* then the confidentiality of those messages may be compromised. In particular,
* if a plaintext block of any of these messages is known, say, the jth
* plaintext block, then the jth output of the forward cipher
- * function can be determined easily from the jth ciphertext block of
- * the message. This information allows the jth plaintext block of
- * any other message that is encrypted using the same IV
to be
- * easily recovered from the jth ciphertext block of that message.
Confidentiality may similarly be compromised if any of the input blocks to
+ * function can be determined easily from the jth ciphertext block
+ * of the message. This information allows the jth plaintext block
+ * of any other message that is encrypted using the same IV
to be
+ * easily recovered from the jth ciphertext block of that message.
+ *
+ * Confidentiality may similarly be compromised if any of the input blocks to
* the forward cipher function for the encryption of a message is used as the
- * IV
for the encryption of another message under the given key.
References:
- * + *IV
for the encryption of another message under the given key.
+ * + * References: *
Trivial package-private constructor for use by the Factory class.
- * + * Trivial package-private constructor for use by the Factory class. + * * @param underlyingCipher the underlying cipher implementation. * @param cipherBlockSize the underlying cipher block size to use. */ @@ -140,8 +135,8 @@ public class OFB extends BaseMode implements Cloneable } /** - *Private constructor for cloning purposes.
- * + * Private constructor for cloning purposes. + * * @param that the mode to clone. */ private OFB(OFB that) @@ -149,28 +144,15 @@ public class OFB extends BaseMode implements Cloneable this((IBlockCipher) that.cipher.clone(), that.cipherBlockSize); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // java.lang.Cloneable interface implementation ---------------------------- - public Object clone() { return new OFB(this); } - // Implementation of abstract methods in BaseMode -------------------------- - public void setup() { if (modeBlockSize != cipherBlockSize) - { - throw new IllegalArgumentException(IMode.MODE_BLOCK_SIZE); - } - + throw new IllegalArgumentException(IMode.MODE_BLOCK_SIZE); outputBlock = (byte[]) iv.clone(); } @@ -182,13 +164,11 @@ public class OFB extends BaseMode implements Cloneable { cipher.encryptBlock(outputBlock, 0, outputBlock, 0); for (int j = 0; j < cipherBlockSize;) - { - out[o++] = (byte) (in[i++] ^ outputBlock[j++]); - } + out[o++] = (byte)(in[i++] ^ outputBlock[j++]); } public void decryptBlock(byte[] in, int i, byte[] out, int o) { this.encryptBlock(in, i, out, o); } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/pad/BasePad.java b/libjava/classpath/gnu/javax/crypto/pad/BasePad.java index 49c5d05..8b475d2 100644 --- a/libjava/classpath/gnu/javax/crypto/pad/BasePad.java +++ b/libjava/classpath/gnu/javax/crypto/pad/BasePad.java @@ -38,24 +38,24 @@ exception statement from your version. */ package gnu.javax.crypto.pad; +import gnu.java.security.Configuration; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + /** - *An abstract class to facilitate implementing padding algorithms.
+ * An abstract class to facilitate implementing padding algorithms. */ -public abstract class BasePad implements IPad +public abstract class BasePad + implements IPad { - - // Constants and variables - // ------------------------------------------------------------------------- - + private static final Logger log = Logger.getLogger(BasePad.class.getName()); /** The canonical name prefix of the padding algorithm. */ protected String name; - /** The block size, in bytes, for this instance. */ protected int blockSize; - // Constructor(s) - // ------------------------------------------------------------------------- - /** Trivial constructor for use by concrete subclasses. */ protected BasePad(final String name) { @@ -65,84 +65,122 @@ public abstract class BasePad implements IPad blockSize = -1; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // IPad interface implementation ------------------------------------------- - public String name() { final StringBuffer sb = new StringBuffer(name); if (blockSize != -1) - { - sb.append('-').append(String.valueOf(8 * blockSize)); - } + sb.append('-').append(String.valueOf(8 * blockSize)); return sb.toString(); } public void init(final int bs) throws IllegalStateException { if (blockSize != -1) - { - throw new IllegalStateException(); - } + throw new IllegalStateException(); blockSize = bs; setup(); } + /** + * Initialises the algorithm with designated attributes. Names, valid and/or + * recognisable by all concrete implementations are described in {@link IPad} + * class documentation. Other algorithm-specific attributes MUST be documented + * in the implementation class of that padding algorithm. + *
+ * For compatibility reasons, this method is not declared abstract.
+ * Furthermore, and unless overridden, the default implementation will throw
+ * an {@link UnsupportedOperationException}. Concrete padding algorithms MUST
+ * override this method if they wish to offer an initialisation method that
+ * allows for other than the padding block size parameter to be specified.
+ *
+ * @param attributes a set of name-value pairs that describes the desired
+ * future behaviour of this instance.
+ * @exception IllegalStateException if the instance is already initialised.
+ * @exception IllegalArgumentException if the block size value is invalid.
+ */
+ public void init(Map attributes) throws IllegalStateException
+ {
+ throw new UnsupportedOperationException();
+ }
+
public void reset()
{
blockSize = -1;
}
+ /**
+ * A default implementation of a correctness test that exercises the padder
+ * implementation, using block sizes varying from 2 to 256 bytes.
+ *
+ * @return true
if the concrete implementation correctly unpads
+ * what it pads for all tested block sizes. Returns false
+ * if the test fails for any block size.
+ */
public boolean selfTest()
{
+ final byte[] in = new byte[1024];
+ for (int bs = 2; bs < 256; bs++)
+ if (! test1BlockSize(bs, in))
+ return false;
+ return true;
+ }
+
+ /**
+ * The basic symmetric test for a padder given a specific block size.
+ *
+ * The code ensures that the implementation is capable of unpadding what it
+ * pads.
+ *
+ * @param size the block size to test.
+ * @param buffer a work buffer. It is exposed as an argument for this method
+ * to reduce un-necessary object allocations.
+ * @return true
if the test passes; false
+ * otherwise.
+ */
+ protected boolean test1BlockSize(int size, byte[] buffer)
+ {
byte[] padBytes;
final int offset = 5;
- final int limit = 1024;
- final byte[] in = new byte[limit];
- for (int bs = 2; bs < 256; bs++)
+ final int limit = buffer.length;
+ this.init(size);
+ for (int i = 0; i < limit - offset - blockSize; i++)
{
- this.init(bs);
- for (int i = 0; i < limit - offset - blockSize; i++)
+ padBytes = pad(buffer, offset, i);
+ if (((i + padBytes.length) % blockSize) != 0)
{
- padBytes = pad(in, offset, i);
- if (((i + padBytes.length) % blockSize) != 0)
- {
- new RuntimeException(name()).printStackTrace(System.err);
- return false;
- }
-
- System.arraycopy(padBytes, 0, in, offset + i, padBytes.length);
- try
- {
- if (padBytes.length != unpad(in, offset, i + padBytes.length))
- {
- new RuntimeException(name()).printStackTrace(System.err);
- return false;
- }
- }
- catch (WrongPaddingException x)
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "Length of padded text MUST be a multiple of "
+ + blockSize, new RuntimeException(name()));
+ return false;
+ }
+ System.arraycopy(padBytes, 0, buffer, offset + i, padBytes.length);
+ try
+ {
+ if (padBytes.length != unpad(buffer, offset, i + padBytes.length))
{
- x.printStackTrace(System.err);
+ if (Configuration.DEBUG)
+ log.log(Level.SEVERE,
+ "IPad [" + name() + "] failed symmetric operation",
+ new RuntimeException(name()));
return false;
}
}
- this.reset();
+ catch (WrongPaddingException x)
+ {
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "test1BlockSize", x);
+ return false;
+ }
}
-
+ this.reset();
return true;
}
- // abstract methods to implement by subclasses -----------------------------
-
/**
- *
If any additional checks or resource setup must be done by the - * subclass, then this is the hook for it. This method will be called before - * the {@link #init(int)} method returns.
+ * If any additional checks or resource setup must be done by the subclass, + * then this is the hook for it. This method will be called before the + * {@link #init(int)} method returns. */ public abstract void setup(); @@ -150,4 +188,4 @@ public abstract class BasePad implements IPad public abstract int unpad(byte[] in, int off, int len) throws WrongPaddingException; -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/pad/IPad.java b/libjava/classpath/gnu/javax/crypto/pad/IPad.java index 4b4c925..0e3db7d 100644 --- a/libjava/classpath/gnu/javax/crypto/pad/IPad.java +++ b/libjava/classpath/gnu/javax/crypto/pad/IPad.java @@ -38,29 +38,32 @@ exception statement from your version. */ package gnu.javax.crypto.pad; +import java.util.Map; + /** - *The basic visible methods of any padding algorithm.
- * - *Padding algorithms serve to pad and unpad byte arrays usually + * The basic visible methods, and attribute names, of every padding algorithm. + *
+ * Padding algorithms serve to pad and unpad byte arrays usually * as the last step in an encryption or respectively a decryption * operation. Their input buffers are usually those processed by instances of - * {@link gnu.crypto.mode.IMode} and/or {@link gnu.crypto.cipher.IBlockCipher}.
+ * {@link gnu.javax.crypto.mode.IMode} and/or + * {@link gnu.javax.crypto.cipher.IBlockCipher}. */ public interface IPad { - - // Constants - // ------------------------------------------------------------------------- - - // Methods - // ------------------------------------------------------------------------- + /** + * Property name of the block size in which to operate the padding algorithm. + * The value associated with this property name is taken to be a positive + * {@link Integer} greater than zero. + */ + String PADDING_BLOCK_SIZE = "gnu.crypto.pad.block.size"; /** @return the canonical name of this instance. */ String name(); /** * Initialises the padding scheme with a designated block size. - * + * * @param bs the designated block size. * @exception IllegalStateException if the instance is already initialised. * @exception IllegalArgumentException if the block size value is invalid. @@ -68,29 +71,43 @@ public interface IPad void init(int bs) throws IllegalStateException; /** + * Initialises the algorithm with designated attributes. Names, valid and/or + * recognisable by all concrete implementations are described in the class + * documentation above. Other algorithm-specific attributes MUST be documented + * in the implementation class of that padding algorithm. + * + * @param attributes a set of name-value pairs that describes the desired + * future behaviour of this instance. + * @exception IllegalStateException if the instance is already initialised. + * @exception IllegalArgumentException if the block size value is invalid. + */ + void init(Map attributes) throws IllegalStateException; + + /** * Returns the byte sequence that should be appended to the designated input. - * + * * @param in the input buffer containing the bytes to pad. * @param offset the starting index of meaningful data in in. * @param length the number of meaningful bytes in in. * @return the possibly 0-byte long sequence to be appended to the designated - * input. + * input. */ byte[] pad(byte[] in, int offset, int length); /** * Returns the number of bytes to discard from a designated input buffer. - * + * * @param in the input buffer containing the bytes to unpad. * @param offset the starting index of meaningful data in in. * @param length the number of meaningful bytes in in. * @return the number of bytes to discard, to the left of index position - * offset + length in in. In other words, if the return - * value of a successful invocation of this method is result, then - * the unpadded byte sequence will be offset + length - result bytes - * in in, starting from index position offset. + *offset + length
in in. In other words, if
+ * the return value of a successful invocation of this method is
+ * result
, then the unpadded byte sequence will be
+ * offset + length - result
bytes in in,
+ * starting from index position offset
.
* @exception WrongPaddingException if the data is not terminated with the
- * expected padding bytes.
+ * expected padding bytes.
*/
int unpad(byte[] in, int offset, int length) throws WrongPaddingException;
@@ -102,9 +119,9 @@ public interface IPad
/**
* A basic symmetric pad/unpad test.
- *
- * @return true if the implementation passes a basic symmetric
- * self-test. Returns false otherwise.
+ *
+ * @return true
if the implementation passes a basic symmetric
+ * self-test. Returns false
otherwise.
*/
boolean selfTest();
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/pad/ISO10126.java b/libjava/classpath/gnu/javax/crypto/pad/ISO10126.java
new file mode 100644
index 0000000..8e8c592
--- /dev/null
+++ b/libjava/classpath/gnu/javax/crypto/pad/ISO10126.java
@@ -0,0 +1,109 @@
+/* ISO10126.java -- An implementation of the ISO 10126-2 padding scheme
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; if not, write to the Free Software
+Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.crypto.pad;
+
+import gnu.java.security.Registry;
+import gnu.java.security.util.PRNG;
+
+/**
+ * The implementation of the ISO 10126-2 padding algorithm.
+ * + * The last byte of the padding block is the number of padding bytes, all other + * padding bytes are random. + *
+ * References: + *
A padding algorithm implementation of the EME-PKCS1-V1.5 encoding/decoding + * A padding algorithm implementation of the EME-PKCS1-V1.5 encoding/decoding * algorithm as described in section 7.2 of RFC-3447. This is effectively an * Adapter over an instance of {@link EME_PKCS1_V1_5} initialised with - * the RSA public shared modulus length (in bytes).
- * - *References:
+ * the RSA public shared modulus length (in bytes). + *+ * References: *
Trivial package-private constructor for use by the Factory class. - *
+ * Trivial package-private constructor for use by the Factory class. * - * @see gnu.crypto.pad.PadFactory + * @see PadFactory */ PKCS1_V1_5() { super(Registry.EME_PKCS1_V1_5_PAD); } - // Class methods - // ------------------------------------------------------------------------- - - // Implementation of abstract methods in BasePad - // ------------------------------------------------------------------------- - public void setup() { codec = EME_PKCS1_V1_5.getInstance(blockSize); @@ -117,10 +91,8 @@ public class PKCS1_V1_5 extends BasePad final byte[] EM = codec.encode(M); final byte[] result = new byte[blockSize - length]; System.arraycopy(EM, 0, result, 0, result.length); - if (DEBUG && debuglevel > 8) - { - debug("padding: 0x" + Util.toString(result)); - } + if (Configuration.DEBUG) + log.fine("padding: 0x" + Util.toString(result)); return result; } @@ -130,15 +102,11 @@ public class PKCS1_V1_5 extends BasePad final byte[] EM = new byte[length]; System.arraycopy(in, offset, EM, 0, length); final int result = length - codec.decode(EM).length; - if (DEBUG && debuglevel > 8) - { - debug("padding length: " + String.valueOf(result)); - } + if (Configuration.DEBUG) + log.fine("padding length: " + String.valueOf(result)); return result; } - // overloaded methods ------------------------------------------------------ - public boolean selfTest() { final int[] mLen = new int[] { 16, 20, 32, 48, 64 }; @@ -156,29 +124,33 @@ public class PKCS1_V1_5 extends BasePad p = pad(M, 0, j); if (j + p.length != blockSize) { - new RuntimeException(name()).printStackTrace(System.err); + if (Configuration.DEBUG) + log.log(Level.SEVERE, + "Length of padded text MUST be a multiple of " + + blockSize, new RuntimeException(name())); return false; } - System.arraycopy(p, 0, EM, 0, p.length); System.arraycopy(M, 0, EM, p.length, j); try { if (p.length != unpad(EM, 0, blockSize)) { - new RuntimeException(name()).printStackTrace(System.err); + if (Configuration.DEBUG) + log.log(Level.SEVERE, "Failed symmetric operation", + new RuntimeException(name())); return false; } } catch (WrongPaddingException x) { - x.printStackTrace(System.err); + if (Configuration.DEBUG) + log.throwing(this.getClass().getName(), "selfTest", x); return false; } } reset(); } - return true; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/pad/PKCS7.java b/libjava/classpath/gnu/javax/crypto/pad/PKCS7.java index 5697aff..bef1784 100644 --- a/libjava/classpath/gnu/javax/crypto/pad/PKCS7.java +++ b/libjava/classpath/gnu/javax/crypto/pad/PKCS7.java @@ -1,129 +1,98 @@ /* PKCS7.java -- - Copyright (C) 2001, 2002, 2006 Free Software Foundation, Inc. - -This file is a part of GNU Classpath. - -GNU Classpath is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or (at -your option) any later version. - -GNU Classpath is distributed in the hope that it will be useful, but -WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -General Public License for more details. - -You should have received a copy of the GNU General Public License -along with GNU Classpath; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 -USA - -Linking this library statically or dynamically with other modules is -making a combined work based on this library. Thus, the terms and -conditions of the GNU General Public License cover the whole -combination. - -As a special exception, the copyright holders of this library give you -permission to link this library with independent modules to produce an -executable, regardless of the license terms of these independent -modules, and to copy and distribute the resulting executable under -terms of your choice, provided that you also meet, for each linked -independent module, the terms and conditions of the license of that -module. An independent module is a module which is not derived from -or based on this library. If you modify this library, you may extend -this exception to your version of the library, but you are not -obligated to do so. If you do not wish to do so, delete this -exception statement from your version. */ + Copyright (C) 2001, 2002, 2006 Free Software Foundation, Inc. + + This file is a part of GNU Classpath. + + GNU Classpath is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or (at + your option) any later version. + + GNU Classpath is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with GNU Classpath; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 + USA + + Linking this library statically or dynamically with other modules is + making a combined work based on this library. Thus, the terms and + conditions of the GNU General Public License cover the whole + combination. + + As a special exception, the copyright holders of this library give you + permission to link this library with independent modules to produce an + executable, regardless of the license terms of these independent + modules, and to copy and distribute the resulting executable under + terms of your choice, provided that you also meet, for each linked + independent module, the terms and conditions of the license of that + module. An independent module is a module which is not derived from + or based on this library. If you modify this library, you may extend + this exception to your version of the library, but you are not + obligated to do so. If you do not wish to do so, delete this + exception statement from your version. */ package gnu.javax.crypto.pad; +import gnu.java.security.Configuration; import gnu.java.security.Registry; import gnu.java.security.util.Util; -import java.io.PrintWriter; +import java.util.logging.Logger; /** - *The implementation of the PKCS7 padding algorithm.
- * - *This algorithm is described for 8-byte blocks in [RFC-1423] and extended to - * block sizes of up to 256 bytes in [PKCS-7].
- * - * References:+ * This algorithm is described for 8-byte blocks in [RFC-1423] and extended to + * block sizes of up to 256 bytes in [PKCS-7]. + *
+ * References: + *
+ * Identifiers.
- * - * @see gnu.crypto.pad.PadFactory + * Trivial package-private constructor for use by the Factory class. + * + * @see PadFactory */ PKCS7() { super(Registry.PKCS7_PAD); } - // Class methods - // ------------------------------------------------------------------------- - - // Implementation of abstract methods in BasePad - // ------------------------------------------------------------------------- - public void setup() { if (blockSize < 2 || blockSize > 256) - { - throw new IllegalArgumentException(); - } + throw new IllegalArgumentException(); } public byte[] pad(byte[] in, int offset, int length) { int padLength = blockSize; if (length % blockSize != 0) - { - padLength = blockSize - length % blockSize; - } + padLength = blockSize - length % blockSize; byte[] result = new byte[padLength]; for (int i = 0; i < padLength;) - { - result[i++] = (byte) padLength; - } - - if (DEBUG && debuglevel > 8) - { - debug("padding: 0x" + Util.toString(result)); - } + result[i++] = (byte) padLength; + if (Configuration.DEBUG) + log.fine("padding: 0x" + Util.toString(result)); return result; } @@ -133,17 +102,10 @@ public final class PKCS7 extends BasePad int limit = offset + length; int result = in[limit - 1] & 0xFF; for (int i = 0; i < result; i++) - { - if (result != (in[--limit] & 0xFF)) - { - throw new WrongPaddingException(); - } - } - - if (DEBUG && debuglevel > 8) - { - debug("padding length: " + String.valueOf(result)); - } + if (result != (in[--limit] & 0xFF)) + throw new WrongPaddingException(); + if (Configuration.DEBUG) + log.fine("padding length: " + result); return result; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/pad/PadFactory.java b/libjava/classpath/gnu/javax/crypto/pad/PadFactory.java index 913d69d..eaa7811 100644 --- a/libjava/classpath/gnu/javax/crypto/pad/PadFactory.java +++ b/libjava/classpath/gnu/javax/crypto/pad/PadFactory.java @@ -45,16 +45,13 @@ import java.util.HashSet; import java.util.Set; /** - *
A Factory to instantiate padding schemes.
+ * A Factory to instantiate padding schemes. */ -public class PadFactory implements Registry +public class PadFactory + implements Registry { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- + /** Collection of padding algorithm names --cached for speed. */ + private static Set names; /** Trivial constructor to enforce Singleton pattern. */ private PadFactory() @@ -62,76 +59,62 @@ public class PadFactory implements Registry super(); } - // Class methods - // ------------------------------------------------------------------------- - /** - *Returns an instance of a padding algorithm given its name.
- * + * Returns an instance of a padding algorithm given its name. + * * @param pad the case-insensitive name of the padding algorithm. - * @return an instance of the padding algorithm, operating with a given - * block size, ornull
if none found.
+ * @return an instance of the padding algorithm, operating with a given block
+ * size, or null
if none found.
* @throws InternalError if the implementation does not pass its self-test.
*/
public static final IPad getInstance(String pad)
{
if (pad == null)
- {
- return null;
- }
+ return null;
pad = pad.trim().toLowerCase();
if (pad.endsWith("padding"))
pad = pad.substring(0, pad.length() - "padding".length());
IPad result = null;
if (pad.equals(PKCS7_PAD) || pad.equals(PKCS5_PAD))
- {
- result = new PKCS7();
- }
+ result = new PKCS7();
else if (pad.equals(TBC_PAD))
- {
- result = new TBC();
- }
+ result = new TBC();
else if (pad.equals(EME_PKCS1_V1_5_PAD))
- {
- result = new PKCS1_V1_5();
- }
+ result = new PKCS1_V1_5();
else if (pad.equals(SSL3_PAD))
- {
- result = new SSL3();
- }
+ result = new SSL3();
else if (pad.equals(TLS1_PAD))
- {
- result = new TLS1();
- }
+ result = new TLS1();
+ else if (pad.equals(ISO10126_PAD))
+ result = new ISO10126();
- if (result != null && !result.selfTest())
- {
- throw new InternalError(result.name());
- }
+ if (result != null && ! result.selfTest())
+ throw new InternalError(result.name());
return result;
}
/**
- * Returns a {@link java.util.Set} of names of padding algorithms - * supported by this Factory.
- * + * Returns a {@link Set} of names of padding algorithms supported by this + * Factory. + * * @return a {@link Set} of padding algorithm names (Strings). */ public static final Set getNames() { - HashSet hs = new HashSet(); - hs.add(PKCS5_PAD); - hs.add(PKCS7_PAD); - hs.add(TBC_PAD); - hs.add(EME_PKCS1_V1_5_PAD); - hs.add(SSL3_PAD); - hs.add(TLS1_PAD); - - return Collections.unmodifiableSet(hs); + if (names == null) + { + HashSet hs = new HashSet(); + hs.add(PKCS5_PAD); + hs.add(PKCS7_PAD); + hs.add(TBC_PAD); + hs.add(EME_PKCS1_V1_5_PAD); + hs.add(SSL3_PAD); + hs.add(TLS1_PAD); + hs.add(ISO10126_PAD); + names = Collections.unmodifiableSet(hs); + } + return names; } - - // Instance methods - // ------------------------------------------------------------------------- } diff --git a/libjava/classpath/gnu/javax/crypto/pad/SSL3.java b/libjava/classpath/gnu/javax/crypto/pad/SSL3.java index 25aeefa..78964d6 100644 --- a/libjava/classpath/gnu/javax/crypto/pad/SSL3.java +++ b/libjava/classpath/gnu/javax/crypto/pad/SSL3.java @@ -39,39 +39,31 @@ exception statement from your version. */ package gnu.javax.crypto.pad; /** - * The padding scheme used by the Secure Sockets Layer, version 3. This - * padding scheme is used in the block-ciphered struct, e.g.: - * + * The padding scheme used by the Secure Sockets Layer, version 3. This padding + * scheme is used in the block-ciphered struct, e.g.: *- * block-ciphered struct { - * opaque content[SSLCompressed.length]; - * opaque MAC[CipherSpec.hash_size]; - * uint8 padding[GenericBlockCipher.padding_length]; - * uint8 padding_length; - * } GenericBlockCipher; + * block-ciphered struct { + * opaque content[SSLCompressed.length]; + * opaque MAC[CipherSpec.hash_size]; + * uint8 padding[GenericBlockCipher.padding_length]; + * uint8 padding_length; + * } GenericBlockCipher; *- * - *
Where padding_length is cipher_block_size - - * ((SSLCompressed.length + CipherSpec.hash_size) - * % cipher_block_size) - 1. That is, the padding is enough bytes - * to make the plaintext a multiple of the block size minus one, plus one - * additional byte for the padding length. The padding can be any arbitrary - * data.
+ *+ * Where padding_length is cipher_block_size - + * ((SSLCompressed.length + CipherSpec.hash_size) % + * cipher_block_size) - 1. That is, the padding is enough bytes to make + * the plaintext a multiple of the block size minus one, plus one additional + * byte for the padding length. The padding can be any arbitrary data. */ -public class SSL3 extends BasePad +public class SSL3 + extends BasePad { - - // Constructors. - // ------------------------------------------------------------------------- - public SSL3() { super("ssl3"); } - // Instance methods. - // ------------------------------------------------------------------------- - public void setup() { if (blockSize <= 0 || blockSize > 255) @@ -83,7 +75,7 @@ public class SSL3 extends BasePad int padlen = blockSize - (len % blockSize); byte[] pad = new byte[padlen]; for (int i = 0; i < padlen; i++) - pad[i] = (byte) (padlen - 1); + pad[i] = (byte)(padlen - 1); return pad; } @@ -95,4 +87,4 @@ public class SSL3 extends BasePad throw new WrongPaddingException(); return padlen + 1; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/pad/TBC.java b/libjava/classpath/gnu/javax/crypto/pad/TBC.java index 25c3e42..e5ff4b5 100644 --- a/libjava/classpath/gnu/javax/crypto/pad/TBC.java +++ b/libjava/classpath/gnu/javax/crypto/pad/TBC.java @@ -38,95 +38,63 @@ exception statement from your version. */ package gnu.javax.crypto.pad; +import gnu.java.security.Configuration; import gnu.java.security.Registry; import gnu.java.security.util.Util; -import java.io.PrintWriter; +import java.util.logging.Logger; /** - *
The implementation of the Trailing Bit Complement (TBC) padding algorithm.
- * - *In this mode, "...the data string is padded at the trailing end with the + * The implementation of the Trailing Bit Complement (TBC) padding algorithm. + *
+ * In this mode, "...the data string is padded at the trailing end with the * complement of the trailing bit of the unpadded message: if the trailing bit - * is 1, then 0 bits are appended, and if the trailing bit is - * 0, then 1 bits are appended. As few bits are added as are - * necessary to meet the formatting size requirement."
- * - * References:+ * is 1, then 0 bits are appended, and if the trailing + * bit is 0, then 1 bits are appended. As few bits are + * added as are necessary to meet the formatting size requirement." + *
+ * References: + *
- * - * @see gnu.crypto.pad.PadFactory + * Trivial package-private constructor for use by the Factory class. + * + * @see PadFactory */ TBC() { super(Registry.TBC_PAD); } - // Class methods - // ------------------------------------------------------------------------- - - // Implementation of abstract methods in BasePad - // ------------------------------------------------------------------------- - public void setup() { if (blockSize < 1 || blockSize > 256) - { - throw new IllegalArgumentException(); - } + throw new IllegalArgumentException(); } public byte[] pad(byte[] in, int offset, int length) { int padLength = blockSize; if (length % blockSize != 0) - { - padLength = blockSize - length % blockSize; - } + padLength = blockSize - length % blockSize; byte[] result = new byte[padLength]; int lastBit = in[offset + length - 1] & 0x01; if (lastBit == 0) - { - for (int i = 0; i < padLength;) - { - result[i++] = 0x01; - } - } // else it's already set to zeroes by virtue of initialisation - - if (DEBUG && debuglevel > 8) - { - debug("padding: 0x" + Util.toString(result)); - } + for (int i = 0; i < padLength;) + result[i++] = 0x01; + // else it's already set to zeroes by virtue of initialisation + if (Configuration.DEBUG) + log.fine("padding: 0x" + Util.toString(result)); return result; } @@ -141,16 +109,10 @@ public final class TBC extends BasePad result++; limit--; } - if (result > length) - { - throw new WrongPaddingException(); - } - - if (DEBUG && debuglevel > 8) - { - debug("padding length: " + String.valueOf(result)); - } + throw new WrongPaddingException(); + if (Configuration.DEBUG) + log.fine("padding length: " + result); return result; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/pad/TLS1.java b/libjava/classpath/gnu/javax/crypto/pad/TLS1.java index 00a538f..1d690dd 100644 --- a/libjava/classpath/gnu/javax/crypto/pad/TLS1.java +++ b/libjava/classpath/gnu/javax/crypto/pad/TLS1.java @@ -38,42 +38,32 @@ exception statement from your version. */ package gnu.javax.crypto.pad; -import gnu.java.security.util.Util; - /** - * The padding scheme used by the Transport Layer Security protocol, - * version 1. This padding scheme is used in the block-ciphered struct, - * e.g.: - * + * The padding scheme used by the Transport Layer Security protocol, version 1. + * This padding scheme is used in the block-ciphered struct, e.g.: *
- * block-ciphered struct { - * opaque content[TLSCompressed.length]; - * opaque MAC[CipherSpec.hash_size]; - * uint8 padding[GenericBlockCipher.padding_length]; - * uint8 padding_length; - * } GenericBlockCipher; + * block-ciphered struct { + * opaque content[TLSCompressed.length]; + * opaque MAC[CipherSpec.hash_size]; + * uint8 padding[GenericBlockCipher.padding_length]; + * uint8 padding_length; + * } GenericBlockCipher; *- * - *
Where padding_length is any multiple of cipher_block_size - - * ((SSLCompressed.length + CipherSpec.hash_size) - * % cipher_block_size) - 1 that is less than 255. Every byte of the + *
+ * Where padding_length is any multiple of cipher_block_size - + * ((SSLCompressed.length + CipherSpec.hash_size) % + * cipher_block_size) - 1 that is less than 255. Every byte of the * padding must be equal to padding_length. That is, the end of the - * plaintext is n + 1 copies of the unsigned byte n.
+ * plaintext is n + 1 copies of the unsigned byte n. */ -public class TLS1 extends BasePad +public class TLS1 + extends BasePad { - - // Constructors. - // ------------------------------------------------------------------------- - public TLS1() { super("tls1"); } - // Instance methods. - // ------------------------------------------------------------------------- - public void setup() { if (blockSize <= 0 || blockSize > 255) @@ -85,9 +75,7 @@ public class TLS1 extends BasePad int padlen = blockSize - (len % blockSize); byte[] pad = new byte[padlen]; for (int i = 0; i < padlen; i++) - { - pad[i] = (byte) (padlen - 1); - } + pad[i] = (byte)(padlen - 1); return pad; } @@ -96,10 +84,8 @@ public class TLS1 extends BasePad { int padlen = in[off + len - 1] & 0xFF; for (int i = off + (len - padlen - 1); i < off + len - 1; i++) - { - if ((in[i] & 0xFF) != padlen) - throw new WrongPaddingException(); - } + if ((in[i] & 0xFF) != padlen) + throw new WrongPaddingException(); return padlen + 1; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/pad/WrongPaddingException.java b/libjava/classpath/gnu/javax/crypto/pad/WrongPaddingException.java index e477cf3..090d021 100644 --- a/libjava/classpath/gnu/javax/crypto/pad/WrongPaddingException.java +++ b/libjava/classpath/gnu/javax/crypto/pad/WrongPaddingException.java @@ -39,23 +39,10 @@ exception statement from your version. */ package gnu.javax.crypto.pad; /** - *A checked exception that indicates that a padding algorithm did not find the - * expected padding bytes when unpadding some data.
+ * A checked exception that indicates that a padding algorithm did not find the + * expected padding bytes when unpadding some data. */ -public class WrongPaddingException extends Exception +public class WrongPaddingException + extends Exception { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - - // implicit 0-arguments constructor - - // Class methods - // ------------------------------------------------------------------------- - - // Instant methods - // ------------------------------------------------------------------------- } diff --git a/libjava/classpath/gnu/javax/crypto/prng/ARCFour.java b/libjava/classpath/gnu/javax/crypto/prng/ARCFour.java index 22316ec..b726529 100644 --- a/libjava/classpath/gnu/javax/crypto/prng/ARCFour.java +++ b/libjava/classpath/gnu/javax/crypto/prng/ARCFour.java @@ -45,88 +45,65 @@ import gnu.java.security.prng.LimitReachedException; import java.util.Map; /** - * RC4 is a stream cipher developed by Ron Rivest. Until 1994 RC4 was a - * trade secret of RSA Data Security, Inc., when it was released - * anonymously to a mailing list. This version is a descendent of that - * code, and since there is no proof that the leaked version was in fact - * RC4 and because "RC4" is a trademark, it is called "ARCFOUR", short for - * "Allegedly RC4". - * - *This class only implements the keystream of ARCFOUR. To use - * this as a stream cipher, one would say:
- * - *out = in ^ arcfour.nextByte();- * - *
This operation works for encryption and decryption.
- * - *References:
- * + * RC4 is a stream cipher developed by Ron Rivest. Until 1994 RC4 was a trade + * secret of RSA Data Security, Inc., when it was released anonymously to a + * mailing list. This version is a descendent of that code, and since there is + * no proof that the leaked version was in fact RC4 and because "RC4" is a + * trademark, it is called "ARCFOUR", short for "Allegedly RC4". + *+ * This class only implements the keystream of ARCFOUR. To use this as a + * stream cipher, one would say: + *
+ * out = in ˆ arcfour.nextByte(); + *+ *
+ * This operation works for encryption and decryption. + *
+ * References: *
An entropy pool-based pseudo-random number generator based on the PRNG - * in Peter Gutmann's cryptlib (http://www.cs.auckland.ac.nz/~pgut001/cryptlib/).
- * - *The basic properties of this generator are:
- * + * An entropy pool-based pseudo-random number generator based on the PRNG in + * Peter Gutmann's cryptlib (http://www.cs.auckland.ac.nz/~pgut001/cryptlib/). + *+ * The basic properties of this generator are: *
Create and initialize a CSPRNG instance with the "system" parameters; - * the files, URLs, programs, and {@link EntropySource} sources used by - * the instance are derived from properties set in the system {@link - * Properties}.
- * - *All properties are of the from name.N, where name + * Create and initialize a CSPRNG instance with the "system" parameters; the + * files, URLs, programs, and {@link EntropySource} sources used by the + * instance are derived from properties set in the system {@link Properties}. + *
+ * All properties are of the from name.N, where name * is the name of the source, and N is an integer (staring at 1) that - * indicates the preference number for that source.
- * - *The following vales for name are used here:
- * + * indicates the preference number for that source. + *+ * The following vales for name are used here: *
These properties are file sources, passed as the {@link #FILE_SOURCES} - * parameter of the instance. The property value is a 4-tuple formatted as:
- * + *+ * These properties are file sources, passed as the {@link #FILE_SOURCES} + * parameter of the instance. The property value is a 4-tuple formatted as: + *
*quality ; offset ; count ; path- * - *
The parameters are mapped to the parameters defined for {@link - * #FILE_SOURCES}. Leading or trailing spaces on any item are trimmed - * off.
+ * The parameters are mapped to the parameters defined for {@link + * #FILE_SOURCES}. Leading or trailing spaces on any item are trimmed off. + *
+ *These properties are URL sources, passed as the {@link #URL_SOURCES} + *
+ * These properties are URL sources, passed as the {@link #URL_SOURCES} * parameter of the instance. The property is formatted the same way as file - * sources, but the path argument must be a valid URL.
These properties are program sources, passed as the {@link - * #PROGRAM_SOURCES} parameter of the instance. This property is formatted - * the same way as file and URL sources, but the last argument is a program - * and its arguments.
+ * These properties are program sources, passed as the {@link + * #PROGRAM_SOURCES} parameter of the instance. This property is formatted the + * same way as file and URL sources, but the last argument is a program and + * its arguments. + *
+ *These properties are other sources, passed as the {@link OTHER_SOURCES} - * parameter of the instance. The property value must be the full name - * of a class that implements the {@link EntropySource} interface and has a - * public no-argument constructor.
+ * These properties are other sources, passed as the {@link #OTHER_SOURCES} + * parameter of the instance. The property value must be the full name of a + * class that implements the {@link EntropySource} interface and has a public + * no-argument constructor. + *
+ *Finally, a boolean property "gnu.crypto.csprng.blocking" can be set to - * the desired value of {@link #BLOCKING}.
- * - *An example of valid properties would be:
- * + *+ * Finally, a boolean property "gnu.crypto.csprng.blocking" can be set to the + * desired value of {@link #BLOCKING}. + *
+ * An example of valid properties would be: *
- * gnu.crypto.csprng.blocking=true - * - * gnu.crypto.csprng.file.1=75.0;0;256;/dev/random - * gnu.crypto.csprng.file.2=10.0;0;100;/home/user/file - * - * gnu.crypto.csprng.url.1=5.0;0;256;http://www.random.org/cgi-bin/randbyte?nbytes=256 - * gnu.crypto.csprng.url.2=0;256;256;http://slashdot.org/ - * - * gnu.crypto.csprng.program.1=0.5;0;10;last -n 50 - * gnu.crypto.csprng.program.2=0.5;0;10;tcpdump -c 5 - * - * gnu.crypto.csprng.other.1=foo.bar.MyEntropySource - * gnu.crypto.csprng.other.2=com.company.OtherEntropySource + * gnu.crypto.csprng.blocking=true + * + * gnu.crypto.csprng.file.1=75.0;0;256;/dev/random + * gnu.crypto.csprng.file.2=10.0;0;100;/home/user/file + * + * gnu.crypto.csprng.url.1=5.0;0;256;http://www.random.org/cgi-bin/randbyte?nbytes=256 + * gnu.crypto.csprng.url.2=0;256;256;http://slashdot.org/ + * + * gnu.crypto.csprng.program.1=0.5;0;10;last -n 50 + * gnu.crypto.csprng.program.2=0.5;0;10;tcpdump -c 5 + * + * gnu.crypto.csprng.other.1=foo.bar.MyEntropySource + * gnu.crypto.csprng.other.2=com.company.OtherEntropySource **/ public static IRandom getSystemInstance() throws ClassNotFoundException, @@ -366,70 +289,57 @@ public class CSPRNG extends BasePRNG HashMap attrib = new HashMap(); attrib.put(BLOCKING, Boolean.valueOf(getProperty(BLOCK))); String s = null; - // Get each file source "gnu.crypto.csprng.file.N". List l = new LinkedList(); for (int i = 0; (s = getProperty(FILES + i)) != null; i++) - { - try - { - l.add(parseString(s.trim())); - } - catch (NumberFormatException nfe) - { - } - } + try + { + l.add(parseString(s.trim())); + } + catch (NumberFormatException nfe) + { + } attrib.put(FILE_SOURCES, l); - l = new LinkedList(); for (int i = 0; (s = getProperty(URLS + i)) != null; i++) - { - try - { - l.add(parseURL(s.trim())); - } - catch (NumberFormatException nfe) - { - } - catch (MalformedURLException mue) - { - } - } + try + { + l.add(parseURL(s.trim())); + } + catch (NumberFormatException nfe) + { + } + catch (MalformedURLException mue) + { + } attrib.put(URL_SOURCES, l); - l = new LinkedList(); for (int i = 0; (s = getProperty(PROGS + i)) != null; i++) - { - try - { - l.add(parseString(s.trim())); - } - catch (NumberFormatException nfe) - { - } - } + try + { + l.add(parseString(s.trim())); + } + catch (NumberFormatException nfe) + { + } attrib.put(PROGRAM_SOURCES, l); - l = new LinkedList(); for (int i = 0; (s = getProperty(OTHER + i)) != null; i++) - { - try - { - Class c = Class.forName(s.trim()); - l.add(c.newInstance()); - } - catch (ClassNotFoundException cnfe) - { - } - catch (InstantiationException ie) - { - } - catch (IllegalAccessException iae) - { - } - } + try + { + Class c = Class.forName(s.trim()); + l.add(c.newInstance()); + } + catch (ClassNotFoundException cnfe) + { + } + catch (InstantiationException ie) + { + } + catch (IllegalAccessException iae) + { + } attrib.put(OTHER_SOURCES, l); - instance.init(attrib); return instance; } @@ -449,9 +359,7 @@ public class CSPRNG extends BasePRNG { StringTokenizer tok = new StringTokenizer(s, ";"); if (tok.countTokens() != 4) - { - throw new IllegalArgumentException("malformed property"); - } + throw new IllegalArgumentException("malformed property"); Double quality = new Double(tok.nextToken()); Integer offset = new Integer(tok.nextToken()); Integer length = new Integer(tok.nextToken()); @@ -464,9 +372,7 @@ public class CSPRNG extends BasePRNG { StringTokenizer tok = new StringTokenizer(s, ";"); if (tok.countTokens() != 4) - { - throw new IllegalArgumentException("malformed property"); - } + throw new IllegalArgumentException("malformed property"); Double quality = new Double(tok.nextToken()); Integer offset = new Integer(tok.nextToken()); Integer length = new Integer(tok.nextToken()); @@ -474,9 +380,6 @@ public class CSPRNG extends BasePRNG return new SimpleList(quality, offset, length, url); } - // Instance methods. - // ------------------------------------------------------------------------- - public Object clone() { return new CSPRNG(); @@ -485,34 +388,25 @@ public class CSPRNG extends BasePRNG public void setup(Map attrib) { List list = null; - - if (DEBUG) - { - debug(String.valueOf(attrib)); - } + if (Configuration.DEBUG) + log.fine("attrib=" + String.valueOf(attrib)); try { list = (List) attrib.get(FILE_SOURCES); - if (DEBUG) - { - debug(String.valueOf(list)); - } + if (Configuration.DEBUG) + log.fine("list=" + String.valueOf(list)); if (list != null) { files.clear(); for (Iterator it = list.iterator(); it.hasNext();) { List l = (List) it.next(); - if (DEBUG) - { - debug("l=" + l); - } + if (Configuration.DEBUG) + log.fine("l=" + l); if (l.size() != 4) { - if (DEBUG) - { - debug("file list too small: " + l.size()); - } + if (Configuration.DEBUG) + log.fine("file list too small: " + l.size()); throw new IllegalArgumentException("invalid file list"); } Double quality = (Double) l.get(0); @@ -525,37 +419,27 @@ public class CSPRNG extends BasePRNG } catch (ClassCastException cce) { - if (DEBUG) - { - debug("bad file list: " + cce.getMessage()); - cce.printStackTrace(); - } + if (Configuration.DEBUG) + log.log(Level.FINE, "bad file list", cce); throw new IllegalArgumentException("invalid file list"); } - try { list = (List) attrib.get(URL_SOURCES); - if (DEBUG) - { - debug(String.valueOf(list)); - } + if (Configuration.DEBUG) + log.fine("list=" + String.valueOf(list)); if (list != null) { urls.clear(); for (Iterator it = list.iterator(); it.hasNext();) { List l = (List) it.next(); - if (DEBUG) - { - debug("l=" + l); - } + if (Configuration.DEBUG) + log.fine("l=" + l); if (l.size() != 4) { - if (DEBUG) - { - debug("URL list too small: " + l.size()); - } + if (Configuration.DEBUG) + log.fine("URL list too small: " + l.size()); throw new IllegalArgumentException("invalid URL list"); } Double quality = (Double) l.get(0); @@ -568,37 +452,27 @@ public class CSPRNG extends BasePRNG } catch (ClassCastException cce) { - if (DEBUG) - { - debug("bad URL list: " + cce.getMessage()); - cce.printStackTrace(); - } + if (Configuration.DEBUG) + log.log(Level.FINE, "bad URL list", cce); throw new IllegalArgumentException("invalid URL list"); } - try { list = (List) attrib.get(PROGRAM_SOURCES); - if (DEBUG) - { - debug(String.valueOf(list)); - } + if (Configuration.DEBUG) + log.fine("list=" + String.valueOf(list)); if (list != null) { progs.clear(); for (Iterator it = list.iterator(); it.hasNext();) { List l = (List) it.next(); - if (DEBUG) - { - debug("l=" + l); - } + if (Configuration.DEBUG) + log.fine("l=" + l); if (l.size() != 4) { - if (DEBUG) - { - debug("program list too small: " + l.size()); - } + if (Configuration.DEBUG) + log.fine("program list too small: " + l.size()); throw new IllegalArgumentException("invalid program list"); } Double quality = (Double) l.get(0); @@ -611,35 +485,25 @@ public class CSPRNG extends BasePRNG } catch (ClassCastException cce) { - if (DEBUG) - { - debug("bad program list: " + cce.getMessage()); - cce.printStackTrace(); - } + if (Configuration.DEBUG) + log.log(Level.FINE, "bad program list", cce); throw new IllegalArgumentException("invalid program list"); } - try { list = (List) attrib.get(OTHER_SOURCES); - if (DEBUG) - { - debug(String.valueOf(list)); - } + if (Configuration.DEBUG) + log.fine("list=" + String.valueOf(list)); if (list != null) { other.clear(); for (Iterator it = list.iterator(); it.hasNext();) { EntropySource src = (EntropySource) it.next(); - if (DEBUG) - { - debug("src=" + src); - } + if (Configuration.DEBUG) + log.fine("src=" + src); if (src == null) - { - throw new NullPointerException("null source in source list"); - } + throw new NullPointerException("null source in source list"); other.add(src); } } @@ -653,19 +517,14 @@ public class CSPRNG extends BasePRNG { Boolean block = (Boolean) attrib.get(BLOCKING); if (block != null) - { - blocking = block.booleanValue(); - } + blocking = block.booleanValue(); else - { - blocking = true; - } + blocking = true; } catch (ClassCastException cce) { throw new IllegalArgumentException("invalid blocking parameter"); } - poller = new Poller(files, urls, progs, other, this); try { @@ -679,27 +538,21 @@ public class CSPRNG extends BasePRNG public void fillBlock() throws LimitReachedException { - if (DEBUG) - { - debug("fillBlock"); - } + if (Configuration.DEBUG) + log.fine("fillBlock"); if (getQuality() < 100.0) { - if (DEBUG) - { - debug("doing slow poll"); - } + if (Configuration.DEBUG) + log.fine("doing slow poll"); slowPoll(); } - do { fastPoll(); mixRandomPool(); } while (mixCount < MIX_COUNT); - - if (!x917init || x917count >= X917_LIFETIME) + if (! x917init || x917count >= X917_LIFETIME) { mixRandomPool(pool); Map attr = new HashMap(); @@ -715,59 +568,45 @@ public class CSPRNG extends BasePRNG { throw new Error(ike.toString()); } - mixRandomPool(pool); generateX917(pool); mixRandomPool(pool); generateX917(pool); - if (x917init) - { - quality = 0.0; - } + quality = 0.0; x917init = true; x917count = 0; } - byte[] export = new byte[ALLOC_SIZE]; for (int i = 0; i < ALLOC_SIZE; i++) - { - export[i] = (byte) (pool[i] ^ 0xFF); - } - + export[i] = (byte)(pool[i] ^ 0xFF); mixRandomPool(); mixRandomPool(export); - generateX917(export); - for (int i = 0; i < OUTPUT_SIZE; i++) - { - buffer[i] = (byte) (export[i] ^ export[i + OUTPUT_SIZE]); - } + buffer[i] = (byte)(export[i] ^ export[i + OUTPUT_SIZE]); Arrays.fill(export, (byte) 0); } /** - * Add an array of bytes into the randomness pool. Note that this method - * will not increment the pool's quality counter (this can only be - * done via a source provided to the setup method). - * + * Add an array of bytes into the randomness pool. Note that this method will + * not increment the pool's quality counter (this can only be done via + * a source provided to the setup method). + * * @param buf The byte array. * @param off The offset from whence to start reading bytes. * @param len The number of bytes to add. * @throws ArrayIndexOutOfBoundsException If off or len are - * out of the range of buf. + * out of the range of buf. */ public synchronized void addRandomBytes(byte[] buf, int off, int len) { if (off < 0 || len < 0 || off + len > buf.length) + throw new ArrayIndexOutOfBoundsException(); + if (Configuration.DEBUG) { - throw new ArrayIndexOutOfBoundsException(); - } - if (DEBUG) - { - debug("adding random bytes:"); - debug(Util.toString(buf, off, len)); + log.fine("adding random bytes:"); + log.fine(Util.toString(buf, off, len)); } final int count = off + len; for (int i = off; i < count; i++) @@ -782,18 +621,16 @@ public class CSPRNG extends BasePRNG } /** - * Add a single random byte to the randomness pool. Note that this method - * will not increment the pool's quality counter (this can only be - * done via a source provided to the setup method). - * + * Add a single random byte to the randomness pool. Note that this method will + * not increment the pool's quality counter (this can only be done via + * a source provided to the setup method). + * * @param b The byte to add. */ public synchronized void addRandomByte(byte b) { - if (DEBUG) - { - debug("adding byte " + Integer.toHexString(b)); - } + if (Configuration.DEBUG) + log.fine("adding byte " + Integer.toHexString(b)); pool[index++] ^= b; if (index >= pool.length) { @@ -802,23 +639,14 @@ public class CSPRNG extends BasePRNG } } - // Package methods. - // ------------------------------------------------------------------------- - synchronized void addQuality(double quality) { - if (DEBUG) - { - debug("adding quality " + quality); - } + if (Configuration.DEBUG) + log.fine("adding quality " + quality); if (this.quality < 100) - { - this.quality += quality; - } - if (DEBUG) - { - debug("quality now " + this.quality); - } + this.quality += quality; + if (Configuration.DEBUG) + log.fine("quality now " + this.quality); } synchronized double getQuality() @@ -826,13 +654,10 @@ public class CSPRNG extends BasePRNG return quality; } - // Own methods. - // ------------------------------------------------------------------------- - /** - * The mix operation. This method will, for every 20-byte block in the - * random pool, hash that block, the previous 20 bytes, and the next - * 44 bytes with SHA-1, writing the result back into that block. + * The mix operation. This method will, for every 20-byte block in the random + * pool, hash that block, the previous 20 bytes, and the next 44 bytes with + * SHA-1, writing the result back into that block. */ private void mixRandomPool(byte[] buf) { @@ -841,25 +666,17 @@ public class CSPRNG extends BasePRNG { // First update the bytes [p-19..p-1]. if (i == 0) - { - hash.update(buf, buf.length - hashSize, hashSize); - } + hash.update(buf, buf.length - hashSize, hashSize); else - { - hash.update(buf, i - hashSize, hashSize); - } - + hash.update(buf, i - hashSize, hashSize); // Now the next 64 bytes. if (i + 64 < buf.length) - { - hash.update(buf, i, 64); - } + hash.update(buf, i, 64); else { hash.update(buf, i, buf.length - i); hash.update(buf, 0, 64 - (buf.length - i)); } - byte[] digest = hash.digest(); System.arraycopy(digest, 0, buf, i, hashSize); } @@ -878,28 +695,22 @@ public class CSPRNG extends BasePRNG { int copy = Math.min(buf.length - i, X917_POOL_SIZE); for (int j = 0; j < copy; j++) - { - x917pool[j] ^= pool[off + j]; - } - + x917pool[j] ^= pool[off + j]; cipher.encryptBlock(x917pool, 0, x917pool, 0); System.arraycopy(x917pool, 0, buf, off, copy); cipher.encryptBlock(x917pool, 0, x917pool, 0); - off += copy; x917count++; } } /** - * Add random data always immediately available into the random pool, such - * as the values of the eight asynchronous counters, the current time, the - * current memory usage, the calling thread name, and the current stack - * trace. - * - *
This method does not alter the quality counter, and is provided more - * to maintain randomness, not to seriously improve the current random - * state. + * Add random data always immediately available into the random pool, such as + * the values of the eight asynchronous counters, the current time, the + * current memory usage, the calling thread name, and the current stack trace. + *
+ * This method does not alter the quality counter, and is provided more to + * maintain randomness, not to seriously improve the current random state. */ private void fastPoll() { @@ -909,14 +720,12 @@ public class CSPRNG extends BasePRNG addRandomByte(b); addRandomByte((byte) System.currentTimeMillis()); addRandomByte((byte) Runtime.getRuntime().freeMemory()); - String s = Thread.currentThread().getName(); if (s != null) { byte[] buf = s.getBytes(); addRandomBytes(buf, 0, buf.length); } - ByteArrayOutputStream bout = new ByteArrayOutputStream(1024); PrintStream pout = new PrintStream(bout); Throwable t = new Throwable(); @@ -928,12 +737,10 @@ public class CSPRNG extends BasePRNG private void slowPoll() throws LimitReachedException { - if (DEBUG) - { - debug("poller is alive? " - + (pollerThread == null ? false : pollerThread.isAlive())); - } - if (pollerThread == null || !pollerThread.isAlive()) + if (Configuration.DEBUG) + log.fine("poller is alive? " + + (pollerThread == null ? false : pollerThread.isAlive())); + if (pollerThread == null || ! pollerThread.isAlive()) { boolean interrupted = false; pollerThread = new Thread(poller); @@ -941,27 +748,21 @@ public class CSPRNG extends BasePRNG pollerThread.setPriority(Thread.NORM_PRIORITY - 1); pollerThread.start(); if (blocking) - { - try - { - pollerThread.join(); - } - catch (InterruptedException ie) - { - interrupted = true; - } - } - + try + { + pollerThread.join(); + } + catch (InterruptedException ie) + { + interrupted = true; + } // If the full slow poll has completed after we waited for it, // and there in insufficient randomness, throw an exception. - if (!interrupted && blocking && quality < 100.0) + if (! interrupted && blocking && quality < 100.0) { - if (DEBUG) - { - debug("insufficient quality: " + quality); - } - throw new LimitReachedException( - "insufficient randomness was polled"); + if (Configuration.DEBUG) + log.fine("insufficient quality: " + quality); + throw new LimitReachedException("insufficient randomness was polled"); } } } @@ -979,33 +780,21 @@ public class CSPRNG extends BasePRNG Arrays.fill(buffer, (byte) 0); } - // Inner classes. - // ------------------------------------------------------------------------- - /** - * A simple thread that constantly updates a byte counter. This class is - * used in a group of lowest-priority threads and the values of their - * counters (updated in competition with all other threads) is used as a - * source of entropy bits. + * A simple thread that constantly updates a byte counter. This class is used + * in a group of lowest-priority threads and the values of their counters + * (updated in competition with all other threads) is used as a source of + * entropy bits. */ - private static class Spinner implements Runnable + private static class Spinner + implements Runnable { - - // Field. - // ----------------------------------------------------------------------- - - private byte counter; - - // Constructor. - // ----------------------------------------------------------------------- + protected byte counter; private Spinner() { } - // Instance methods. - // ----------------------------------------------------------------------- - public void run() { while (true) @@ -1022,27 +811,16 @@ public class CSPRNG extends BasePRNG } } - private final class Poller implements Runnable + private final class Poller + implements Runnable { - - // Fields. - // ----------------------------------------------------------------------- - private final List files; - private final List urls; - private final List progs; - private final List other; - private final CSPRNG pool; - private boolean running; - // Constructor. - // ----------------------------------------------------------------------- - Poller(List files, List urls, List progs, List other, CSPRNG pool) { super(); @@ -1053,17 +831,14 @@ public class CSPRNG extends BasePRNG this.pool = pool; } - // Instance methods. - // ----------------------------------------------------------------------- - public void run() { running = true; - if (DEBUG) + if (Configuration.DEBUG) { - debug("files: " + files); - debug("URLs: " + urls); - debug("progs: " + progs); + log.fine("files: " + files); + log.fine("URLs: " + urls); + log.fine("progs: " + progs); } Iterator files_it = files.iterator(); Iterator urls_it = urls.iterator(); @@ -1073,190 +848,132 @@ public class CSPRNG extends BasePRNG while (files_it.hasNext() || urls_it.hasNext() || prog_it.hasNext() || other_it.hasNext()) { - // There is enough random data. Go away. - if (pool.getQuality() >= 100.0 || !running) - { - return; - } - + if (pool.getQuality() >= 100.0 || ! running) + return; if (files_it.hasNext()) - { - try - { - List l = (List) files_it.next(); - if (DEBUG) - { - debug(l.toString()); - } - double qual = ((Double) l.get(0)).doubleValue(); - int offset = ((Integer) l.get(1)).intValue(); - int count = ((Integer) l.get(2)).intValue(); - String src = (String) l.get(3); - InputStream in = new FileInputStream(src); - byte[] buf = new byte[count]; - if (offset > 0) - { - in.skip(offset); - } - int len = in.read(buf); - if (len >= 0) - { - pool.addRandomBytes(buf, 0, len); - pool.addQuality(qual * ((double) len / (double) count)); - } - if (DEBUG) - { - debug("got " + len + " bytes from " + src); - } - } - catch (Exception x) - { - if (DEBUG) - { - debug(x.toString()); - x.printStackTrace(); - } - } - } - - if (pool.getQuality() >= 100.0 || !running) - { - return; - } - + try + { + List l = (List) files_it.next(); + if (Configuration.DEBUG) + log.fine(l.toString()); + double qual = ((Double) l.get(0)).doubleValue(); + int offset = ((Integer) l.get(1)).intValue(); + int count = ((Integer) l.get(2)).intValue(); + String src = (String) l.get(3); + InputStream in = new FileInputStream(src); + byte[] buf = new byte[count]; + if (offset > 0) + in.skip(offset); + int len = in.read(buf); + if (len >= 0) + { + pool.addRandomBytes(buf, 0, len); + pool.addQuality(qual * ((double) len / (double) count)); + } + if (Configuration.DEBUG) + log.fine("got " + len + " bytes from " + src); + } + catch (Exception x) + { + if (Configuration.DEBUG) + log.throwing(this.getClass().getName(), "run", x); + } + if (pool.getQuality() >= 100.0 || ! running) + return; if (urls_it.hasNext()) - { - try - { - List l = (List) urls_it.next(); - if (DEBUG) - { - debug(l.toString()); - } - double qual = ((Double) l.get(0)).doubleValue(); - int offset = ((Integer) l.get(1)).intValue(); - int count = ((Integer) l.get(2)).intValue(); - URL src = (URL) l.get(3); - InputStream in = src.openStream(); - byte[] buf = new byte[count]; - if (offset > 0) - { - in.skip(offset); - } - int len = in.read(buf); - if (len >= 0) - { - pool.addRandomBytes(buf, 0, len); - pool.addQuality(qual * ((double) len / (double) count)); - } - if (DEBUG) - { - debug("got " + len + " bytes from " + src); - } - } - catch (Exception x) - { - if (DEBUG) - { - debug(x.toString()); - x.printStackTrace(); - } - } - } - - if (pool.getQuality() >= 100.0 || !running) - { - return; - } - + try + { + List l = (List) urls_it.next(); + if (Configuration.DEBUG) + log.fine(l.toString()); + double qual = ((Double) l.get(0)).doubleValue(); + int offset = ((Integer) l.get(1)).intValue(); + int count = ((Integer) l.get(2)).intValue(); + URL src = (URL) l.get(3); + InputStream in = src.openStream(); + byte[] buf = new byte[count]; + if (offset > 0) + in.skip(offset); + int len = in.read(buf); + if (len >= 0) + { + pool.addRandomBytes(buf, 0, len); + pool.addQuality(qual * ((double) len / (double) count)); + } + if (Configuration.DEBUG) + log.fine("got " + len + " bytes from " + src); + } + catch (Exception x) + { + if (Configuration.DEBUG) + log.throwing(this.getClass().getName(), "run", x); + } + if (pool.getQuality() >= 100.0 || ! running) + return; Process proc = null; if (prog_it.hasNext()) - { - try - { - List l = (List) prog_it.next(); - if (DEBUG) - { - debug(l.toString()); - } - double qual = ((Double) l.get(0)).doubleValue(); - int offset = ((Integer) l.get(1)).intValue(); - int count = ((Integer) l.get(2)).intValue(); - String src = (String) l.get(3); - proc = null; - proc = Runtime.getRuntime().exec(src); - InputStream in = proc.getInputStream(); - byte[] buf = new byte[count]; - if (offset > 0) - { - in.skip(offset); - } - int len = in.read(buf); - if (len >= 0) - { - pool.addRandomBytes(buf, 0, len); - pool.addQuality(qual * ((double) len / (double) count)); - } - proc.destroy(); - proc.waitFor(); - if (DEBUG) - { - debug("got " + len + " bytes from " + src); - } - } - catch (Exception x) - { - if (DEBUG) - { - debug(x.toString()); - x.printStackTrace(); - } - try - { - if (proc != null) - { - proc.destroy(); - proc.waitFor(); - } - } - catch (Exception ignored) - { - } - } - } - - if (pool.getQuality() >= 100.0 || !running) - { - return; - } - + try + { + List l = (List) prog_it.next(); + if (Configuration.DEBUG) + log.finer(l.toString()); + double qual = ((Double) l.get(0)).doubleValue(); + int offset = ((Integer) l.get(1)).intValue(); + int count = ((Integer) l.get(2)).intValue(); + String src = (String) l.get(3); + proc = null; + proc = Runtime.getRuntime().exec(src); + InputStream in = proc.getInputStream(); + byte[] buf = new byte[count]; + if (offset > 0) + in.skip(offset); + int len = in.read(buf); + if (len >= 0) + { + pool.addRandomBytes(buf, 0, len); + pool.addQuality(qual * ((double) len / (double) count)); + } + proc.destroy(); + proc.waitFor(); + if (Configuration.DEBUG) + log.fine("got " + len + " bytes from " + src); + } + catch (Exception x) + { + if (Configuration.DEBUG) + log.throwing(this.getClass().getName(), "run", x); + try + { + if (proc != null) + { + proc.destroy(); + proc.waitFor(); + } + } + catch (Exception ignored) + { + } + } + if (pool.getQuality() >= 100.0 || ! running) + return; if (other_it.hasNext()) - { - try - { - EntropySource src = (EntropySource) other_it.next(); - byte[] buf = src.nextBytes(); - if (pool == null) - { - return; - } - pool.addRandomBytes(buf, 0, buf.length); - pool.addQuality(src.quality()); - if (DEBUG) - { - debug("got " + buf.length + " bytes from " + src); - } - } - catch (Exception x) - { - if (DEBUG) - { - debug(x.toString()); - x.printStackTrace(); - } - } - } + try + { + EntropySource src = (EntropySource) other_it.next(); + byte[] buf = src.nextBytes(); + if (pool == null) + return; + pool.addRandomBytes(buf, 0, buf.length); + pool.addQuality(src.quality()); + if (Configuration.DEBUG) + log.fine("got " + buf.length + " bytes from " + src); + } + catch (Exception x) + { + if (Configuration.DEBUG) + log.throwing(this.getClass().getName(), "run", x); + } } } @@ -1265,4 +982,4 @@ public class CSPRNG extends BasePRNG running = false; } } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/prng/Fortuna.java b/libjava/classpath/gnu/javax/crypto/prng/Fortuna.java index 69ce860..8aec9ab 100644 --- a/libjava/classpath/gnu/javax/crypto/prng/Fortuna.java +++ b/libjava/classpath/gnu/javax/crypto/prng/Fortuna.java @@ -45,7 +45,6 @@ import gnu.java.security.prng.BasePRNG; import gnu.java.security.prng.LimitReachedException; import gnu.java.security.prng.RandomEvent; import gnu.java.security.prng.RandomEventListener; - import gnu.javax.crypto.cipher.CipherFactory; import gnu.javax.crypto.cipher.IBlockCipher; @@ -53,9 +52,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; - import java.security.InvalidKeyException; - import java.util.Arrays; import java.util.Collections; import java.util.Iterator; @@ -63,68 +60,54 @@ import java.util.Map; /** * The Fortuna continuously-seeded pseudo-random number generator. This - * generator is composed of two major pieces: the entropy accumulator - * and the generator function. The former takes in random bits and - * incorporates them into the generator's state. The latter takes this - * base entropy and generates pseudo-random bits from it. - * - *
There are some things users of this class must be aware of: - * + * generator is composed of two major pieces: the entropy accumulator and the + * generator function. The former takes in random bits and incorporates them + * into the generator's state. The latter takes this base entropy and generates + * pseudo-random bits from it. + *
+ * There are some things users of this class must be aware of: *
References:
- * + *+ * References: *
Counter Mode is a way to define a pseudorandom keystream generator using - * a block cipher. The keystream can be used for additive encryption, key - * derivation, or any other application requiring pseudorandom data.
- * - *In ICM, the keystream is logically broken into segments. Each segment is + * Counter Mode is a way to define a pseudorandom keystream generator using a + * block cipher. The keystream can be used for additive encryption, key + * derivation, or any other application requiring pseudorandom data. + *
+ * In ICM, the keystream is logically broken into segments. Each segment is * identified with a segment index, and the segments have equal lengths. This * segmentation makes ICM especially appropriate for securing packet-based - * protocols.
- * - *This implementation adheres to the definition of the ICM keystream
- * generation function that allows for any symetric key block cipher algorithm
- * (initialisation parameter gnu.crypto.prng.icm.cipher.name
taken
- * to be an instance of {@link java.lang.String}) to be used. If such a
+ * protocols.
+ *
+ * This implementation adheres to the definition of the ICM keystream generation
+ * function that allows for any symetric key block cipher algorithm
+ * (initialisation parameter gnu.crypto.prng.icm.cipher.name
+ * taken to be an instance of {@link java.lang.String}) to be used. If such a
* parameter is not defined/included in the initialisation Map
,
* then the "Rijndael" algorithm is used. Furthermore, if the initialisation
* parameter gnu.crypto.cipher.block.size
(taken to be a instance
* of {@link java.lang.Integer}) is missing or undefined in the initialisation
- * Map
, then the cipher's default block size is used.
The practical limits and constraints of such generator are:
+ *Map
, then the cipher's default block size is used.
+ * + * The practical limits and constraints of such generator are: *
- * 256 ** BLOCK_INDEX_LENGTH
. The number of segments MUST NOT
- * exceed 256 ** SEGMENT_INDEX_LENGTH
. These restrictions ensure
- * the uniqueness of each block cipher input.SEGMENT_LENGTH
octets; this value
- * MUST NOT exceed the value (256 ** BLOCK_INDEX_LENGTH) *
+ * - The number of blocks in any segment MUST NOT exceed
+ * 256 ** BLOCK_INDEX_LENGTH
.
+ * The number of segments MUST NOT exceed
+ * 256 ** SEGMENT_INDEX_LENGTH
. These restrictions ensure the
+ * uniqueness of each block cipher input.
+ * - Each segment contains
SEGMENT_LENGTH
octets; this value
+ * MUST NOT exceed the value (256 ** BLOCK_INDEX_LENGTH) *
* BLOCK_LENGTH
.
- *
- * - The sum of
SEGMENT_INDEX_LENGTH
and
- * BLOCK_INDEX_LENGTH
MUST NOT exceed BLOCK_LENGTH
- * / 2
. This requirement protects the ICM keystream generator from
- * potentially failing to be pseudorandom.
+ * - The sum of
SEGMENT_INDEX_LENGTH
and
+ * BLOCK_INDEX_LENGTH
MUST NOT exceed BLOCK_LENGTH
+ * / 2
.
+ * This requirement protects the ICM keystream generator from potentially
+ * failing to be pseudorandom.
*
NOTE: Rijndael is used as the default symmetric key block cipher + *
+ * NOTE: Rijndael is used as the default symmetric key block cipher * algorithm because, with its default block and key sizes, it is the AES. Yet * being Rijndael, the algorithm offers more versatile block and key sizes which - * may prove to be useful for generating longer key streams.
- * - *References:
- * + * may prove to be useful for generating longer key streams. + *+ * References: *
An implementation of the key derivation function KDF2 from PKCS #5: + * An implementation of the key derivation function KDF2 from PKCS #5: * Password-Based Cryptography (PBE). This KDF is essentially a way to * transform a password and a salt into a stream of random bytes, which may then - * be used to initialize a cipher or a MAC.
- * - *This version uses a MAC as its pseudo-random function, and the password is - * used as the key.
- * - *References:
+ * be used to initialize a cipher or a MAC. + *+ * This version uses a MAC as its pseudo-random function, and the password is + * used as the key. + *
+ * References: *
Creates a new PBKDF2 object. The argument is the MAC that will serve as - * the pseudo-random function. The MAC does not need to be initialized.
- * + * Creates a new PBKDF2 object. The argument is the MAC that will serve as the + * pseudo-random function. The MAC does not need to be initialized. + * * @param mac The pseudo-random function. */ public PBKDF2(IMac mac) @@ -103,30 +94,19 @@ public class PBKDF2 extends BasePRNG implements Cloneable iterationCount = -1; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - public void setup(Map attributes) { Map macAttrib = new HashMap(); macAttrib.put(HMac.USE_WITH_PKCS5_V2, Boolean.TRUE); - byte[] s = (byte[]) attributes.get(IPBE.SALT); if (s == null) { if (salt == null) - { - throw new IllegalArgumentException("no salt specified"); - } // Otherwise re-use. + throw new IllegalArgumentException("no salt specified"); + // Otherwise re-use. } else - { - salt = s; - } - + salt = s; byte[] macKeyMaterial; char[] password = (char[]) attributes.get(IPBE.PASSWORD); if (password != null) @@ -136,7 +116,6 @@ public class PBKDF2 extends BasePRNG implements Cloneable encoding = IPBE.DEFAULT_PASSWORD_ENCODING; else encoding = encoding.trim(); - try { macKeyMaterial = new String(password).getBytes(encoding); @@ -152,10 +131,10 @@ public class PBKDF2 extends BasePRNG implements Cloneable if (macKeyMaterial != null) macAttrib.put(IMac.MAC_KEY_MATERIAL, macKeyMaterial); - else if (!initialised) - throw new IllegalArgumentException("Neither password nor key-material were specified"); + else if (! initialised) + throw new IllegalArgumentException( + "Neither password nor key-material were specified"); // otherwise re-use previous password/key-material - try { mac.init(macAttrib); @@ -164,27 +143,19 @@ public class PBKDF2 extends BasePRNG implements Cloneable { throw new IllegalArgumentException(x.getMessage()); } - Integer ic = (Integer) attributes.get(IPBE.ITERATION_COUNT); if (ic != null) - { - iterationCount = ic.intValue(); - } + iterationCount = ic.intValue(); if (iterationCount <= 0) - { - throw new IllegalArgumentException("bad iteration count"); - } - + throw new IllegalArgumentException("bad iteration count"); count = 0L; buffer = new byte[mac.macSize()]; try { fillBlock(); - // } catch (Exception x) { } catch (LimitReachedException x) { - // x.printStackTrace(System.err); throw new Error(x.getMessage()); } } @@ -192,34 +163,22 @@ public class PBKDF2 extends BasePRNG implements Cloneable public void fillBlock() throws LimitReachedException { if (++count > ((1L << 32) - 1)) - { - throw new LimitReachedException(); - } - // for (int i = 0; i < buffer.length; i++) { - // buffer[i] = 0; - // } + throw new LimitReachedException(); Arrays.fill(buffer, (byte) 0x00); int limit = salt.length; - // in = new byte[salt.length + 4]; in = new byte[limit + 4]; System.arraycopy(salt, 0, in, 0, salt.length); - // in[salt.length ] = (byte)(count >>> 24); - // in[salt.length+1] = (byte)(count >>> 16); - // in[salt.length+2] = (byte)(count >>> 8); - // in[salt.length+3] = (byte) count; - in[limit++] = (byte) (count >>> 24); - in[limit++] = (byte) (count >>> 16); - in[limit++] = (byte) (count >>> 8); - in[limit] = (byte) count; + in[limit++] = (byte)(count >>> 24); + in[limit++] = (byte)(count >>> 16); + in[limit++] = (byte)(count >>> 8); + in[limit ] = (byte) count; for (int i = 0; i < iterationCount; i++) { mac.reset(); mac.update(in, 0, in.length); in = mac.digest(); for (int j = 0; j < buffer.length; j++) - { - buffer[j] ^= in[j]; - } + buffer[j] ^= in[j]; } } } diff --git a/libjava/classpath/gnu/javax/crypto/prng/PRNGFactory.java b/libjava/classpath/gnu/javax/crypto/prng/PRNGFactory.java index 9ff6558..ee75f8d 100644 --- a/libjava/classpath/gnu/javax/crypto/prng/PRNGFactory.java +++ b/libjava/classpath/gnu/javax/crypto/prng/PRNGFactory.java @@ -40,11 +40,9 @@ package gnu.javax.crypto.prng; import gnu.java.security.Registry; import gnu.java.security.prng.IRandom; - - +import gnu.javax.crypto.mac.HMacFactory; import gnu.javax.crypto.mac.IMac; import gnu.javax.crypto.mac.MacFactory; -import gnu.javax.crypto.mac.HMacFactory; import java.util.Collections; import java.util.HashSet; @@ -52,92 +50,66 @@ import java.util.Iterator; import java.util.Set; /** - *A Factory to instantiate pseudo random number generators.
+ * A Factory to instantiate pseudo random number generators. */ -public class PRNGFactory implements Registry +public class PRNGFactory + implements Registry { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - /** Trivial constructor to enforce Singleton pattern. */ private PRNGFactory() { } - // Class methods - // ------------------------------------------------------------------------- - /** - *Returns an instance of a padding algorithm given its name.
- * + * Returns an instance of a padding algorithm given its name. + * * @param prng the case-insensitive name of the PRNG. * @return an instance of the pseudo-random number generator. * @exception InternalError if the implementation does not pass its self- - * test. + * test. */ public static IRandom getInstance(String prng) { if (prng == null) - { - return null; - } - + return null; prng = prng.trim(); IRandom result = null; if (prng.equalsIgnoreCase(ARCFOUR_PRNG) || prng.equalsIgnoreCase(RC4_PRNG)) - { - result = new ARCFour(); - } + result = new ARCFour(); else if (prng.equalsIgnoreCase(ICM_PRNG)) - { - result = new ICMGenerator(); - } + result = new ICMGenerator(); else if (prng.equalsIgnoreCase(UMAC_PRNG)) - { - result = new UMacGenerator(); - } + result = new UMacGenerator(); else if (prng.toLowerCase().startsWith(PBKDF2_PRNG_PREFIX)) { String macName = prng.substring(PBKDF2_PRNG_PREFIX.length()); IMac mac = MacFactory.getInstance(macName); if (mac == null) - { - return null; - } + return null; result = new PBKDF2(mac); } if (result != null) return result; - return gnu.java.security.prng.PRNGFactory.getInstance (prng); + return gnu.java.security.prng.PRNGFactory.getInstance(prng); } /** - *Returns a {@link Set} of names of padding algorithms supported by this - * Factory.
- * + * Returns a {@link Set} of names of padding algorithms supported by this + * Factory. + * * @return a {@link Set} of pseudo-random number generator algorithm names - * (Strings). + * (Strings). */ public static Set getNames() { - HashSet hs = new HashSet (gnu.java.security.prng.PRNGFactory.getNames ()); + HashSet hs = new HashSet(gnu.java.security.prng.PRNGFactory.getNames()); hs.add(ICM_PRNG); hs.add(UMAC_PRNG); // add all hmac implementations as candidate PBKDF2 ones too for (Iterator it = HMacFactory.getNames().iterator(); it.hasNext();) - { - hs.add(PBKDF2_PRNG_PREFIX + ((String) it.next())); - } - + hs.add(PBKDF2_PRNG_PREFIX + ((String) it.next())); return Collections.unmodifiableSet(hs); } - - // Instance methods - // ------------------------------------------------------------------------- } diff --git a/libjava/classpath/gnu/javax/crypto/prng/UMacGenerator.java b/libjava/classpath/gnu/javax/crypto/prng/UMacGenerator.java index 0e3725c..39c99f7 100644 --- a/libjava/classpath/gnu/javax/crypto/prng/UMacGenerator.java +++ b/libjava/classpath/gnu/javax/crypto/prng/UMacGenerator.java @@ -50,121 +50,90 @@ import java.util.Map; import java.security.InvalidKeyException; /** - *KDFs (Key Derivation Functions) are used to stretch user-supplied - * key material to specific size(s) required by high level cryptographic - * primitives. Described in the KDFs (Key Derivation Functions) are used to stretch user-supplied key + * material to specific size(s) required by high level cryptographic primitives. + * Described in the UMAC * paper, this function basically operates an underlying symmetric key block * cipher instance in output feedback mode (OFB), as a strong - * pseudo-random number generator.
- * - *UMacGenerator
requires an index parameter
+ * pseudo-random number generator.
+ *
+ * UMacGenerator
requires an index parameter
* (initialisation parameter gnu.crypto.prng.umac.kdf.index
taken
- * to be an instance of {@link java.lang.Integer} with a value between
- * 0
and 255
). Using the same key, but different
- * indices, generates different pseudorandom outputs.
This implementation generalises the definition of the
- * UmacGenerator
algorithm to allow for other than the AES symetric
- * key block cipher algorithm (initialisation parameter
+ * to be an instance of {@link Integer} with a value between 0
and
+ * 255
). Using the same key, but different indices, generates
+ * different pseudorandom outputs.
+ *
+ * This implementation generalises the definition of the
+ * UmacGenerator
algorithm to allow for other than the AES
+ * symetric key block cipher algorithm (initialisation parameter
* gnu.crypto.prng.umac.cipher.name
taken to be an instance of
- * {@link java.lang.String}). If such a parameter is not defined/included in the
+ * {@link String}). If such a parameter is not defined/included in the
* initialisation Map
, then the "Rijndael" algorithm is used.
* Furthermore, if the initialisation parameter
- * gnu.crypto.cipher.block.size
(taken to be a instance of {@link
- * java.lang.Integer}) is missing or undefined in the initialisation Map
- *
, then the cipher's default block size is used.
NOTE: Rijndael is used as the default symmetric key block cipher
+ * gnu.crypto.cipher.block.size
(taken to be a instance of
+ * {@link Integer}) is missing or undefined in the initialisation
+ * Map
, then the cipher's default block size is used.
+ *
+ * NOTE: Rijndael is used as the default symmetric key block cipher * algorithm because, with its default block and key sizes, it is the AES. Yet * being Rijndael, the algorithm offers more versatile block and key sizes which - * may prove to be useful for generating "longer" key streams.
- * - *References:
- * + * may prove to be useful for generating "longer" key streams. + *+ * References: *
Property name of the KDF index
value to use in this
+ * Property name of the KDF index
value to use in this
* instance. The value is taken to be an {@link Integer} less than
- * 256
.
256
.
*/
public static final String INDEX = "gnu.crypto.prng.umac.index";
-
/** The name of the underlying symmetric key block cipher algorithm. */
public static final String CIPHER = "gnu.crypto.prng.umac.cipher.name";
-
/** The generator's underlying block cipher. */
private IBlockCipher cipher;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial 0-arguments constructor. */
public UMacGenerator()
{
super(Registry.UMAC_PRNG);
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // Implementation of abstract methods in BasePRNG --------------------------
-
public void setup(Map attributes)
{
boolean newCipher = true;
String cipherName = (String) attributes.get(CIPHER);
if (cipherName == null)
- {
- if (cipher == null)
- { // happy birthday
- cipher = CipherFactory.getInstance(Registry.RIJNDAEL_CIPHER);
- }
- else
- { // we already have one. use it as is
- newCipher = false;
- }
- }
+ if (cipher == null) // happy birthday
+ cipher = CipherFactory.getInstance(Registry.RIJNDAEL_CIPHER);
+ else // we already have one. use it as is
+ newCipher = false;
else
- {
- cipher = CipherFactory.getInstance(cipherName);
- }
-
+ cipher = CipherFactory.getInstance(cipherName);
// find out what block size we should use it in
int cipherBlockSize = 0;
Integer bs = (Integer) attributes.get(IBlockCipher.CIPHER_BLOCK_SIZE);
if (bs != null)
- {
- cipherBlockSize = bs.intValue();
- }
+ cipherBlockSize = bs.intValue();
else
{
- if (newCipher)
- { // assume we'll use its default block size
- cipherBlockSize = cipher.defaultBlockSize();
- } // else use as is
+ if (newCipher) // assume we'll use its default block size
+ cipherBlockSize = cipher.defaultBlockSize();
+ // else use as is
}
-
// get the key material
byte[] key = (byte[]) attributes.get(IBlockCipher.KEY_MATERIAL);
if (key == null)
- {
- throw new IllegalArgumentException(IBlockCipher.KEY_MATERIAL);
- }
+ throw new IllegalArgumentException(IBlockCipher.KEY_MATERIAL);
int keyLength = key.length;
// ensure that keyLength is valid for the chosen underlying cipher
@@ -173,15 +142,10 @@ public class UMacGenerator extends BasePRNG implements Cloneable
{
ok = (keyLength == ((Integer) it.next()).intValue());
if (ok)
- {
- break;
- }
+ break;
}
- if (!ok)
- {
- throw new IllegalArgumentException("key length");
- }
-
+ if (! ok)
+ throw new IllegalArgumentException("key length");
// ensure that remaining params make sense
int index = -1;
Integer i = (Integer) attributes.get(INDEX);
@@ -189,17 +153,12 @@ public class UMacGenerator extends BasePRNG implements Cloneable
{
index = i.intValue();
if (index < 0 || index > 255)
- {
- throw new IllegalArgumentException(INDEX);
- }
+ throw new IllegalArgumentException(INDEX);
}
-
// now initialise the underlying cipher
Map map = new HashMap();
- if (cipherBlockSize != 0)
- { // only needed if new or changed
- map.put(IBlockCipher.CIPHER_BLOCK_SIZE, new Integer(cipherBlockSize));
- }
+ if (cipherBlockSize != 0) // only needed if new or changed
+ map.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(cipherBlockSize));
map.put(IBlockCipher.KEY_MATERIAL, key);
try
{
@@ -209,7 +168,6 @@ public class UMacGenerator extends BasePRNG implements Cloneable
{
throw new IllegalArgumentException(IBlockCipher.KEY_MATERIAL);
}
-
buffer = new byte[cipher.currentBlockSize()];
buffer[cipher.currentBlockSize() - 1] = (byte) index;
try
@@ -225,4 +183,4 @@ public class UMacGenerator extends BasePRNG implements Cloneable
{
cipher.encryptBlock(buffer, 0, buffer, 0);
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/AuthInfo.java b/libjava/classpath/gnu/javax/crypto/sasl/AuthInfo.java
index 1e94255..733d2f0 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/AuthInfo.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/AuthInfo.java
@@ -56,10 +56,6 @@ import java.util.StringTokenizer;
*/
public class AuthInfo
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
private static final ArrayList factories = new ArrayList();
static
{
@@ -72,14 +68,14 @@ public class AuthInfo
{
for (StringTokenizer st = new StringTokenizer(pkgs, "|"); st.hasMoreTokens();)
{
- clazz = st.nextToken();
- if (!"gnu.crypto.sasl".equals(clazz))
+ clazz = st.nextToken().trim();
+ if (! "gnu.javax.crypto.sasl".equals(clazz))
{
clazz += ".AuthInfoProviderFactory";
try
{
- IAuthInfoProviderFactory factory = (IAuthInfoProviderFactory) Class.forName(
- clazz).newInstance();
+ IAuthInfoProviderFactory factory =
+ (IAuthInfoProviderFactory) Class.forName(clazz).newInstance();
factories.add(factory);
}
catch (ClassCastException ignored)
@@ -99,33 +95,25 @@ public class AuthInfo
}
// always add ours last; unless it's already there
if (!factories.contains(ours))
- {
- factories.add(ours);
- }
+ factories.add(ours);
}
- // Constructor(s)
- // -------------------------------------------------------------------------
-
/** Trivial constructor to enforce Singleton pattern. */
private AuthInfo()
{
super();
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
- * A convenience method to return the authentication information provider
- * for a designated SASL mechnanism. It goes through all the installed
- * provider factories, one at a time, and attempts to return a new instance
- * of the provider for the designated mechanism. It stops at the first
- * factory returning a non-null provider.
- *
+ * A convenience method to return the authentication information provider for
+ * a designated SASL mechnanism. It goes through all the installed provider
+ * factories, one at a time, and attempts to return a new instance of the
+ * provider for the designated mechanism. It stops at the first factory
+ * returning a non-null provider.
+ *
* @param mechanism the name of a SASL mechanism.
* @return an implementation that provides {@link IAuthInfoProvider} for that
- * mechanism; or null
if none found.
+ * mechanism; or null
if none found.
*/
public static IAuthInfoProvider getProvider(String mechanism)
{
@@ -134,9 +122,7 @@ public class AuthInfo
IAuthInfoProviderFactory factory = (IAuthInfoProviderFactory) it.next();
IAuthInfoProvider result = factory.getInstance(mechanism);
if (result != null)
- {
- return result;
- }
+ return result;
}
return null;
}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java b/libjava/classpath/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java
index 6ba5fc5..c4fc816 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/AuthInfoProviderFactory.java
@@ -46,44 +46,22 @@ import gnu.javax.crypto.sasl.srp.SRPAuthInfoProvider;
/**
* The concrete SASL authentication information provider factory.
*/
-public class AuthInfoProviderFactory implements IAuthInfoProviderFactory
+public class AuthInfoProviderFactory
+ implements IAuthInfoProviderFactory
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// implicit 0-args constructor
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // IAuthInfoProviderFactory interface implementation -----------------------
-
public IAuthInfoProvider getInstance(String mechanism)
{
if (mechanism == null)
- {
- return null;
- }
+ return null;
mechanism = mechanism.trim().toUpperCase();
if (mechanism.startsWith(Registry.SASL_SRP_MECHANISM))
- {
- return new SRPAuthInfoProvider();
- }
+ return new SRPAuthInfoProvider();
if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM))
- {
- return new CramMD5AuthInfoProvider();
- }
+ return new CramMD5AuthInfoProvider();
if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM))
- {
- return new PlainAuthInfoProvider();
- }
+ return new PlainAuthInfoProvider();
return null;
}
}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/ClientFactory.java b/libjava/classpath/gnu/javax/crypto/sasl/ClientFactory.java
index ef18463..84acfcd 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/ClientFactory.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/ClientFactory.java
@@ -47,11 +47,11 @@ import gnu.javax.crypto.sasl.srp.SRPClient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.HashMap;
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.Sasl;
@@ -62,53 +62,32 @@ import javax.security.sasl.SaslException;
/**
* The implementation of {@link SaslClientFactory}.
*/
-public class ClientFactory implements SaslClientFactory
+public class ClientFactory
+ implements SaslClientFactory
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// implicit 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
public static final Set getNames()
{
- return Collections.unmodifiableSet(new HashSet(
- Arrays.asList(getNamesInternal(null))));
+ return Collections.unmodifiableSet(new HashSet(Arrays.asList(getNamesInternal(null))));
}
private static final String[] getNamesInternal(Map props)
{
- String[] all = new String[] { Registry.SASL_SRP_MECHANISM,
- Registry.SASL_CRAM_MD5_MECHANISM,
- Registry.SASL_PLAIN_MECHANISM,
- Registry.SASL_ANONYMOUS_MECHANISM };
-
+ String[] all = new String[] {
+ Registry.SASL_SRP_MECHANISM,
+ Registry.SASL_CRAM_MD5_MECHANISM,
+ Registry.SASL_PLAIN_MECHANISM,
+ Registry.SASL_ANONYMOUS_MECHANISM };
if (props == null)
- {
- return all;
- }
+ return all;
if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props))
- {
- return new String[0];
- }
-
+ return new String[0];
List result = new ArrayList(all.length);
- ;
for (int i = 0; i < all.length;)
- {
- result.add(all[i++]);
- }
-
+ result.add(all[i++]);
if (hasPolicy(Sasl.POLICY_NOPLAINTEXT, props))
- {
- result.remove(Registry.SASL_PLAIN_MECHANISM);
- }
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
if (hasPolicy(Sasl.POLICY_NOACTIVE, props))
{
result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
@@ -135,32 +114,19 @@ public class ClientFactory implements SaslClientFactory
public static final ClientMechanism getInstance(String mechanism)
{
if (mechanism == null)
- {
- return null;
- }
+ return null;
mechanism = mechanism.trim().toUpperCase();
if (mechanism.equals(Registry.SASL_SRP_MECHANISM))
- {
- return new SRPClient();
- }
+ return new SRPClient();
if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM))
- {
- return new CramMD5Client();
- }
+ return new CramMD5Client();
if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM))
- {
- return new PlainClient();
- }
+ return new PlainClient();
if (mechanism.equals(Registry.SASL_ANONYMOUS_MECHANISM))
- {
- return new AnonymousClient();
- }
+ return new AnonymousClient();
return null;
}
- // Instance methods
- // -------------------------------------------------------------------------
-
public SaslClient createSaslClient(String[] mechanisms,
String authorisationID, String protocol,
String serverName, Map props,
@@ -173,29 +139,21 @@ public class ClientFactory implements SaslClientFactory
mechanism = mechanisms[i];
result = getInstance(mechanism);
if (result != null)
- {
- break;
- }
+ break;
}
-
if (result != null)
{
HashMap attributes = new HashMap();
if (props != null)
- {
- attributes.putAll(props);
- }
+ attributes.putAll(props);
attributes.put(Registry.SASL_AUTHORISATION_ID, authorisationID);
attributes.put(Registry.SASL_PROTOCOL, protocol);
attributes.put(Registry.SASL_SERVER_NAME, serverName);
attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh);
-
result.init(attributes);
return result;
}
-
- throw new SaslException(
- "No supported mechanism found in given mechanism list");
+ throw new SaslException("No supported mechanism found in given mechanism list");
}
public String[] getMechanismNames(Map props)
@@ -207,4 +165,4 @@ public class ClientFactory implements SaslClientFactory
{
return "true".equalsIgnoreCase(String.valueOf(props.get(propertyName)));
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/ClientMechanism.java b/libjava/classpath/gnu/javax/crypto/sasl/ClientMechanism.java
index 45873ae..7f8e9c1 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/ClientMechanism.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/ClientMechanism.java
@@ -42,50 +42,37 @@ import gnu.java.security.Registry;
import java.util.HashMap;
import java.util.Map;
+
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
/**
- * A base class to facilitate implementing SASL client-side mechanisms.
+ * A base class to facilitate implementing SASL client-side mechanisms. */ -public abstract class ClientMechanism implements SaslClient +public abstract class ClientMechanism + implements SaslClient { - - // Constants and variables - // ------------------------------------------------------------------------- - /** Name of this mechanism. */ protected String mechanism; - /** The authorisation identity. */ protected String authorizationID; - /** Name of protocol using this mechanism. */ protected String protocol; - /** Name of server to authenticate to. */ protected String serverName; - /** Properties of qualities desired for this mechanism. */ protected Map properties; - /** Callback handler to use with this mechanism instance. */ protected CallbackHandler handler; - /** Channel binding data to use with this mechanism instance. */ protected byte[] channelBinding; - /** Whether authentication phase is completed (true) or not (false). */ protected boolean complete = false; - /** The state of the authentication automaton. */ protected int state = -1; - // Constructor(s) - // ------------------------------------------------------------------------- - protected ClientMechanism(final String mechanism) { super(); @@ -94,20 +81,10 @@ public abstract class ClientMechanism implements SaslClient this.state = -1; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods to be implemented by concrete subclasses --------------- - protected abstract void initMechanism() throws SaslException; protected abstract void resetMechanism() throws SaslException; - // javax.security.sasl.SaslClient interface implementation ----------------- - public abstract byte[] evaluateChallenge(byte[] challenge) throws SaslException; @@ -121,20 +98,16 @@ public abstract class ClientMechanism implements SaslClient public byte[] unwrap(final byte[] incoming, final int offset, final int len) throws SaslException { - if (!isComplete()) - { - throw new IllegalMechanismStateException(); - } + if (! isComplete()) + throw new IllegalMechanismStateException(); return this.engineUnwrap(incoming, offset, len); } public byte[] wrap(final byte[] outgoing, final int offset, final int len) throws SaslException { - if (!isComplete()) - { - throw new IllegalMechanismStateException(); - } + if (! isComplete()) + throw new IllegalMechanismStateException(); return this.engineWrap(outgoing, offset, len); } @@ -145,58 +118,32 @@ public abstract class ClientMechanism implements SaslClient public Object getNegotiatedProperty(final String propName) { - if (!isComplete()) - { - throw new IllegalStateException(); - } + if (! isComplete()) + throw new IllegalStateException(); if (Sasl.QOP.equals(propName)) - { - return getNegotiatedQOP(); - } + return getNegotiatedQOP(); if (Sasl.STRENGTH.equals(propName)) - { - return getNegotiatedStrength(); - } + return getNegotiatedStrength(); if (Sasl.SERVER_AUTH.equals(propName)) - { - return getNegotiatedServerAuth(); - } + return getNegotiatedServerAuth(); if (Sasl.MAX_BUFFER.equals(propName)) - { - return getNegotiatedMaxBuffer(); - } + return getNegotiatedMaxBuffer(); if (Sasl.RAW_SEND_SIZE.equals(propName)) - { - return getNegotiatedRawSendSize(); - } + return getNegotiatedRawSendSize(); if (Sasl.POLICY_NOPLAINTEXT.equals(propName)) - { - return getNegotiatedPolicyNoPlainText(); - } + return getNegotiatedPolicyNoPlainText(); if (Sasl.POLICY_NOACTIVE.equals(propName)) - { - return getNegotiatedPolicyNoActive(); - } + return getNegotiatedPolicyNoActive(); if (Sasl.POLICY_NODICTIONARY.equals(propName)) - { - return getNegotiatedPolicyNoDictionary(); - } + return getNegotiatedPolicyNoDictionary(); if (Sasl.POLICY_NOANONYMOUS.equals(propName)) - { - return getNegotiatedPolicyNoAnonymous(); - } + return getNegotiatedPolicyNoAnonymous(); if (Sasl.POLICY_FORWARD_SECRECY.equals(propName)) - { - return getNegotiatedPolicyForwardSecrecy(); - } + return getNegotiatedPolicyForwardSecrecy(); if (Sasl.POLICY_PASS_CREDENTIALS.equals(propName)) - { - return getNegotiatedPolicyPassCredentials(); - } + return getNegotiatedPolicyPassCredentials(); if (Sasl.REUSE.equals(propName)) - { - return getReuse(); - } + return getReuse(); return null; } @@ -204,8 +151,6 @@ public abstract class ClientMechanism implements SaslClient { } - // other Instance methods -------------------------------------------------- - public String getAuthorizationID() { return authorizationID; @@ -288,30 +233,23 @@ public abstract class ClientMechanism implements SaslClient } /** - *Initialises the mechanism with designated attributes. Permissible names - * and values are mechanism specific.
- * + * Initialises the mechanism with designated attributes. Permissible names and + * values are mechanism specific. + * * @param attributes a set of name-value pairs that describes the desired - * future behaviour of this instance. + * future behaviour of this instance. * @throws IllegalMechanismStateException if the instance is already - * initialised. + * initialised. * @throws SaslException if an exception occurs during the process. */ public void init(final Map attributes) throws SaslException { if (state != -1) - { - throw new IllegalMechanismStateException("init()"); - } - + throw new IllegalMechanismStateException("init()"); if (properties == null) - { - properties = new HashMap(); - } + properties = new HashMap(); else - { - properties.clear(); - } + properties.clear(); if (attributes != null) { authorizationID = (String) attributes.get(Registry.SASL_AUTHORISATION_ID); @@ -322,35 +260,25 @@ public abstract class ClientMechanism implements SaslClient properties.putAll(attributes); } else - { - handler = null; - } + handler = null; if (authorizationID == null) - { - authorizationID = ""; - } + authorizationID = ""; if (protocol == null) - { - protocol = ""; - } + protocol = ""; if (serverName == null) - { - serverName = ""; - } + serverName = ""; if (channelBinding == null) - { - channelBinding = new byte[0]; - } + channelBinding = new byte[0]; initMechanism(); complete = false; state = 0; } /** - *Resets the mechanism instance for re-initialisation and use with other - * characteristics.
- * + * Resets the mechanism instance for re-initialisation and use with other + * characteristics. + * * @throws SaslException if an exception occurs during the process. */ public void reset() throws SaslException @@ -362,4 +290,4 @@ public abstract class ClientMechanism implements SaslClient complete = false; state = -1; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/ConfidentialityException.java b/libjava/classpath/gnu/javax/crypto/sasl/ConfidentialityException.java index adfc065..62b6857 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/ConfidentialityException.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/ConfidentialityException.java @@ -45,12 +45,12 @@ import javax.security.sasl.SaslException; * exception is thrown to indicate that a violation has occured during the * processing of a confidentiality protection filter. */ -public class ConfidentialityException extends SaslException +public class ConfidentialityException + extends SaslException { - /** - * Constructs a new instance ofConfidentialityException
with no
- * detail message.
+ * Constructs a new instance of ConfidentialityException
with
+ * no detail message.
*/
public ConfidentialityException()
{
@@ -60,7 +60,7 @@ public class ConfidentialityException extends SaslException
/**
* Constructs a new instance of ConfidentialityException
with
* the specified detail message.
- *
+ *
* @param s the detail message.
*/
public ConfidentialityException(String s)
@@ -71,7 +71,7 @@ public class ConfidentialityException extends SaslException
/**
* Constructs a new instance of ConfidentialityException
with a
* detailed message and a root exception.
- *
+ *
* @param s possibly null additional detail about the exception.
* @param x a possibly null root exception that caused this one.
*/
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProvider.java b/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProvider.java
index 2b913a1..60c50d5 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProvider.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProvider.java
@@ -47,71 +47,70 @@ import javax.security.sasl.AuthenticationException;
*/
public interface IAuthInfoProvider
{
-
- // Constants
- // -------------------------------------------------------------------------
-
- // Methods
- // -------------------------------------------------------------------------
-
/**
* Activates (initialises) this provider instance. SHOULD be the first method
* invoked on the provider.
- *
+ *
* @param context a collection of name-value bindings describing the
- * activation context.
- * @throws AuthenticationException if an exception occurs during the operation.
+ * activation context.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
*/
void activate(Map context) throws AuthenticationException;
/**
* Passivates (releases) this provider instance. SHOULD be the last method
- * invoked on the provider. Once it is done, no other method may be invoked
- * on the same instance before it is activated agains.
- *
- * @throws AuthenticationException if an exception occurs during the operation.
+ * invoked on the provider. Once it is done, no other method may be invoked on
+ * the same instance before it is activated agains.
+ *
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
*/
void passivate() throws AuthenticationException;
/**
* Checks if a user with a designated name is known to this provider.
- *
+ *
* @param userName the name of a user to check.
- * @return true
if the user with the designated name is known to
- * this provider; false
otherwise.
- * @throws AuthenticationException if an exception occurs during the operation.
+ * @return true
if the user with the designated name is known
+ * to this provider; false
otherwise.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
*/
boolean contains(String userName) throws AuthenticationException;
/**
* Returns a collection of information about a designated user. The contents
* of the returned map is provider-specific of name-to-value mappings.
- *
+ *
* @param userID a map of name-to-value bindings that fully describe a user.
* @return a collection of information about the designated user.
- * @throws AuthenticationException if an exception occurs during the operation.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
*/
Map lookup(Map userID) throws AuthenticationException;
/**
* Updates the credentials of a designated user.
- *
+ *
* @param userCredentials a map of name-to-value bindings that fully describe
- * a user, including per new credentials.
- * @throws AuthenticationException if an exception occurs during the operation.
+ * a user, including per new credentials.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
*/
void update(Map userCredentials) throws AuthenticationException;
/**
* A provider may operate in more than mode; e.g. SRP-II caters for user
- * credentials computed in more than one message digest algorithm. This
- * method returns the set of name-to-value bindings describing the mode of
- * the provider.
- *
+ * credentials computed in more than one message digest algorithm. This method
+ * returns the set of name-to-value bindings describing the mode of the
+ * provider.
+ *
* @param mode a unique identifier describing the operational mode.
* @return a collection of name-to-value bindings describing the designated
- * mode.
- * @throws AuthenticationException if an exception occurs during the operation.
+ * mode.
+ * @throws AuthenticationException if an exception occurs during the
+ * operation.
*/
Map getConfiguration(String mode) throws AuthenticationException;
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java b/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java
index e630b8d..b6dc775 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/IAuthInfoProviderFactory.java
@@ -43,20 +43,13 @@ package gnu.javax.crypto.sasl;
*/
public interface IAuthInfoProviderFactory
{
-
- // Constants
- // -------------------------------------------------------------------------
-
- // Methods
- // -------------------------------------------------------------------------
-
/**
- * Returns an implementation of a provider for a designated mechanism
- * capable of honouring {@link IAuthInfoProvider} requests.
- *
+ * Returns an implementation of a provider for a designated mechanism capable
+ * of honouring {@link IAuthInfoProvider} requests.
+ *
* @param mechanism the unique name of a mechanism.
* @return an implementation of {@link IAuthInfoProvider} for that mechanism
- * or null
if none found.
+ * or null
if none found.
*/
IAuthInfoProvider getInstance(String mechanism);
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/IllegalMechanismStateException.java b/libjava/classpath/gnu/javax/crypto/sasl/IllegalMechanismStateException.java
index b46ad98..547ac41 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/IllegalMechanismStateException.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/IllegalMechanismStateException.java
@@ -47,9 +47,9 @@ import javax.security.sasl.AuthenticationException;
* invoked on incomplete mechanisms was invoked but the authentication phase of
* that mechanism was already completed.
*/
-public class IllegalMechanismStateException extends AuthenticationException
+public class IllegalMechanismStateException
+ extends AuthenticationException
{
-
/**
* Constructs a new instance of IllegalMechanismStateException
* with no detail message.
@@ -62,7 +62,7 @@ public class IllegalMechanismStateException extends AuthenticationException
/**
* Constructs a new instance of IllegalMechanismStateException
* with the specified detail message.
- *
+ *
* @param detail the detail message.
*/
public IllegalMechanismStateException(String detail)
@@ -73,7 +73,7 @@ public class IllegalMechanismStateException extends AuthenticationException
/**
* Constructs a new instance of IllegalMechanismStateException
* with the specified detail message, and cause.
- *
+ *
* @param detail the detail message.
* @param ex the original cause.
*/
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/InputBuffer.java b/libjava/classpath/gnu/javax/crypto/sasl/InputBuffer.java
index a64ea3e..d676a59 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/InputBuffer.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/InputBuffer.java
@@ -45,39 +45,33 @@ import java.io.IOException;
import java.math.BigInteger;
/**
- * The implementation of an incoming SASL buffer.
- * - *The data elements this class caters for are described in [1].
- * - *References:
+ * The implementation of an incoming SASL buffer. + *+ * The data elements this class caters for are described in [1]. + *
+ * References: *
Constructs a SASL buffer given the buffer's encoded form, including its - * header bytes.
- * - * @param frame the encoded form, including the header bytes, of a SASL buffer. + * Constructs a SASL buffer given the buffer's encoded form, including its + * header bytes. + * + * @param frame the encoded form, including the header bytes, of a SASL + * buffer. * @throws SaslEncodingException if the buffer is malformed. */ public InputBuffer(byte[] frame) throws SaslEncodingException @@ -85,17 +79,13 @@ public class InputBuffer this(); if (frame.length < 4) - { - throw new SaslEncodingException("SASL buffer header too short"); - } - - length = (frame[0] & 0xFF) << 24 | (frame[1] & 0xFF) << 16 - | (frame[2] & 0xFF) << 8 | (frame[3] & 0xFF); + throw new SaslEncodingException("SASL buffer header too short"); + length = (frame[0] & 0xFF) << 24 + | (frame[1] & 0xFF) << 16 + | (frame[2] & 0xFF) << 8 + | (frame[3] & 0xFF); if (length > Registry.SASL_BUFFER_MAX_LIMIT || length < 0) - { - throw new SaslEncodingException("SASL buffer size limit exceeded"); - } - + throw new SaslEncodingException("SASL buffer size limit exceeded"); in = new ByteArrayInputStream(frame, 4, length); } @@ -105,16 +95,13 @@ public class InputBuffer super(); } - // Class methods - // ------------------------------------------------------------------------- - /** - *Returns an instance of a SASL buffer given the buffer's encoded contents, - * excluding the buffer's header bytes.
- * - *Calls the method with the same name and three arguments as: + * Returns an instance of a SASL buffer given the buffer's encoded contents, + * excluding the buffer's header bytes. + *
+ * Calls the method with the same name and three arguments as:
* getInstance(raw, 0, raw.length)
.
- *
+ *
* @param raw the encoded form, excluding the header bytes, of a SASL buffer.
* @return a new instance of {@link InputBuffer}.
*/
@@ -124,9 +111,9 @@ public class InputBuffer
}
/**
- *
Returns an instance of a SASL buffer given the buffer's encoded - * contents, excluding the buffer's header bytes.
- * + * Returns an instance of a SASL buffer given the buffer's encoded contents, + * excluding the buffer's header bytes. + * * @param raw the encoded form, excluding the header bytes, of a SASL buffer. * @param offset offset where to start using raw bytes from. * @param len number of bytes to use. @@ -140,21 +127,8 @@ public class InputBuffer } /** - *Converts four octets into the number that they represent.
- * - * @param b the four octets. - * @return the length. - */ - // public static int fourBytesToLength(byte[] b) throws SaslEncodingException { - // int result = b[0] << 24 | (b[1] & 0xFF) << 16 | (b[2] & 0xFF) << 8 | (b[3] & 0xFF); - // if (result > Registry.SASL_FOUR_BYTE_MAX_LIMIT || result < 0) { - // throw new SaslEncodingException("SASL EOS size limit exceeded"); - // } - // return result; - // } - /** - *Converts two octets into the number that they represent.
- * + * Converts two octets into the number that they represent. + * * @param b the two octets. * @return the length. */ @@ -162,49 +136,37 @@ public class InputBuffer { final int result = (b[0] & 0xFF) << 8 | (b[1] & 0xFF); if (result > Registry.SASL_TWO_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL MPI/Text size limit exceeded"); - } + throw new SaslEncodingException("SASL MPI/Text size limit exceeded"); return result; } - // Instance methods - // ------------------------------------------------------------------------- - public boolean hasMoreElements() { return (in.available() > 0); } /** - *Decodes a SASL scalar quantity, count
-octet long, from the
- * current buffer.
count
-octet long, from the
+ * current buffer.
+ *
* @param count the number of octets of this scalar quantity.
- * @return a native representation of a SASL scalar (unsigned integer) quantity.
+ * @return a native representation of a SASL scalar (unsigned integer)
+ * quantity.
* @throws SaslEncodingException if an encoding exception occurs during the
- * operation.
+ * operation.
* @throws IOException if any other I/O exception occurs during the operation.
*/
public long getScalar(int count) throws IOException
{
if (count < 0 || count > 4)
- {
- throw new SaslEncodingException("Invalid SASL scalar octet count: "
- + String.valueOf(count));
- }
- if (!hasMoreElements())
- {
- throw new SaslEncodingException(
- "Not enough bytes for a scalar in buffer");
- }
+ throw new SaslEncodingException("Invalid SASL scalar octet count: "
+ + String.valueOf(count));
+ if (! hasMoreElements())
+ throw new SaslEncodingException("Not enough bytes for a scalar in buffer");
if (in.available() < count)
- {
- throw new SaslEncodingException("Illegal SASL scalar encoding");
- }
+ throw new SaslEncodingException("Illegal SASL scalar encoding");
byte[] element = new byte[count];
in.read(element);
-
long result = 0L;
for (int i = 0; i < count; i++)
{
@@ -215,125 +177,96 @@ public class InputBuffer
}
/**
- * Decodes a SASL OS from the current buffer.
- * + * Decodes a SASL OS from the current buffer. + * * @return a native representation of a SASL OS. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws IOException if any other I/O exception occurs during the operation. */ public byte[] getOS() throws IOException { - if (!hasMoreElements()) - { - throw new SaslEncodingException( - "Not enough bytes for an octet-sequence in buffer"); - } + if (! hasMoreElements()) + throw new SaslEncodingException( + "Not enough bytes for an octet-sequence in buffer"); final int elementLength = in.read(); if (elementLength > Registry.SASL_ONE_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException( - "SASL octet-sequence size limit exceeded"); - } - + throw new SaslEncodingException("SASL octet-sequence size limit exceeded"); if (in.available() < elementLength) - { - throw new SaslEncodingException("Illegal SASL octet-sequence encoding"); - } - + throw new SaslEncodingException("Illegal SASL octet-sequence encoding"); byte[] result = new byte[elementLength]; in.read(result); - return result; } /** - *Decodes a SASL EOS from the current buffer.
- * + * Decodes a SASL EOS from the current buffer. + * * @return a native representation of a SASL EOS. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws IOException if any other I/O exception occurs during the operation. */ public byte[] getEOS() throws IOException { if (in.available() < 2) - { - throw new SaslEncodingException( - "Not enough bytes for an extended octet-sequence in buffer"); - } - + throw new SaslEncodingException( + "Not enough bytes for an extended octet-sequence in buffer"); byte[] elementLengthBytes = new byte[2]; in.read(elementLengthBytes); final int elementLength = twoBytesToLength(elementLengthBytes); if (in.available() < elementLength) - { - throw new SaslEncodingException( - "Illegal SASL extended octet-sequence encoding"); - } - + throw new SaslEncodingException( + "Illegal SASL extended octet-sequence encoding"); byte[] result = new byte[elementLength]; in.read(result); - return result; } /** - *Decodes a SASL MPI from the current buffer.
- * + * Decodes a SASL MPI from the current buffer. + * * @return a native representation of a SASL MPI. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws IOException if any other I/O exception occurs during the operation. */ public BigInteger getMPI() throws IOException { if (in.available() < 2) - { - throw new SaslEncodingException("Not enough bytes for an MPI in buffer"); - } + throw new SaslEncodingException("Not enough bytes for an MPI in buffer"); byte[] elementLengthBytes = new byte[2]; in.read(elementLengthBytes); final int elementLength = twoBytesToLength(elementLengthBytes); if (in.available() < elementLength) - { - throw new SaslEncodingException( - "Illegal SASL multi-precision integer encoding"); - } - + throw new SaslEncodingException( + "Illegal SASL multi-precision integer encoding"); byte[] element = new byte[elementLength]; in.read(element); - return new BigInteger(1, element); } /** - *Decodes a SASL Text from the current buffer.
- * + * Decodes a SASL Text from the current buffer. + * * @return a native representation of a SASL Text. * @throws SaslEncodingException if an encoding exception occurs during the - * operation. + * operation. * @throws SaslEncodingException if the UTF-8 character encoding is not - * supported on this platform. + * supported on this platform. * @throws IOException if any other I/O exception occurs during the operation. */ public String getText() throws IOException { if (in.available() < 2) - { - throw new SaslEncodingException("Not enough bytes for a text in buffer"); - } + throw new SaslEncodingException("Not enough bytes for a text in buffer"); byte[] elementLengthBytes = new byte[2]; in.read(elementLengthBytes); final int elementLength = twoBytesToLength(elementLengthBytes); if (in.available() < elementLength) - { - throw new SaslEncodingException("Illegal SASL text encoding"); - } - + throw new SaslEncodingException("Illegal SASL text encoding"); byte[] element = new byte[elementLength]; in.read(element); - return new String(element, "UTF8"); } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/IntegrityException.java b/libjava/classpath/gnu/javax/crypto/sasl/IntegrityException.java index 4a56ca2d..9b793ce 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/IntegrityException.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/IntegrityException.java @@ -46,9 +46,9 @@ import javax.security.sasl.SaslException; * processing of an integrity protection filter, including replay * detection. */ -public class IntegrityException extends SaslException +public class IntegrityException + extends SaslException { - /** * Constructs a new instance ofIntegrityException
with no
* detail message.
@@ -61,7 +61,7 @@ public class IntegrityException extends SaslException
/**
* Constructs a new instance of IntegrityException
with the
* specified detail message.
- *
+ *
* @param s the detail message.
*/
public IntegrityException(String s)
@@ -72,7 +72,7 @@ public class IntegrityException extends SaslException
/**
* Constructs a new instance of IntegrityException
with a
* detailed message and a root exception.
- *
+ *
* @param s possibly null additional detail about the exception.
* @param x a possibly null root exception that caused this one.
*/
@@ -80,4 +80,4 @@ public class IntegrityException extends SaslException
{
super(s, x);
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/NoSuchMechanismException.java b/libjava/classpath/gnu/javax/crypto/sasl/NoSuchMechanismException.java
index 6543208..5b16a78 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/NoSuchMechanismException.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/NoSuchMechanismException.java
@@ -44,19 +44,19 @@ import javax.security.sasl.SaslException;
* A checked exception thrown to indicate that a designated SASL mechanism
* implementation was not found.
*/
-public class NoSuchMechanismException extends SaslException
+public class NoSuchMechanismException
+ extends SaslException
{
-
/**
* Constructs a NoSuchMechanismException
with the specified
* detail message. In the case of this exception, the detail message
* designates the offending mechanism name.
- *
+ *
* @param arg the detail message, which in this case is the offending
- * mechanism name.
+ * mechanism name.
*/
public NoSuchMechanismException(String arg)
{
super(arg);
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java b/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java
index fe362c7..387339f 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/NoSuchUserException.java
@@ -44,9 +44,9 @@ import javax.security.sasl.AuthenticationException;
* A checked exception thrown to indicate that a designated user is unknown to
* the authentication layer.
*/
-public class NoSuchUserException extends AuthenticationException
+public class NoSuchUserException
+ extends AuthenticationException
{
-
/** Constructs a NoSuchUserException
with no detail message. */
public NoSuchUserException()
{
@@ -55,9 +55,9 @@ public class NoSuchUserException extends AuthenticationException
/**
* Constructs a NoSuchUserException
with the specified detail
- * message. In the case of this exception, the detail message designates
- * the offending username.
- *
+ * message. In the case of this exception, the detail message designates the
+ * offending username.
+ *
* @param arg the detail message, which in this case is the username.
*/
public NoSuchUserException(String arg)
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/OutputBuffer.java b/libjava/classpath/gnu/javax/crypto/sasl/OutputBuffer.java
index d219e7e..92e34df 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/OutputBuffer.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/OutputBuffer.java
@@ -46,31 +46,25 @@ import java.io.IOException;
import java.math.BigInteger;
/**
- * The implementation of an outgoing SASL buffer.
- * - *The data elements this class caters for are described in [1].
- * - *References:
+ * The implementation of an outgoing SASL buffer. + *+ * The data elements this class caters for are described in [1]. + *
+ * References: *
Encodes a SASL scalar quantity, count
-octet long, to the
- * current buffer.
count
-octet long, to the
+ * current buffer.
+ *
* @param count number of octets to encode b
with.
* @param b the scalar quantity.
* @throws SaslEncodingException if an encoding size constraint is violated.
@@ -96,21 +84,17 @@ public class OutputBuffer
public void setScalar(int count, int b) throws IOException
{
if (count < 0 || count > 4)
- {
- throw new SaslEncodingException("Invalid SASL scalar octet count: "
- + String.valueOf(count));
- }
+ throw new SaslEncodingException("Invalid SASL scalar octet count: "
+ + String.valueOf(count));
byte[] element = new byte[count];
for (int i = count; --i >= 0; b >>>= 8)
- {
- element[i] = (byte) b;
- }
+ element[i] = (byte) b;
out.write(element);
}
/**
- * Encodes a SASL OS to the current buffer.
- * + * Encodes a SASL OS to the current buffer. + * * @param b the OS element. * @throws SaslEncodingException if an encoding size constraint is violated. * @throws IOException if any other I/O exception occurs during the operation. @@ -119,16 +103,14 @@ public class OutputBuffer { final int length = b.length; if (length > Registry.SASL_ONE_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL octet-sequence too long"); - } + throw new SaslEncodingException("SASL octet-sequence too long"); out.write(length & 0xFF); out.write(b); } /** - *Encodes a SASL EOS to the current buffer.
- * + * Encodes a SASL EOS to the current buffer. + * * @param b the EOS element. * @throws SaslEncodingException if an encoding size constraint is violated. * @throws IOException if any other I/O exception occurs during the operation. @@ -137,17 +119,15 @@ public class OutputBuffer { final int length = b.length; if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL extended octet-sequence too long"); - } - byte[] lengthBytes = { (byte) (length >>> 8), (byte) length }; + throw new SaslEncodingException("SASL extended octet-sequence too long"); + byte[] lengthBytes = { (byte)(length >>> 8), (byte) length }; out.write(lengthBytes); out.write(b); } /** - *Encodes a SASL MPI to the current buffer.
- * + * Encodes a SASL MPI to the current buffer. + * * @param val the MPI element. * @throws SaslEncodingException if an encoding size constraint is violated. * @throws IOException if any other I/O exception occurs during the operation. @@ -157,21 +137,19 @@ public class OutputBuffer byte[] b = Util.trim(val); final int length = b.length; if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL multi-precision integer too long"); - } - byte[] lengthBytes = { (byte) (length >>> 8), (byte) length }; + throw new SaslEncodingException("SASL multi-precision integer too long"); + byte[] lengthBytes = { (byte)(length >>> 8), (byte) length }; out.write(lengthBytes); out.write(b); } /** - *Encodes a SASL Text to the current buffer.
- * + * Encodes a SASL Text to the current buffer. + * * @param str the Text element. * @throws SaslEncodingException if an encoding size constraint is violated. * @throws SaslEncodingException if the UTF-8 encoding is not supported on - * this platform. + * this platform. * @throws IOException if any other I/O exception occurs during the operation. */ public void setText(String str) throws IOException @@ -179,18 +157,16 @@ public class OutputBuffer byte[] b = str.getBytes("UTF8"); final int length = b.length; if (length > Registry.SASL_TWO_BYTE_MAX_LIMIT) - { - throw new SaslEncodingException("SASL text too long"); - } - byte[] lengthBytes = { (byte) (length >>> 8), (byte) length }; + throw new SaslEncodingException("SASL text too long"); + byte[] lengthBytes = { (byte)(length >>> 8), (byte) length }; out.write(lengthBytes); out.write(b); } /** - *Returns the encoded form of the current buffer including the 4-byte - * length header.
- * + * Returns the encoded form of the current buffer including the 4-byte length + * header. + * * @throws SaslEncodingException if an encoding size constraint is violated. */ public byte[] encode() throws SaslEncodingException @@ -198,28 +174,25 @@ public class OutputBuffer byte[] buffer = wrap(); final int length = buffer.length; byte[] result = new byte[length + 4]; - result[0] = (byte) (length >>> 24); - result[1] = (byte) (length >>> 16); - result[2] = (byte) (length >>> 8); + result[0] = (byte)(length >>> 24); + result[1] = (byte)(length >>> 16); + result[2] = (byte)(length >>> 8); result[3] = (byte) length; System.arraycopy(buffer, 0, result, 4, length); - return result; } /** - *Returns the encoded form of the current buffer excluding the 4-byte - * length header.
- * + * Returns the encoded form of the current buffer excluding the 4-byte length + * header. + * * @throws SaslEncodingException if an encoding size constraint is violated. */ public byte[] wrap() throws SaslEncodingException { final int length = out.size(); if (length > Registry.SASL_BUFFER_MAX_LIMIT || length < 0) - { - throw new SaslEncodingException("SASL buffer too long"); - } + throw new SaslEncodingException("SASL buffer too long"); return out.toByteArray(); } } diff --git a/libjava/classpath/gnu/javax/crypto/sasl/SaslEncodingException.java b/libjava/classpath/gnu/javax/crypto/sasl/SaslEncodingException.java index 9f4c59f..f6a7464 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/SaslEncodingException.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/SaslEncodingException.java @@ -44,9 +44,9 @@ import javax.security.sasl.SaslException; * A checked exception, thrown when an exception occurs while decoding a SASL * buffer and/or a SASL data element from/to a buffer. */ -public class SaslEncodingException extends SaslException +public class SaslEncodingException + extends SaslException { - /** Constructs aSaslEncodingException
with no detail message. */
public SaslEncodingException()
{
@@ -56,11 +56,11 @@ public class SaslEncodingException extends SaslException
/**
* Constructs a SaslEncodingException
with the specified detail
* message.
- *
+ *
* @param s the detail message.
*/
public SaslEncodingException(String s)
{
super(s);
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/SaslInputStream.java b/libjava/classpath/gnu/javax/crypto/sasl/SaslInputStream.java
index 57eb2b5..d127bf5 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/SaslInputStream.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/SaslInputStream.java
@@ -38,12 +38,13 @@ exception statement from your version. */
package gnu.javax.crypto.sasl;
+import gnu.java.security.Configuration;
import gnu.java.security.util.Util;
+import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
-import java.io.IOException;
-import java.io.PrintWriter;
+import java.util.logging.Logger;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
@@ -53,55 +54,24 @@ import javax.security.sasl.SaslServer;
* An input stream that uses either a {@link SaslClient} or a {@link SaslServer}
* to process the data through these entities' security layer filter(s).
*/
-public class SaslInputStream extends InputStream
+public class SaslInputStream
+ extends InputStream
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "SaslOutputStream";
-
- private static final String ERROR = "ERROR";
-
- private static final String WARN = " WARN";
-
- // private static final String INFO = " INFO";
- private static final String TRACE = "DEBUG";
-
- private static final boolean DEBUG = true;
-
- private static final int debuglevel = 3;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String level, Object obj)
- {
- err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj));
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(SaslInputStream.class.getName());
private SaslClient client;
-
private SaslServer server;
-
private int maxRawSendSize;
-
private InputStream source;
-
private byte[] internalBuf;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public SaslInputStream(SaslClient client, InputStream source)
throws IOException
{
super();
this.client = client;
- maxRawSendSize = Integer.parseInt((String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE));
+ String size = (String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
+ maxRawSendSize = Integer.parseInt(size);
server = null;
this.source = source;
}
@@ -112,19 +82,12 @@ public class SaslInputStream extends InputStream
super();
this.server = server;
- maxRawSendSize = Integer.parseInt((String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE));
+ String size = (String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
+ maxRawSendSize = Integer.parseInt(size);
client = null;
this.source = source;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Instance methods
- // -------------------------------------------------------------------------
-
- // Overloaded java.io.InputStream methods ----------------------------------
-
public int available() throws IOException
{
return (internalBuf == null) ? 0 : internalBuf.length;
@@ -136,25 +99,25 @@ public class SaslInputStream extends InputStream
}
/**
- * Reads the next byte of data from the input stream. The value byte is
+ * Reads the next byte of data from the input stream. The value byte is
* returned as an int
in the range 0
to
* 255
. If no byte is available because the end of the stream
* has been reached, the value -1
is returned. This method
- * blocks until input data is available, the end of the stream is detected,
- * or an exception is thrown.
From a SASL mechanism provider's perspective, if a security layer has - * been negotiated, the underlying source is expected to contain SASL + * blocks until input data is available, the end of the stream is detected, or + * an exception is thrown. + *
+ * From a SASL mechanism provider's perspective, if a security layer has been + * negotiated, the underlying source is expected to contain SASL * buffers, as defined in RFC 2222. Four octets in network byte order in the * front of each buffer identify the length of the buffer. The provider is * responsible for performing any integrity checking or other processing on * the buffer before returning the data as a stream of octets. For example, * the protocol driver's request for a single octet from the stream might; * i.e. an invocation of this method, may result in an entire SASL buffer - * being read and processed before that single octet can be returned.
- * - * @return the next byte of data, or-1
if the end of the stream
- * is reached.
+ * being read and processed before that single octet can be returned.
+ *
+ * @return the next byte of data, or -1
if the end of the
+ * stream is reached.
* @throws IOException if an I/O error occurs.
*/
public int read() throws IOException
@@ -168,7 +131,6 @@ public class SaslInputStream extends InputStream
else
{
byte[] tmp = new byte[internalBuf.length - 1];
- // System.arraycopy(internalBuf, 0, tmp, 0, tmp.length);
System.arraycopy(internalBuf, 1, tmp, 0, tmp.length);
internalBuf = tmp;
}
@@ -179,94 +141,83 @@ public class SaslInputStream extends InputStream
int check = read(buf);
result = (check > 0) ? (buf[0] & 0xFF) : -1;
}
-
return result;
}
/**
- * Reads up to len
bytes of data from the underlying
- * source input stream into an array of bytes. An attempt is made to
- * read as many as len
bytes, but a smaller number may be read,
- * possibly zero. The number of bytes actually read is returned as an
- * integer.
This method blocks until input data is available, end of file is - * detected, or an exception is thrown.
- * - *If b
is null
, a {@link NullPointerException} is
- * thrown.
If off
is negative, or len
is negative, or
- * off+len
is greater than the length of the array b
,
- * then an {@link IndexOutOfBoundsException} is thrown.
If len
is zero, then no bytes are read and 0
+ * Reads up to len
bytes of data from the underlying source
+ * input stream into an array of bytes. An attempt is made to read as many as
+ * len
bytes, but a smaller number may be read, possibly zero.
+ * The number of bytes actually read is returned as an integer.
+ *
+ * This method blocks until input data is available, end of file is detected, + * or an exception is thrown. + *
+ * If b
is null
, a {@link NullPointerException}
+ * is thrown.
+ *
+ * If off
is negative, or len
is negative, or
+ * off+len
is greater than the length of the array
+ * b
, then an {@link IndexOutOfBoundsException} is thrown.
+ *
+ * If len
is zero, then no bytes are read and 0
* is returned; otherwise, there is an attempt to read at least one byte. If
* no byte is available because the stream is at end of file, the value
* -1
is returned; otherwise, at least one byte is read and
- * stored into b
.
The first byte read is stored into element b[off]
, the
- * next one into b[off+1]
, and so on. The number of bytes read
- * is, at most, equal to len
. Let k
be the number
+ * stored into b
.
+ *
+ * The first byte read is stored into element b[off]
, the next
+ * one into b[off+1]
, and so on. The number of bytes read is,
+ * at most, equal to len
. Let k
be the number
* of bytes actually read; these bytes will be stored in elements
* b[off]
through b[off+k-1]
, leaving elements
- * b[off+k]
through b[off+len-1]
unaffected.
In every case, elements b[0]
through b[off]
+ * b[off+k]
through b[off+len-1]
unaffected.
+ *
+ * In every case, elements b[0]
through b[off]
* and elements b[off+len]
through b[b.length-1]
- * are unaffected.
If the first byte cannot be read for any reason other than end of file, - * then an {@link IOException} is thrown. In particular, an {@link IOException} - * is thrown if the input stream has been closed.
- * - *From the SASL mechanism provider's perspective, if a security layer has + * are unaffected. + *
+ * If the first byte cannot be read for any reason other than end of file, + * then an {@link IOException} is thrown. In particular, an + * {@link IOException} is thrown if the input stream has been closed. + *
+ * From the SASL mechanism provider's perspective, if a security layer has * been negotiated, the underlying source is expected to contain SASL * buffers, as defined in RFC 2222. Four octets in network byte order in the * front of each buffer identify the length of the buffer. The provider is * responsible for performing any integrity checking or other processing on * the buffer before returning the data as a stream of octets. The protocol * driver's request for a single octet from the stream might result in an - * entire SASL buffer being read and processed before that single octet can - * be returned.
- * + * entire SASL buffer being read and processed before that single octet can be + * returned. + * * @param b the buffer into which the data is read. * @param off the start offset in arrayb
at which the data is
- * wricodeen.
+ * wricodeen.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or -1
- * if there is no more data because the end of the stream has been reached.
+ * if there is no more data because the end of the stream has been
+ * reached.
* @throws IOException if an I/O error occurs.
*/
public int read(byte[] b, int off, int len) throws IOException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> read(b, " + String.valueOf(off) + ", "
- + String.valueOf(len) + ")");
-
- if (b == null)
- {
- throw new NullPointerException("b");
- }
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "read", new Object[] {
+ b, Integer.valueOf(off), Integer.valueOf(len)
+ });
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length)
|| ((off + len) < 0))
- {
- throw new IndexOutOfBoundsException("off=" + String.valueOf(off)
- + ", len=" + String.valueOf(len)
- + ", b.length="
- + String.valueOf(b.length));
- }
+ throw new IndexOutOfBoundsException("off=" + off + ", len=" + len
+ + ", b.length=" + b.length);
if (len == 0)
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== read() --> 0");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "read", Integer.valueOf(0));
return 0;
}
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Available: " + String.valueOf(available()));
-
+ if (Configuration.DEBUG)
+ log.finer("Available: " + available());
int result = 0;
if (internalBuf == null || internalBuf.length < 1)
try
@@ -274,24 +225,26 @@ public class SaslInputStream extends InputStream
internalBuf = readSaslBuffer();
if (internalBuf == null)
{
- if (DEBUG && debuglevel > 4)
- debug(WARN, "Underlying stream empty. Returning -1");
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== read() --> -1");
+ if (Configuration.DEBUG)
+ {
+ log.finer("Underlying stream empty. Returning -1");
+ log.exiting(this.getClass().getName(), "read",
+ Integer.valueOf(-1));
+ }
return -1;
}
}
catch (InterruptedIOException x)
{
- if (DEBUG && debuglevel > 6)
- debug(TRACE, x);
- if (DEBUG && debuglevel > 4)
- debug(WARN, "Reading thread was interrupted. Returning -1");
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== read() --> -1");
+ if (Configuration.DEBUG)
+ {
+ log.finer("Reading thread was interrupted. Returning -1");
+ log.throwing(this.getClass().getName(), "read", x);
+ log.exiting(this.getClass().getName(), "read",
+ Integer.valueOf(-1));
+ }
return -1;
}
-
if (len <= internalBuf.length)
{
result = len;
@@ -311,10 +264,8 @@ public class SaslInputStream extends InputStream
result = internalBuf.length;
System.arraycopy(internalBuf, 0, b, off, result);
internalBuf = null;
-
off += result;
len -= result;
-
int remaining; // count of bytes remaining in buffer after an iteration
int delta; // count of bytes moved to b after an iteration
int datalen;
@@ -328,13 +279,11 @@ public class SaslInputStream extends InputStream
data = readSaslBuffer();
if (data == null)
{
- if (DEBUG && debuglevel > 4)
- debug(WARN, "Underlying stream exhausted. Breaking...");
+ if (Configuration.DEBUG)
+ log.finer("Underlying stream exhausted. Breaking...");
break;
}
-
datalen = data.length;
-
// copy [part of] the result to b
remaining = (datalen <= len) ? 0 : datalen - len;
delta = datalen - remaining;
@@ -344,7 +293,6 @@ public class SaslInputStream extends InputStream
internalBuf = new byte[remaining];
System.arraycopy(data, delta, internalBuf, 0, remaining);
}
-
// update off, result and len
off += delta;
result += delta;
@@ -352,36 +300,32 @@ public class SaslInputStream extends InputStream
}
else
{ // nothing much we can do except return what we have
- if (DEBUG && debuglevel > 4)
- debug(WARN,
- "Not enough bytes in source to read a buffer. Breaking...");
+ if (Configuration.DEBUG)
+ log.finer("Not enough bytes in source to read a buffer. Breaking...");
break;
}
}
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Remaining: "
- + (internalBuf == null ? 0 : internalBuf.length));
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== read() --> " + String.valueOf(result));
+ if (Configuration.DEBUG)
+ {
+ log.finer("Remaining: "
+ + (internalBuf == null ? 0 : internalBuf.length));
+ log.exiting(this.getClass().getName(), "read()", String.valueOf(result));
+ }
return result;
}
- // other nstance methods ---------------------------------------------------
-
/**
* Reads a SASL buffer from the underlying source if at least 4 bytes are
* available.
- *
+ *
* @return the byte[] of decoded buffer contents, or null if the underlying
- * source was exhausted.
+ * source was exhausted.
* @throws IOException if an I/O exception occurs during the operation.
*/
private byte[] readSaslBuffer() throws IOException
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> readSaslBuffer()");
-
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "readSaslBuffer()");
int realLength; // check if we read as many bytes as we're supposed to
byte[] result = new byte[4];
try
@@ -389,32 +333,27 @@ public class SaslInputStream extends InputStream
realLength = source.read(result);
if (realLength == -1)
{
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== readSaslBuffer() --> null");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "readSaslBuffer");
return null;
}
}
catch (IOException x)
{
- if (DEBUG && debuglevel > 0)
- debug(ERROR, x);
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "readSaslBuffer", x);
throw x;
}
-
if (realLength != 4)
- {
- throw new IOException("Was expecting 4 but found "
- + String.valueOf(realLength));
- }
- int bufferLength = result[0] << 24 | (result[1] & 0xFF) << 16
- | (result[2] & 0xFF) << 8 | (result[3] & 0xFF);
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "SASL buffer size: " + bufferLength);
+ throw new IOException("Was expecting 4 but found " + realLength);
+ int bufferLength = result[0] << 24
+ | (result[1] & 0xFF) << 16
+ | (result[2] & 0xFF) << 8
+ | (result[3] & 0xFF);
+ if (Configuration.DEBUG)
+ log.finer("SASL buffer size: " + bufferLength);
if (bufferLength > maxRawSendSize || bufferLength < 0)
- {
- throw new SaslEncodingException("SASL buffer (security layer) too long");
- }
+ throw new SaslEncodingException("SASL buffer (security layer) too long");
result = new byte[bufferLength];
try
@@ -423,37 +362,32 @@ public class SaslInputStream extends InputStream
}
catch (IOException x)
{
- if (DEBUG && debuglevel > 0)
- debug(ERROR, x);
+ if (Configuration.DEBUG)
+ log.throwing(this.getClass().getName(), "readSaslBuffer", x);
throw x;
}
-
if (realLength != bufferLength)
- throw new IOException("Was expecting " + String.valueOf(bufferLength)
- + " but found " + String.valueOf(realLength));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (before security) (hex): "
- + Util.dumpString(result));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (before security) (str): \""
- + new String(result) + "\"");
-
- if (client != null)
+ throw new IOException("Was expecting " + bufferLength + " but found "
+ + realLength);
+ if (Configuration.DEBUG)
{
- result = client.unwrap(result, 0, realLength);
+ log.finer("Incoming buffer (before security) (hex): "
+ + Util.dumpString(result));
+ log.finer("Incoming buffer (before security) (str): \""
+ + new String(result) + "\"");
}
+ if (client != null)
+ result = client.unwrap(result, 0, realLength);
else
+ result = server.unwrap(result, 0, realLength);
+ if (Configuration.DEBUG)
{
- result = server.unwrap(result, 0, realLength);
+ log.finer("Incoming buffer (after security) (hex): "
+ + Util.dumpString(result));
+ log.finer("Incoming buffer (after security) (str): \""
+ + new String(result) + "\"");
+ log.exiting(this.getClass().getName(), "readSaslBuffer");
}
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (after security) (hex): "
- + Util.dumpString(result));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Incoming buffer (after security) (str): \""
- + new String(result) + "\"");
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== readSaslBuffer()");
return result;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/SaslOutputStream.java b/libjava/classpath/gnu/javax/crypto/sasl/SaslOutputStream.java
index 6997201..d21f1f3 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/SaslOutputStream.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/SaslOutputStream.java
@@ -38,11 +38,12 @@ exception statement from your version. */
package gnu.javax.crypto.sasl;
+import gnu.java.security.Configuration;
import gnu.java.security.util.Util;
-import java.io.OutputStream;
import java.io.IOException;
-import java.io.PrintWriter;
+import java.io.OutputStream;
+import java.util.logging.Logger;
import javax.security.sasl.Sasl;
import javax.security.sasl.SaslClient;
@@ -52,51 +53,23 @@ import javax.security.sasl.SaslServer;
* An output stream that uses either a {@link SaslClient} or a {@link SaslServer}
* to process the data through these entities' security layer filter(s).
*/
-public class SaslOutputStream extends OutputStream
+public class SaslOutputStream
+ extends OutputStream
{
-
- // Debugging methods and variables
- // -------------------------------------------------------------------------
-
- private static final String NAME = "SaslOutputStream";
-
- // private static final String ERROR = "ERROR";
- // private static final String WARN = " WARN";
- // private static final String INFO = " INFO";
- private static final String TRACE = "DEBUG";
-
- private static final boolean DEBUG = true;
-
- private static final int debuglevel = 3;
-
- private static final PrintWriter err = new PrintWriter(System.out, true);
-
- private static void debug(String level, Object obj)
- {
- err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj));
- }
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
+ private static final Logger log = Logger.getLogger(SaslOutputStream.class.getName());
private SaslClient client;
-
private SaslServer server;
-
private int maxRawSendSize;
-
private OutputStream dest;
- // Constructor(s)
- // -------------------------------------------------------------------------
-
public SaslOutputStream(SaslClient client, OutputStream dest)
throws IOException
{
super();
this.client = client;
- maxRawSendSize = Integer.parseInt((String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE));
+ String size = (String) client.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
+ maxRawSendSize = Integer.parseInt(size);
server = null;
this.dest = dest;
}
@@ -107,17 +80,12 @@ public class SaslOutputStream extends OutputStream
super();
this.server = server;
- maxRawSendSize = Integer.parseInt((String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE));
+ String size = (String) server.getNegotiatedProperty(Sasl.RAW_SEND_SIZE);
+ maxRawSendSize = Integer.parseInt(size);
client = null;
this.dest = dest;
}
- // Class methods
- // -------------------------------------------------------------------------
-
- // Overloaded java.io.OutputStream methods
- // -------------------------------------------------------------------------
-
public void close() throws IOException
{
dest.flush();
@@ -148,71 +116,60 @@ public class SaslOutputStream extends OutputStream
*/
public void write(byte[] b, int off, int len) throws IOException
{
- if (b == null)
- {
- throw new NullPointerException("b");
- }
+ if (Configuration.DEBUG)
+ log.entering(this.getClass().getName(), "write");
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length)
|| ((off + len) < 0))
- {
- throw new IndexOutOfBoundsException("off=" + String.valueOf(off)
- + ", len=" + String.valueOf(len)
- + ", b.length="
- + String.valueOf(b.length));
- }
+ throw new IndexOutOfBoundsException("off=" + off + ", len=" + len
+ + ", b.length=" + b.length);
if (len == 0)
{
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "write");
return;
}
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "==> write()");
-
int chunckSize, length, chunck = 1;
byte[] output = null, result;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "About to wrap " + String.valueOf(len) + " byte(s)...");
+ if (Configuration.DEBUG)
+ log.finer("About to wrap " + len + " byte(s)...");
while (len > 0)
{
chunckSize = (len > maxRawSendSize ? maxRawSendSize : len);
-
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (before security) (hex): "
- + Util.dumpString(b, off, chunckSize));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (before security) (str): \""
- + new String(b, off, chunckSize) + "\"");
-
+ if (Configuration.DEBUG)
+ {
+ log.finer("Outgoing buffer (before security) (hex): "
+ + Util.dumpString(b, off, chunckSize));
+ log.finer("Outgoing buffer (before security) (str): \""
+ + new String(b, off, chunckSize) + "\"");
+ }
if (client != null)
output = client.wrap(b, off, chunckSize);
else
output = server.wrap(b, off, chunckSize);
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (after security) (hex): "
- + Util.dumpString(output));
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Outgoing buffer (after security) (str): \""
- + new String(output) + "\"");
-
+ if (Configuration.DEBUG)
+ {
+ log.finer("Outgoing buffer (after security) (hex): "
+ + Util.dumpString(output));
+ log.finer("Outgoing buffer (after security) (str): \""
+ + new String(output) + "\"");
+ }
length = output.length;
result = new byte[length + 4];
- result[0] = (byte) (length >>> 24);
- result[1] = (byte) (length >>> 16);
- result[2] = (byte) (length >>> 8);
+ result[0] = (byte)(length >>> 24);
+ result[1] = (byte)(length >>> 16);
+ result[2] = (byte)(length >>> 8);
result[3] = (byte) length;
System.arraycopy(output, 0, result, 4, length);
-
dest.write(result);
-
off += chunckSize;
len -= chunckSize;
- if (DEBUG && debuglevel > 6)
- debug(TRACE, "Wrapped chunck #" + String.valueOf(chunck));
+ if (Configuration.DEBUG)
+ log.finer("Wrapped chunck #" + chunck);
chunck++;
}
-
dest.flush();
- if (DEBUG && debuglevel > 8)
- debug(TRACE, "<== write()");
+ if (Configuration.DEBUG)
+ log.exiting(this.getClass().getName(), "write");
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/SaslUtil.java b/libjava/classpath/gnu/javax/crypto/sasl/SaslUtil.java
index e70312c..4b0b697 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/SaslUtil.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/SaslUtil.java
@@ -40,7 +40,6 @@ package gnu.javax.crypto.sasl;
import gnu.java.security.util.Util;
-import java.math.BigInteger;
import java.security.MessageDigest;
/**
@@ -48,30 +47,17 @@ import java.security.MessageDigest;
*/
public class SaslUtil
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
private SaslUtil()
{
super();
}
- // Class methods
- // -------------------------------------------------------------------------
-
public static final boolean validEmailAddress(String address)
{
// need to do better than this
return (address.indexOf("@") != -1);
}
- // Visualisation methods
- // -------------------------------------------------------------------------
-
/** Returns the context of the designated hash as a string. */
public static final String dump(MessageDigest md)
{
@@ -86,4 +72,4 @@ public class SaslUtil
}
return result;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/ServerFactory.java b/libjava/classpath/gnu/javax/crypto/sasl/ServerFactory.java
index e9b08db..7aa3796 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/ServerFactory.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/ServerFactory.java
@@ -62,53 +62,33 @@ import javax.security.sasl.SaslServerFactory;
/**
* The implementation of the {@link SaslServerFactory}.
*/
-public class ServerFactory implements SaslServerFactory
+public class ServerFactory
+ implements SaslServerFactory
{
-
- // Constants and variables
- // -------------------------------------------------------------------------
-
- // Constructor(s)
- // -------------------------------------------------------------------------
-
// implicit 0-arguments constructor
- // Class methods
- // -------------------------------------------------------------------------
-
public static final Set getNames()
{
- return Collections.unmodifiableSet(new HashSet(
- Arrays.asList(getNamesInternal(null))));
+ return Collections.unmodifiableSet(new HashSet(Arrays.asList(getNamesInternal(null))));
}
private static final String[] getNamesInternal(Map props)
{
- String[] all = new String[] { Registry.SASL_SRP_MECHANISM,
- Registry.SASL_CRAM_MD5_MECHANISM,
- Registry.SASL_PLAIN_MECHANISM,
- Registry.SASL_ANONYMOUS_MECHANISM };
-
+ String[] all = new String[] {
+ Registry.SASL_SRP_MECHANISM,
+ Registry.SASL_CRAM_MD5_MECHANISM,
+ Registry.SASL_PLAIN_MECHANISM,
+ Registry.SASL_ANONYMOUS_MECHANISM };
List result = new ArrayList(4);
int i;
for (i = 0; i < all.length;)
- {
- result.add(all[i++]);
- }
-
+ result.add(all[i++]);
if (props == null)
- {
- return (String[]) result.toArray(new String[0]); // all
- }
- if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props))
- { // none
- return new String[0];
- }
-
+ return (String[]) result.toArray(new String[0]); // all
+ if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props)) // none
+ return new String[0];
if (hasPolicy(Sasl.POLICY_NOPLAINTEXT, props))
- {
- result.remove(Registry.SASL_PLAIN_MECHANISM);
- }
+ result.remove(Registry.SASL_PLAIN_MECHANISM);
if (hasPolicy(Sasl.POLICY_NOACTIVE, props))
{
result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
@@ -135,32 +115,19 @@ public class ServerFactory implements SaslServerFactory
public static final ServerMechanism getInstance(String mechanism)
{
if (mechanism == null)
- {
- return null;
- }
+ return null;
mechanism = mechanism.trim().toUpperCase();
if (mechanism.equals(Registry.SASL_SRP_MECHANISM))
- {
- return new SRPServer();
- }
+ return new SRPServer();
if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM))
- {
- return new CramMD5Server();
- }
+ return new CramMD5Server();
if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM))
- {
- return new PlainServer();
- }
+ return new PlainServer();
if (mechanism.equals(Registry.SASL_ANONYMOUS_MECHANISM))
- {
- return new AnonymousServer();
- }
+ return new AnonymousServer();
return null;
}
- // Instance methods
- // -------------------------------------------------------------------------
-
public SaslServer createSaslServer(String mechanism, String protocol,
String serverName, Map props,
CallbackHandler cbh) throws SaslException
@@ -170,13 +137,10 @@ public class ServerFactory implements SaslServerFactory
{
HashMap attributes = new HashMap();
if (props != null)
- {
- attributes.putAll(props);
- }
+ attributes.putAll(props);
attributes.put(Registry.SASL_PROTOCOL, protocol);
attributes.put(Registry.SASL_SERVER_NAME, serverName);
attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh);
-
result.init(attributes);
}
return result;
@@ -191,4 +155,4 @@ public class ServerFactory implements SaslServerFactory
{
return "true".equalsIgnoreCase(String.valueOf(props.get(propertyName)));
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/ServerMechanism.java b/libjava/classpath/gnu/javax/crypto/sasl/ServerMechanism.java
index f12a075..75603a1 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/ServerMechanism.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/ServerMechanism.java
@@ -45,51 +45,36 @@ import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslServer;
import javax.security.sasl.SaslException;
+import javax.security.sasl.SaslServer;
/**
- * A base class to facilitate implementing SASL server-side mechanisms.
+ * A base class to facilitate implementing SASL server-side mechanisms. */ -public abstract class ServerMechanism implements SaslServer +public abstract class ServerMechanism + implements SaslServer { - - // Constants and variables - // ------------------------------------------------------------------------- - /** Name of this mechanism. */ protected String mechanism; - /** Name of protocol using this mechanism. */ protected String protocol; - /** Name of server to authenticate to. */ protected String serverName; - /** Properties of qualities desired for this mechanism. */ protected Map properties; - /** Callback handler to use with this mechanism instance. */ protected CallbackHandler handler; - /** Whether authentication phase is completed (true) or not (false). */ protected boolean complete = false; - /** The authorisation identity. */ protected String authorizationID; - /** Channel binding data to use with this mechanism instance. */ protected byte[] channelBinding; - /** The state of the authentication automaton. -1 means uninitialised. */ protected int state = -1; - /** The provider for authentication information. */ protected IAuthInfoProvider authenticator; - // Constructor(s) - // ------------------------------------------------------------------------- - protected ServerMechanism(final String mechanism) { super(); @@ -99,20 +84,10 @@ public abstract class ServerMechanism implements SaslServer this.state = -1; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods to be implemented by concrete subclasses --------------- - protected abstract void initMechanism() throws SaslException; protected abstract void resetMechanism() throws SaslException; - // javax.security.sasl.SaslServer interface implementation ----------------- - public abstract byte[] evaluateResponse(byte[] response) throws SaslException; public boolean isComplete() @@ -123,20 +98,16 @@ public abstract class ServerMechanism implements SaslServer public byte[] unwrap(final byte[] incoming, final int offset, final int len) throws SaslException { - if (!isComplete()) - { - throw new IllegalMechanismStateException(); - } + if (! isComplete()) + throw new IllegalMechanismStateException(); return this.engineUnwrap(incoming, offset, len); } public byte[] wrap(final byte[] outgoing, final int offset, final int len) throws SaslException { - if (!isComplete()) - { - throw new IllegalMechanismStateException(); - } + if (! isComplete()) + throw new IllegalMechanismStateException(); return this.engineWrap(outgoing, offset, len); } @@ -152,58 +123,32 @@ public abstract class ServerMechanism implements SaslServer public Object getNegotiatedProperty(final String propName) { - if (!isComplete()) - { - throw new IllegalStateException(); - } + if (! isComplete()) + throw new IllegalStateException(); if (Sasl.QOP.equals(propName)) - { - return getNegotiatedQOP(); - } + return getNegotiatedQOP(); if (Sasl.STRENGTH.equals(propName)) - { - return getNegotiatedStrength(); - } + return getNegotiatedStrength(); if (Sasl.SERVER_AUTH.equals(propName)) - { - return getNegotiatedServerAuth(); - } + return getNegotiatedServerAuth(); if (Sasl.MAX_BUFFER.equals(propName)) - { - return getNegotiatedMaxBuffer(); - } + return getNegotiatedMaxBuffer(); if (Sasl.RAW_SEND_SIZE.equals(propName)) - { - return getNegotiatedRawSendSize(); - } + return getNegotiatedRawSendSize(); if (Sasl.POLICY_NOPLAINTEXT.equals(propName)) - { - return getNegotiatedPolicyNoPlainText(); - } + return getNegotiatedPolicyNoPlainText(); if (Sasl.POLICY_NOACTIVE.equals(propName)) - { - return getNegotiatedPolicyNoActive(); - } + return getNegotiatedPolicyNoActive(); if (Sasl.POLICY_NODICTIONARY.equals(propName)) - { - return getNegotiatedPolicyNoDictionary(); - } + return getNegotiatedPolicyNoDictionary(); if (Sasl.POLICY_NOANONYMOUS.equals(propName)) - { - return getNegotiatedPolicyNoAnonymous(); - } + return getNegotiatedPolicyNoAnonymous(); if (Sasl.POLICY_FORWARD_SECRECY.equals(propName)) - { - return getNegotiatedPolicyForwardSecrecy(); - } + return getNegotiatedPolicyForwardSecrecy(); if (Sasl.POLICY_PASS_CREDENTIALS.equals(propName)) - { - return getNegotiatedPolicyPassCredentials(); - } + return getNegotiatedPolicyPassCredentials(); if (Sasl.REUSE.equals(propName)) - { - return getReuse(); - } + return getReuse(); return null; } @@ -212,8 +157,6 @@ public abstract class ServerMechanism implements SaslServer reset(); } - // other Instance methods -------------------------------------------------- - protected String getNegotiatedQOP() { return Registry.QOP_AUTH; @@ -291,30 +234,23 @@ public abstract class ServerMechanism implements SaslServer } /** - *Initialises the mechanism with designated attributes. Permissible names - * and values are mechanism specific.
- * + * Initialises the mechanism with designated attributes. Permissible names and + * values are mechanism specific. + * * @param attributes a set of name-value pairs that describes the desired - * future behaviour of this instance. + * future behaviour of this instance. * @throws IllegalMechanismStateException if the instance is already - * initialised. + * initialised. * @throws SaslException if an exception occurs during the process. */ public void init(final Map attributes) throws SaslException { if (state != -1) - { - throw new IllegalMechanismStateException("init()"); - } - + throw new IllegalMechanismStateException("init()"); if (properties == null) - { - properties = new HashMap(); - } + properties = new HashMap(); else - { - properties.clear(); - } + properties.clear(); if (attributes != null) { protocol = (String) attributes.get(Registry.SASL_PROTOCOL); @@ -324,35 +260,24 @@ public abstract class ServerMechanism implements SaslServer properties.putAll(attributes); } else - { - handler = null; - } - + handler = null; if (protocol == null) - { - protocol = ""; - } + protocol = ""; if (serverName == null) - { - serverName = ""; - } + serverName = ""; if (authenticator != null) - { - authenticator.activate(properties); - } + authenticator.activate(properties); if (channelBinding == null) - { - channelBinding = new byte[0]; - } + channelBinding = new byte[0]; initMechanism(); complete = false; state = 0; } /** - *Resets the mechanism instance for re-initialisation and use with other - * characteristics.
- * + * Resets the mechanism instance for re-initialisation and use with other + * characteristics. + * * @throws SaslException if an exception occurs during the process. */ public void reset() throws SaslException @@ -360,12 +285,10 @@ public abstract class ServerMechanism implements SaslServer resetMechanism(); properties.clear(); if (authenticator != null) - { - authenticator.passivate(); - } + authenticator.passivate(); protocol = serverName = null; channelBinding = null; complete = false; state = -1; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/UserAlreadyExistsException.java b/libjava/classpath/gnu/javax/crypto/sasl/UserAlreadyExistsException.java index 764a36d..1563be9 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/UserAlreadyExistsException.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/UserAlreadyExistsException.java @@ -44,9 +44,9 @@ import javax.security.sasl.SaslException; * A checked exception thrown to indicate that a designated user is already * known to the the authentication layer. */ -public class UserAlreadyExistsException extends SaslException +public class UserAlreadyExistsException + extends SaslException { - /** * Constructs aUserAlreadyExistsException
with no detail
* message.
@@ -60,7 +60,7 @@ public class UserAlreadyExistsException extends SaslException
* Constructs a UserAlreadyExistsException
with the specified
* detail message. In the case of this exception, the detail message
* designates the offending username.
- *
+ *
* @param userName the detail message, which in this case is the username.
*/
public UserAlreadyExistsException(String userName)
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java b/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java
index f5b1faa..87f5e5f 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java
@@ -44,35 +44,22 @@ import gnu.javax.crypto.sasl.IllegalMechanismStateException;
import java.io.UnsupportedEncodingException;
+import javax.security.sasl.AuthenticationException;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslException;
-import javax.security.sasl.AuthenticationException;
/**
- * The ANONYMOUS client-side mechanism.
+ * The ANONYMOUS client-side mechanism. */ -public class AnonymousClient extends ClientMechanism implements SaslClient +public class AnonymousClient + extends ClientMechanism + implements SaslClient { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public AnonymousClient() { super(Registry.SASL_ANONYMOUS_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -81,8 +68,6 @@ public class AnonymousClient extends ClientMechanism implements SaslClient { } - // javax.security.sasl.SaslClient interface implementation ----------------- - public boolean hasInitialResponse() { return true; @@ -99,13 +84,10 @@ public class AnonymousClient extends ClientMechanism implements SaslClient private byte[] response() throws SaslException { - if (!AnonymousUtil.isValidTraceInformation(authorizationID)) - { - throw new AuthenticationException( - "Authorisation ID is not a valid email address"); - } + if (! AnonymousUtil.isValidTraceInformation(authorizationID)) + throw new AuthenticationException( + "Authorisation ID is not a valid email address"); complete = true; - // return authorizationID.getBytes(); final byte[] result; try { @@ -117,4 +99,4 @@ public class AnonymousClient extends ClientMechanism implements SaslClient } return result; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java b/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java index 2c10f78..7645604 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java @@ -50,28 +50,15 @@ import javax.security.sasl.SaslServer; /** * The ANONYMOUS server-side mechanism. */ -public class AnonymousServer extends ServerMechanism implements SaslServer +public class AnonymousServer + extends ServerMechanism + implements SaslServer { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public AnonymousServer() { super(Registry.SASL_ANONYMOUS_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -80,14 +67,10 @@ public class AnonymousServer extends ServerMechanism implements SaslServer { } - // javax.security.sasl.SaslServer interface implementation ----------------- - public byte[] evaluateResponse(final byte[] response) throws SaslException { if (response == null) - { - return null; - } + return null; try { authorizationID = new String(response, "UTF-8"); @@ -104,4 +87,4 @@ public class AnonymousServer extends ServerMechanism implements SaslServer authorizationID = null; throw new AuthenticationException("Invalid email address"); } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java b/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java index 99e95ea..9047ebd 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/anonymous/AnonymousUtil.java @@ -45,65 +45,39 @@ import gnu.javax.crypto.sasl.SaslUtil; */ public class AnonymousUtil { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - /** Trivial private constructor to enforce Singleton pattern. */ private AnonymousUtil() { super(); } - // Class methods - // ------------------------------------------------------------------------- - static boolean isValidTraceInformation(String traceInformation) { if (traceInformation == null) - { - return false; - } + return false; if (traceInformation.length() == 0) - { - return true; - } + return true; if (SaslUtil.validEmailAddress(traceInformation)) - { - return true; - } + return true; return isValidToken(traceInformation); } static boolean isValidToken(String token) { if (token == null) - { - return false; - } + return false; if (token.length() == 0) - { - return false; - } + return false; if (token.length() > 255) - { - return false; - } + return false; if (token.indexOf('@') != -1) - { - return false; - } + return false; for (int i = 0; i < token.length(); i++) { char c = token.charAt(i); if (c < 0x20 || c > 0x7E) - { - return false; - } + return false; } return true; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java index cf73b6f..dec0366 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java @@ -51,44 +51,26 @@ import javax.security.sasl.AuthenticationException; /** * The CRAM-MD5 mechanism authentication information provider implementation. */ -public class CramMD5AuthInfoProvider implements IAuthInfoProvider +public class CramMD5AuthInfoProvider + implements IAuthInfoProvider { - - // Constants and variables - // ------------------------------------------------------------------------- - private PasswordFile passwordFile = null; - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-args constrcutor - // Class methods - // ------------------------------------------------------------------------- - - // IAuthInfoProvider interface implementation - // ------------------------------------------------------------------------- - public void activate(Map context) throws AuthenticationException { try { if (context == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else { String pfn = (String) context.get(CramMD5Registry.PASSWORD_FILE); if (pfn == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else - { - passwordFile = new PasswordFile(pfn); - } + passwordFile = new PasswordFile(pfn); } } catch (IOException x) @@ -105,10 +87,8 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("contains()", - new IllegalStateException()); - } + throw new AuthenticationException("contains()", + new IllegalStateException()); boolean result = false; try { @@ -124,18 +104,13 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("lookup()", - new IllegalStateException()); - } + throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null) - { - throw new NoSuchUserException(""); - } + throw new NoSuchUserException(""); String[] data = passwordFile.lookup(userName); result.put(Registry.SASL_USERNAME, data[0]); result.put(Registry.SASL_PASSWORD, data[1]); @@ -148,9 +123,7 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("lookup()", x); } return result; @@ -159,10 +132,7 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider public void update(Map userCredentials) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("update()", - new IllegalStateException()); - } + throw new AuthenticationException("update()", new IllegalStateException()); try { String userName = (String) userCredentials.get(Registry.SASL_USERNAME); @@ -174,9 +144,7 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider String shell = (String) userCredentials.get(CramMD5Registry.SHELL_FIELD); if (uid == null || gid == null || gecos == null || dir == null || shell == null) - { - passwordFile.changePasswd(userName, password); - } + passwordFile.changePasswd(userName, password); else { String[] attributes = new String[] { uid, gid, gecos, dir, shell }; @@ -186,9 +154,7 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("update()", x); } } @@ -197,4 +163,4 @@ public class CramMD5AuthInfoProvider implements IAuthInfoProvider { throw new AuthenticationException("", new UnsupportedOperationException()); } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java index 094109f..c90cbe9 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java @@ -56,25 +56,15 @@ import javax.security.sasl.SaslException; /** * The CRAM-MD5 SASL client-side mechanism. */ -public class CramMD5Client extends ClientMechanism implements SaslClient +public class CramMD5Client + extends ClientMechanism + implements SaslClient { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public CramMD5Client() { super(Registry.SASL_CRAM_MD5_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -83,8 +73,6 @@ public class CramMD5Client extends ClientMechanism implements SaslClient { } - // javax.security.sasl.SaslClient interface implementation ----------------- - public boolean hasInitialResponse() { return false; @@ -93,30 +81,22 @@ public class CramMD5Client extends ClientMechanism implements SaslClient public byte[] evaluateChallenge(final byte[] challenge) throws SaslException { if (challenge == null) - { - throw new SaslException("null challenge"); - } + throw new SaslException("null challenge"); try { final String username; final char[] password; Callback[] callbacks; - - if ((!properties.containsKey(Registry.SASL_USERNAME)) - && (!properties.containsKey(Registry.SASL_PASSWORD))) + if ((! properties.containsKey(Registry.SASL_USERNAME)) + && (! properties.containsKey(Registry.SASL_PASSWORD))) { callbacks = new Callback[2]; - final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); final PasswordCallback pwdCB = new PasswordCallback("password: ", false); callbacks[0] = nameCB; @@ -128,47 +108,35 @@ public class CramMD5Client extends ClientMechanism implements SaslClient else { if (properties.containsKey(Registry.SASL_USERNAME)) - { - username = (String) properties.get(Registry.SASL_USERNAME); - } + username = (String) properties.get(Registry.SASL_USERNAME); else { callbacks = new Callback[1]; final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); callbacks[0] = nameCB; this.handler.handle(callbacks); username = nameCB.getName(); } if (properties.containsKey(Registry.SASL_PASSWORD)) - { - password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray(); - } + password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray(); else { callbacks = new Callback[1]; - final PasswordCallback pwdCB = new PasswordCallback( - "password: ", + final PasswordCallback pwdCB = new PasswordCallback("password: ", false); callbacks[0] = pwdCB; this.handler.handle(callbacks); password = pwdCB.getPassword(); } } - if (password == null) - { - throw new SaslException("null password supplied"); - } + throw new SaslException("null password supplied"); final byte[] digest; try { @@ -181,7 +149,6 @@ public class CramMD5Client extends ClientMechanism implements SaslClient final String response = username + " " + Util.toString(digest).toLowerCase(); this.complete = true; - return response.getBytes("UTF-8"); } catch (UnsupportedCallbackException x) @@ -198,4 +165,4 @@ public class CramMD5Client extends ClientMechanism implements SaslClient { return Registry.QOP_AUTH; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java index 1c61cac..bbd46a3 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Registry.java @@ -45,22 +45,16 @@ public interface CramMD5Registry { /** Name of the password file (used by the server) property. */ String PASSWORD_FILE = "gnu.crypto.sasl.crammd5.password.file"; - /** Default password file (used by the server) pathname. */ String DEFAULT_PASSWORD_FILE = "/etc/passwd"; - /** Name of the UID field in the plain password file. */ String UID_FIELD = "crammd5.uid"; - /** Name of the GID field in the plain password file. */ String GID_FIELD = "crammd5.gid"; - /** Name of the GECOS field in the plain password file. */ String GECOS_FIELD = "crammd5.gecos"; - /** Name of the DIR field in the plain password file. */ String DIR_FIELD = "crammd5.dir"; - /** Name of the SHELL field in the plain password file. */ String SHELL_FIELD = "crammd5.shell"; -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java index d6622b6..9be0341 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Server.java @@ -55,29 +55,19 @@ import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; /** - *The CRAM-MD5 SASL server-side mechanism.
+ * The CRAM-MD5 SASL server-side mechanism. */ -public class CramMD5Server extends ServerMechanism implements SaslServer +public class CramMD5Server + extends ServerMechanism + implements SaslServer { - - // Constants and variables - // ------------------------------------------------------------------------- - private byte[] msgID; - // Constructor(s) - // ------------------------------------------------------------------------- - public CramMD5Server() { super(Registry.SASL_CRAM_MD5_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -86,8 +76,6 @@ public class CramMD5Server extends ServerMechanism implements SaslServer { } - // javax.security.sasl.SaslServer interface implementation ----------------- - public byte[] evaluateResponse(final byte[] response) throws SaslException { if (state == 0) @@ -96,7 +84,6 @@ public class CramMD5Server extends ServerMechanism implements SaslServer state++; return msgID; } - final String responseStr = new String(response); final int index = responseStr.lastIndexOf(" "); final String username = responseStr.substring(0, index); @@ -109,10 +96,8 @@ public class CramMD5Server extends ServerMechanism implements SaslServer { throw new AuthenticationException("evaluateResponse()", x); } - // Look up the password final char[] password = lookupPassword(username); - // Compute the digest byte[] digest; try @@ -125,19 +110,15 @@ public class CramMD5Server extends ServerMechanism implements SaslServer } try { - // digest = (new String(Util.toString(digest).toLowerCase())).getBytes("UTF-8"); digest = Util.toString(digest).toLowerCase().getBytes("UTF-8"); } catch (UnsupportedEncodingException x) { throw new AuthenticationException("evaluateResponse()", x); } - // Compare the received and computed digests - if (!Arrays.equals(digest, responseDigest)) - { - throw new AuthenticationException("Digest mismatch"); - } + if (! Arrays.equals(digest, responseDigest)) + throw new AuthenticationException("Digest mismatch"); state++; return null; } @@ -152,34 +133,26 @@ public class CramMD5Server extends ServerMechanism implements SaslServer return Registry.QOP_AUTH; } - // Other instance methods -------------------------------------------------- - private char[] lookupPassword(final String userName) throws SaslException { try { - if (!authenticator.contains(userName)) - { - throw new NoSuchUserException(userName); - } + if (! authenticator.contains(userName)) + throw new NoSuchUserException(userName); final Map userID = new HashMap(); userID.put(Registry.SASL_USERNAME, userName); final Map credentials = authenticator.lookup(userID); final String password = (String) credentials.get(Registry.SASL_PASSWORD); if (password == null) - { - throw new AuthenticationException("lookupPassword()", - new InternalError()); - } + throw new AuthenticationException("lookupPassword()", + new InternalError()); return password.toCharArray(); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("lookupPassword()", x); } } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java index 6e75393..2145512 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java @@ -56,29 +56,17 @@ import javax.security.sasl.SaslException; */ class CramMD5Util { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - private CramMD5Util() { super(); } - // Class methods - // ------------------------------------------------------------------------- - static byte[] createMsgID() throws SaslException { - //The PLAIN SASL client-side mechanism.
+ * The PLAIN SASL client-side mechanism. */ -public class PlainClient extends ClientMechanism implements SaslClient +public class PlainClient + extends ClientMechanism + implements SaslClient { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public PlainClient() { super(Registry.SASL_PLAIN_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -80,8 +67,6 @@ public class PlainClient extends ClientMechanism implements SaslClient { } - // javax.security.sasl.SaslClient interface implementation ----------------- - public boolean hasInitialResponse() { return true; @@ -94,22 +79,16 @@ public class PlainClient extends ClientMechanism implements SaslClient final String username; final char[] password; Callback[] callbacks; - - if ((!properties.containsKey(Registry.SASL_USERNAME)) - && (!properties.containsKey(Registry.SASL_PASSWORD))) + if ((! properties.containsKey(Registry.SASL_USERNAME)) + && (! properties.containsKey(Registry.SASL_PASSWORD))) { callbacks = new Callback[2]; - final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); final PasswordCallback pwdCB = new PasswordCallback("password: ", false); callbacks[0] = nameCB; @@ -121,67 +100,49 @@ public class PlainClient extends ClientMechanism implements SaslClient else { if (properties.containsKey(Registry.SASL_USERNAME)) - { - username = (String) properties.get(Registry.SASL_USERNAME); - } + username = (String) properties.get(Registry.SASL_USERNAME); else { callbacks = new Callback[1]; final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); callbacks[0] = nameCB; this.handler.handle(callbacks); username = nameCB.getName(); } - if (properties.containsKey(Registry.SASL_PASSWORD)) - { - password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray(); - } + password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray(); else { callbacks = new Callback[1]; - final PasswordCallback pwdCB = new PasswordCallback( - "password: ", + final PasswordCallback pwdCB = new PasswordCallback("password: ", false); callbacks[0] = pwdCB; this.handler.handle(callbacks); password = pwdCB.getPassword(); } } - if (password == null) - { - throw new SaslException("null password supplied"); - } + throw new SaslException("null password supplied"); final StringBuffer sb = new StringBuffer(); if (authorizationID != null) - { - sb.append(authorizationID); - } + sb.append(authorizationID); sb.append('\0'); sb.append(username); sb.append('\0'); sb.append(password); this.complete = true; - final byte[] response = sb.toString().getBytes("UTF-8"); return response; } catch (Exception x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("evaluateChallenge()", x); } } @@ -190,4 +151,4 @@ public class PlainClient extends ClientMechanism implements SaslClient { return Registry.QOP_AUTH; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainRegistry.java b/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainRegistry.java index 0b48c0a..84e1760 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainRegistry.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainRegistry.java @@ -40,28 +40,18 @@ package gnu.javax.crypto.sasl.plain; public interface PlainRegistry { - - // Constants - // ------------------------------------------------------------------------- - /** Name of PLAIN password file property. */ String PASSWORD_FILE = "gnu.crypto.sasl.plain.password.file"; - /** Default fully qualified pathname of the PLAIN password file. */ String DEFAULT_PASSWORD_FILE = "/etc/tpasswd"; - /** Name of the UID field in the plain password file. */ String UID_FIELD = "plain.uid"; - /** Name of the GID field in the plain password file. */ String GID_FIELD = "plain.gid"; - /** Name of the GECOS field in the plain password file. */ String GECOS_FIELD = "plain.gecos"; - /** Name of the DIR field in the plain password file. */ String DIR_FIELD = "plain.dir"; - /** Name of the SHELL field in the plain password file. */ String SHELL_FIELD = "plain.shell"; -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainServer.java b/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainServer.java index 2056884..52deef5 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainServer.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/plain/PlainServer.java @@ -54,30 +54,17 @@ import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; /** - *The PLAIN SASL server-side mechanism.
+ * The PLAIN SASL server-side mechanism. */ -public class PlainServer extends ServerMechanism implements SaslServer +public class PlainServer + extends ServerMechanism + implements SaslServer { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public PlainServer() { super(Registry.SASL_PLAIN_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { } @@ -86,43 +73,27 @@ public class PlainServer extends ServerMechanism implements SaslServer { } - // javax.security.sasl.SaslServer interface implementation ----------------- - public byte[] evaluateResponse(final byte[] response) throws SaslException { if (response == null) - { - return null; - } + return null; try { final String nullStr = new String("\0"); - final StringTokenizer strtok = new StringTokenizer( - new String(response), + final StringTokenizer strtok = new StringTokenizer(new String(response), nullStr, true); - authorizationID = strtok.nextToken(); - if (!authorizationID.equals(nullStr)) - { - strtok.nextToken(); - } + if (! authorizationID.equals(nullStr)) + strtok.nextToken(); else - { - authorizationID = null; - } + authorizationID = null; final String id = strtok.nextToken(); if (id.equals(nullStr)) - { - throw new SaslException("No identity given"); - } + throw new SaslException("No identity given"); if (authorizationID == null) - { - authorizationID = id; - } - if ((!authorizationID.equals(nullStr)) && (!authorizationID.equals(id))) - { - throw new SaslException("Delegation not supported"); - } + authorizationID = id; + if ((! authorizationID.equals(nullStr)) && (! authorizationID.equals(id))) + throw new SaslException("Delegation not supported"); strtok.nextToken(); final byte[] pwd; try @@ -134,9 +105,7 @@ public class PlainServer extends ServerMechanism implements SaslServer throw new SaslException("evaluateResponse()", x); } if (pwd == null) - { - throw new SaslException("No password given"); - } + throw new SaslException("No password given"); final byte[] password; try { @@ -146,10 +115,8 @@ public class PlainServer extends ServerMechanism implements SaslServer { throw new SaslException("evaluateResponse()", x); } - if (!Arrays.equals(pwd, password)) - { - throw new SaslException("Password incorrect"); - } + if (! Arrays.equals(pwd, password)) + throw new SaslException("Password incorrect"); this.complete = true; return null; } @@ -164,33 +131,25 @@ public class PlainServer extends ServerMechanism implements SaslServer return Registry.QOP_AUTH; } - // other methods ----------------------------------------------------------- - private char[] lookupPassword(final String userName) throws SaslException { try { - if (!authenticator.contains(userName)) - { - throw new NoSuchUserException(userName); - } + if (! authenticator.contains(userName)) + throw new NoSuchUserException(userName); final Map userID = new HashMap(); userID.put(Registry.SASL_USERNAME, userName); final Map credentials = authenticator.lookup(userID); final String password = (String) credentials.get(Registry.SASL_PASSWORD); if (password == null) - { - throw new SaslException("lookupPassword()", new InternalError()); - } + throw new SaslException("lookupPassword()", new InternalError()); return password.toCharArray(); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("lookupPassword()", x); } } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/CALG.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/CALG.java index 6215783..3085432 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/CALG.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/CALG.java @@ -58,65 +58,55 @@ import java.util.HashMap; import javax.security.sasl.SaslException; /** - *A Factory class that returns CALG (Confidentiality Algorithm) instances - * that operate as described in the draft-burdis-cat-sasl-srp-08.
- * - *The designated CALG block cipher should be used in OFB (Output Feedback + * A Factory class that returns CALG (Confidentiality Algorithm) instances that + * operate as described in the draft-burdis-cat-sasl-srp-08. + *
+ * The designated CALG block cipher should be used in OFB (Output Feedback * Block) mode in the ISO variant, as described in The Handbook of Applied - * Cryptography, algorithm 7.20.
- * - *Let k
be the block size of the chosen symmetric key block
- * cipher algorithm; e.g. for AES this is 128
bits or 16
- * octets. The OFB mode used shall be of length/size k
.
It is recommended that block ciphers operating in OFB mode be used with an + * Cryptography, algorithm 7.20. + *
+ * Let k
be the block size of the chosen symmetric key block
+ * cipher algorithm; e.g. for AES this is 128
bits or
+ * 16
octets. The OFB mode used shall be of length/size
+ * k
.
+ *
+ * It is recommended that block ciphers operating in OFB mode be used with an
* Initial Vector (the mode's IV). In such a mode of operation - OFB with key
* re-use - the IV need not be secret. For the mechanism in question the IVs
- * shall be a random octet sequence of k
bytes.
k
. When the input
+ * shall be a random octet sequence of k
bytes.
+ *
+ * The input data to the confidentiality protection algorithm shall be a
+ * multiple of the symmetric cipher block size k
. When the input
* length is not a multiple of k
octets, the data shall be padded
- * according to the following scheme:
Assuming the length of the input is l
octets,
+ * according to the following scheme:
+ *
+ * Assuming the length of the input is l
octets,
* (k - (l mod k))
octets, all having the value
* (k - (l mod k))
, shall be appended to the original data. In
* other words, the input is padded at the trailing end with one of the
- * following sequences:
- * - * 01 -- if l mod k = k-1 - * 02 02 -- if l mod k = k-2 - * ... - * ... - * ... - * k k ... k k -- if l mod k = 0 - *- * - *
The padding can be removed unambiguously since all input is padded and no + * + * 01 -- if l mod k = k-1 + * 02 02 -- if l mod k = k-2 + * ... + * ... + * ... + * k k ... k k -- if l mod k = 0 + * + *
+ * The padding can be removed unambiguously since all input is padded and no
* padding sequence is a suffix of another. This padding method is well-defined
* if and only if k < 256
octets, which is the case with
- * symmetric key block ciphers today, and in the forseeable future.
Returns an instance of a SASL-SRP CALG implementation.
- * + * Returns an instance of a SASL-SRP CALG implementation. + * * @param algorithm the name of the symmetric cipher algorithm. * @return an instance of this object. */ @@ -144,118 +131,60 @@ public final class CALG final int blockSize = cipher.defaultBlockSize(); final int keySize = cipher.defaultKeySize(); final Cascade ofbCipher = new Cascade(); - final Object modeNdx = ofbCipher.append(Stage.getInstance( - ModeFactory.getInstance( - Registry.OFB_MODE, - cipher, - blockSize), - Direction.FORWARD)); + IMode ofbMode = ModeFactory.getInstance(Registry.OFB_MODE, + cipher, + blockSize); + Stage modeStage = Stage.getInstance(ofbMode, Direction.FORWARD); + final Object modeNdx = ofbCipher.append(modeStage); final IPad pkcs7 = PadFactory.getInstance(Registry.PKCS7_PAD); - // the passed IV may be longer that what we need. ensure correct length - // byte[] realIV = null; - // if (iv.length == blockSize) { - // realIV = iv; - // } else { - // realIV = new byte[blockSize]; - // if (iv.length > blockSize) { - // System.arraycopy(iv, 0, realIV, 0, blockSize); - // } else { // shouldnt happen - // System.arraycopy(iv, 0, realIV, 0, iv.length); - // } - // } - - // HashMap modeAttributes = new HashMap(); - // modeAttributes.put(IBlockCipher.KEY_MATERIAL, K.clone()); - // modeAttributes.put(IMode.IV, realIV); - final Assembly asm = new Assembly(); asm.addPreTransformer(Transformer.getCascadeTransformer(ofbCipher)); asm.addPreTransformer(Transformer.getPaddingTransformer(pkcs7)); - - // HashMap attributes = new HashMap(); - // attributes.put(Assembly.DIRECTION, dir); - // attributes.put(modeNdx, modeAttributes); - // try { - // asm.init(attributes); - // } catch (TransformerException x) { - // throw new SaslException("getInstance()", x); - // } - return new CALG(blockSize, keySize, modeNdx, asm); } - // Instance methods - // ------------------------------------------------------------------------- - /** - *Initialises a SASL-SRP CALG implementation.
- * + * Initialises a SASL-SRP CALG implementation. + * * @param kdf the key derivation function. * @param iv the initial vector value to use. * @param dir whether this CALG is used for encryption or decryption. */ - // public void init(byte[] K, byte[] iv, Direction dir) throws SaslException { public void init(final KDF kdf, final byte[] iv, final Direction dir) throws SaslException { - // IBlockCipher cipher = CipherFactory.getInstance(algorithm); - // int blockSize = cipher.defaultBlockSize(); - // Cascade ofbCipher = new Cascade(); - // Object modeNdx = ofbCipher.append( - // Stage.getInstace( - // ModeFactory.getInstance(Registry.OFB_MODE, cipher, blockSize), - // Direction.FORWARD)); - // IPad pkcs7 = PadFactory.getInstance(Registry.PKCS7_PAD); - // the passed IV may be longer that what we need. ensure correct length final byte[] realIV; if (iv.length == blockSize) - { - realIV = iv; - } + realIV = iv; else { realIV = new byte[blockSize]; if (iv.length > blockSize) - { - System.arraycopy(iv, 0, realIV, 0, blockSize); - } - else - { // shouldnt happen - System.arraycopy(iv, 0, realIV, 0, iv.length); - } + System.arraycopy(iv, 0, realIV, 0, blockSize); + else // shouldnt happen + System.arraycopy(iv, 0, realIV, 0, iv.length); } - final HashMap modeAttributes = new HashMap(); - // modeAttributes.put(IBlockCipher.KEY_MATERIAL, K.clone()); final byte[] sk = kdf.derive(keySize); modeAttributes.put(IBlockCipher.KEY_MATERIAL, sk); - //System.out.println("**** Initialised CALG with: "+gnu.crypto.util.Util.dumpString(sk)); modeAttributes.put(IMode.IV, realIV); - - // Assembly asm = new Assembly(); - // asm.addPreTransformer(Transformer.getCascadeTransformer(ofbCipher)); - // asm.addPreTransformer(Transformer.getPaddingTransformer(pkcs7)); - final HashMap attributes = new HashMap(); attributes.put(Assembly.DIRECTION, dir); attributes.put(modeNdx, modeAttributes); try { - // asm.init(attributes); assembly.init(attributes); } catch (TransformerException x) { throw new SaslException("getInstance()", x); } - - // return new CALG(asm); } /** - *Encrypts or decrypts, depending on the mode already set, a designated - * array of bytes and returns the result.
- * + * Encrypts or decrypts, depending on the mode already set, a designated array + * of bytes and returns the result. + * * @param data the data to encrypt/decrypt. * @return the decrypted/encrypted result. * @throws ConfidentialityException if an exception occurs duirng the process. @@ -266,9 +195,9 @@ public final class CALG } /** - *Encrypts or decrypts, depending on the mode already set, a designated - * array of bytes and returns the result.
- * + * Encrypts or decrypts, depending on the mode already set, a designated array + * of bytes and returns the result. + * * @param data the data to encrypt/decrypt. * @param offset where to start indata
.
* @param length how many bytes to consider in data
.
@@ -289,4 +218,4 @@ public final class CALG
}
return result;
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/ClientStore.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/ClientStore.java
index ce16f4a..866e610 100644
--- a/libjava/classpath/gnu/javax/crypto/sasl/srp/ClientStore.java
+++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/ClientStore.java
@@ -41,29 +41,19 @@ package gnu.javax.crypto.sasl.srp;
import java.util.HashMap;
/**
- * The client-side implementation of the SRP security context store.
+ * The client-side implementation of the SRP security context store. */ public class ClientStore { - - // Constants and variables - // ------------------------------------------------------------------------- - /** The underlying singleton. */ private static ClientStore singleton = null; - /** The map of uid --> SASL Security Context record. */ private static final HashMap uid2ssc = new HashMap(); - /** The map of sid --> Session timing record. */ private static final HashMap uid2ttl = new HashMap(); - /** A synchronisation lock. */ private static final Object lock = new Object(); - // Constructor(s) - // ------------------------------------------------------------------------- - /** Private constructor to enforce Singleton pattern. */ private ClientStore() { @@ -72,33 +62,25 @@ public class ClientStore // TODO: add a cleaning timer thread } - // Class methods - // ------------------------------------------------------------------------- - /** - *Returns the classloader Singleton.
- * + * Returns the classloader Singleton. + * * @return the classloader Singleton instance. */ static synchronized final ClientStore instance() { if (singleton == null) - { - singleton = new ClientStore(); - } + singleton = new ClientStore(); return singleton; } - // Instance methods - // ------------------------------------------------------------------------- - /** - *Returns a boolean flag indicating if the designated client's session is - * still alive or not.
- * + * Returns a boolean flag indicating if the designated client's session is + * still alive or not. + * * @param uid the identifier of the client whose session to check. * @returntrue
if the designated client's session is still
- * alive. false
otherwise.
+ * alive. false
otherwise.
*/
boolean isAlive(final String uid)
{
@@ -107,11 +89,11 @@ public class ClientStore
{
final Object obj = uid2ssc.get(uid);
result = (obj != null);
- if (result)
- { // is it still alive?
+ if (result) // is it still alive?
+ {
final StoreEntry sto = (StoreEntry) uid2ttl.get(uid);
- if (!sto.isAlive())
- { // invalidate it
+ if (! sto.isAlive()) // invalidate it
+ {
uid2ssc.remove(uid);
uid2ttl.remove(uid);
}
@@ -121,11 +103,11 @@ public class ClientStore
}
/**
- * Records a mapping between a client's unique identifier and its security - * context.
- * - * @param uid the unique identifier of the SRP client for which the session - * is to be cached. + * Records a mapping between a client's unique identifier and its security + * context. + * + * @param uid the unique identifier of the SRP client for which the session is + * to be cached. * @param ttl the session's Time-To-Live indicator (in seconds). * @param ctx the client's security context. */ @@ -139,9 +121,9 @@ public class ClientStore } /** - *Removes the mapping between the designated SRP client unique identifier - * and the its session security context (and other timing information).
- * + * Removes the mapping between the designated SRP client unique identifier and + * the its session security context (and other timing information). + * * @param uid the identifier of the client whose session is to invalidate. */ void invalidateSession(final String uid) @@ -154,9 +136,9 @@ public class ClientStore } /** - *Returns an SRP client's security context record mapped by that client's - * unique identifier.
- * + * Returns an SRP client's security context record mapped by that client's + * unique identifier. + * * @param uid the identifier of the client whose session is to restore. * @return the SRP client's security context. */ @@ -170,4 +152,4 @@ public class ClientStore } return result; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/IALG.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/IALG.java index 51492f9..85c9370 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/IALG.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/IALG.java @@ -48,20 +48,14 @@ import java.util.HashMap; import javax.security.sasl.SaslException; /** - *A Factory class that returns IALG (Integrity Algorithm) instances that - * operate as described in the draft-burdis-cat-sasl-srp-04 and later.
+ * A Factory class that returns IALG (Integrity Algorithm) instances that + * operate as described in the draft-burdis-cat-sasl-srp-04 and later. */ -public final class IALG implements Cloneable +public final class IALG + implements Cloneable { - - // Constants and variables - // -------------------------------------------------------------------------- - private IMac hmac; - // Constructor(s) - // -------------------------------------------------------------------------- - /** Private constructor to enforce instantiation through Factory method. */ private IALG(final IMac hmac) { @@ -70,12 +64,9 @@ public final class IALG implements Cloneable this.hmac = hmac; } - // Class methods - // ------------------------------------------------------------------------- - /** - *Returns an instance of a SASL-SRP IALG implementation.
- * + * Returns an instance of a SASL-SRP IALG implementation. + * * @param algorithm the name of the HMAC algorithm. * @return an instance of this object. */ @@ -85,44 +76,24 @@ public final class IALG implements Cloneable final IMac hmac; hmac = MacFactory.getInstance(algorithm); if (hmac == null) - { - throw new SaslException("getInstance()", - new NoSuchAlgorithmException(algorithm)); - } - // try { - // byte[] sk = (byte[]) K.clone(); - // HashMap map = new HashMap(); - // map.put(IMac.MAC_KEY_MATERIAL, sk); - // hmac.init(map); - // } catch (InvalidKeyException x) { - // throw new SaslException("getInstance()", x); - // } + throw new SaslException("getInstance()", + new NoSuchAlgorithmException(algorithm)); return new IALG(hmac); } - // Instance methods - // ------------------------------------------------------------------------- - - // Cloneable interface implementation -------------------------------------- - public Object clone() throws CloneNotSupportedException { return new IALG((IMac) hmac.clone()); } - // other methdds ----------------------------------------------------------- - - // public void init(final byte[] K) throws SaslException { public void init(final KDF kdf) throws SaslException { try { - // final byte[] sk = (byte[]) K.clone(); final byte[] sk = kdf.derive(hmac.macSize()); final HashMap map = new HashMap(); map.put(IMac.MAC_KEY_MATERIAL, sk); hmac.init(map); - //System.out.println("**** Initialised IALG with: "+gnu.crypto.util.Util.dumpString(sk)); } catch (InvalidKeyException x) { @@ -146,8 +117,8 @@ public final class IALG implements Cloneable } /** - *Returns the length (in bytes) of this SASL SRP Integrity Algorithm.
- * + * Returns the length (in bytes) of this SASL SRP Integrity Algorithm. + * * @return the length, in bytes, of this integrity protection algorithm. */ public int length() diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/KDF.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/KDF.java index 0d5eeac..aa3edac 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/KDF.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/KDF.java @@ -47,67 +47,46 @@ import gnu.javax.crypto.prng.UMacGenerator; import java.util.HashMap; /** - *The SASL-SRP KDF implementation, which is also used, depending on how it - * was instantiated, as a secure Pseudo Random Number Generator.
+ * The SASL-SRP KDF implementation, which is also used, depending on how it was + * instantiated, as a secure Pseudo Random Number Generator. */ public class KDF { - - // Constants and variables - // ------------------------------------------------------------------------- - - private static final int AES_BLOCK_SIZE = 16; // default block size for the AES - + private static final int AES_BLOCK_SIZE = 16; // default block size for AES private static final int AES_KEY_SIZE = 16; // default key size for the AES - private static final byte[] buffer = new byte[1]; - /** Our default source of randomness. */ private static final PRNG prng = PRNG.getInstance(); - - /** The shared secret K to use. */ - // private byte[] keyMaterial; /** The underlying UMAC Generator instance. */ private UMacGenerator umac = null; - // Constructor(s) - // ------------------------------------------------------------------------- - /** - *Constructs an instance of the KDF
initialised with the
- * designated shared secret bytes.
KDF
initialised with the
+ * designated shared secret bytes.
+ *
* @param keyMaterial the SASL SRP shared secret (K) bytes.
*/
private KDF(final byte[] keyMaterial, final int ndx)
{
super();
- // if (ndx != 0) {
- // this.keyMaterial = (byte[]) keyMaterial.clone();
- // }
final HashMap map = new HashMap();
map.put(UMacGenerator.CIPHER, Registry.AES_CIPHER);
- map.put(UMacGenerator.INDEX, new Integer(ndx));
- map.put(IBlockCipher.CIPHER_BLOCK_SIZE, new Integer(AES_BLOCK_SIZE));
+ map.put(UMacGenerator.INDEX, Integer.valueOf(ndx));
+ map.put(IBlockCipher.CIPHER_BLOCK_SIZE, Integer.valueOf(AES_BLOCK_SIZE));
final byte[] key = new byte[AES_KEY_SIZE];
System.arraycopy(keyMaterial, 0, key, 0, AES_KEY_SIZE);
map.put(IBlockCipher.KEY_MATERIAL, key);
-
umac = new UMacGenerator();
umac.init(map);
- //System.out.println("**** Initialised KDF with: "+gnu.crypto.util.Util.dumpString(key));
}
- // Class methods
- // -------------------------------------------------------------------------
-
/**
- * A Factory mehod that returns an instance of a KDF
based on
- * supplied seed data.
KDF
based on
+ * supplied seed data.
+ *
* @param K the SASL SRP shared secret for a KDF
to be used for
- * CALG and IALG setup. null
otherwise.
+ * CALG and IALG setup. null
otherwise.
* @return an instance of a KDF
.
*/
static final KDF getInstance(final byte[] K)
@@ -134,36 +113,28 @@ public class KDF
return (buffer[0] & 0xFF);
}
- // Instance methods
- // -------------------------------------------------------------------------
-
/**
- * Returns a designated number of bytes suitable for use in the SASL SRP - * mechanism.
- * + * Returns a designated number of bytes suitable for use in the SASL SRP + * mechanism. + * * @param length the number of bytes needed. * @return a byte array containing the generated/selected bytes. */ public synchronized byte[] derive(final int length) { final byte[] result = new byte[length]; - // if (keyMaterial == null || length > keyMaterial.length) { try { umac.nextBytes(result, 0, length); } - catch (IllegalStateException x) - { // should not happen + catch (IllegalStateException x) // should not happen + { x.printStackTrace(System.err); } - catch (LimitReachedException x) - { // idem + catch (LimitReachedException x) // idem + { x.printStackTrace(System.err); } - // } else { - // System.arraycopy(keyMaterial, 0, result, 0, length); - // } - return result; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/PasswordFile.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/PasswordFile.java index 1628a41..36888df 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/PasswordFile.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/PasswordFile.java @@ -39,7 +39,6 @@ exception statement from your version. */ package gnu.javax.crypto.sasl.srp; import gnu.java.security.Registry; -import gnu.java.security.hash.IMessageDigest; import gnu.java.security.util.Util; import gnu.javax.crypto.key.srp6.SRPAlgorithm; import gnu.javax.crypto.sasl.NoSuchUserException; @@ -50,9 +49,9 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.IOException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.math.BigInteger; @@ -62,70 +61,58 @@ import java.util.NoSuchElementException; import java.util.StringTokenizer; /** - *The implementation of SRP password files.
- * - *For SRP, there are three (3) files: + * The implementation of SRP password files. + *
+ * For SRP, there are three (3) files: *
This implementation assumes the following message digest algorithm codes: + *
+ * This implementation assumes the following message digest algorithm codes: *
IMPORTANT: This method computes the verifiers as described in - * RFC-2945, which differs from the description given on the web page for - * SRP-6.
- * - *Reference:
+ *+ * IMPORTANT: This method computes the verifiers as described in + * RFC-2945, which differs from the description given on the web page for SRP-6. + *
+ * Reference: *
Returns a string representing the decimal value of an integer - * identifying the message digest algorithm to use for the SRP computations. - *
- * + * Returns a string representing the decimal value of an integer identifying + * the message digest algorithm to use for the SRP computations. + * * @param mdName the canonical name of a message digest algorithm. * @return a string representing the decimal value of an ID for that - * algorithm. + * algorithm. */ private static final String nameToID(final String mdName) { if (Registry.SHA_HASH.equalsIgnoreCase(mdName) || Registry.SHA1_HASH.equalsIgnoreCase(mdName) || Registry.SHA160_HASH.equalsIgnoreCase(mdName)) - { - return "0"; - } + return "0"; else if (Registry.MD5_HASH.equalsIgnoreCase(mdName)) - { - return "1"; - } + return "1"; else if (Registry.RIPEMD128_HASH.equalsIgnoreCase(mdName)) - { - return "2"; - } + return "2"; else if (Registry.RIPEMD160_HASH.equalsIgnoreCase(mdName)) - { - return "3"; - } + return "3"; else if (Registry.SHA256_HASH.equalsIgnoreCase(mdName)) - { - return "4"; - } + return "4"; else if (Registry.SHA384_HASH.equalsIgnoreCase(mdName)) - { - return "5"; - } + return "5"; else if (Registry.SHA512_HASH.equalsIgnoreCase(mdName)) - { - return "6"; - } + return "6"; return "0"; } - // SRP password configuration file methods --------------------------------- - /** - *Checks if the current configuration file contains the <N, g> pair
- * for the designated index
.
index
.
+ *
* @param index a string representing 1-digit identification of an <N, g>
- * pair used.
- * @return true
if the designated index
is that of
- * a known <N, g> pair, and false
otherwise.
+ * pair used.
+ * @return true
if the designated index
is that
+ * of a known <N, g> pair, and false
otherwise.
* @throws IOException if an exception occurs during the process.
* @see SRPRegistry#N_2048_BITS
* @see SRPRegistry#N_1536_BITS
@@ -280,16 +239,16 @@ public class PasswordFile
}
/**
- * Returns a pair of strings representing the pair of N
and
- * g
MPIs for the designated index
.
N
and
+ * g
MPIs for the designated index
.
+ *
* @param index a string representing 1-digit identification of an <N, g>
- * pair to look up.
+ * pair to look up.
* @return a pair of strings, arranged in an array, where the first (at index
- * position #0) is the repesentation of the MPI N
, and the
- * second (at index position #1) is the representation of the MPI
- * g
. If the index
refers to an unknown pair, then
- * an empty string array is returned.
+ * position #0) is the repesentation of the MPI N
, and
+ * the second (at index position #1) is the representation of the MPI
+ * g
. If the index
refers to an unknown
+ * pair, then an empty string array is returned.
* @throws IOException if an exception occurs during the process.
*/
public synchronized String[] lookupConfig(final String index)
@@ -298,14 +257,10 @@ public class PasswordFile
checkCurrent();
String[] result = null;
if (configurations.containsKey(index))
- {
- result = (String[]) configurations.get(index);
- }
+ result = (String[]) configurations.get(index);
return result;
}
- // SRP base and extended password configuration files methods --------------
-
public synchronized boolean contains(final String user) throws IOException
{
checkCurrent();
@@ -318,9 +273,7 @@ public class PasswordFile
{
checkCurrent();
if (entries.containsKey(user))
- {
- throw new UserAlreadyExistsException(user);
- }
+ throw new UserAlreadyExistsException(user);
final HashMap fields = new HashMap(4);
fields.put(USER_FIELD, user); // 0
fields.put(VERIFIERS_FIELD, newVerifiers(user, salt, passwd, index)); // 1
@@ -334,10 +287,8 @@ public class PasswordFile
throws IOException
{
checkCurrent();
- if (!entries.containsKey(user))
- {
- throw new NoSuchUserException(user);
- }
+ if (! entries.containsKey(user))
+ throw new NoSuchUserException(user);
final HashMap fields = (HashMap) entries.get(user);
final byte[] salt;
try
@@ -369,27 +320,23 @@ public class PasswordFile
finally
{
if (pw1 != null)
- {
- try
- {
- pw1.flush();
- }
- finally
- {
- pw1.close();
- }
- }
+ try
+ {
+ pw1.flush();
+ }
+ finally
+ {
+ pw1.close();
+ }
if (pw2 != null)
- {
- try
- {
- pw2.flush();
- }
- finally
- {
- pw2.close();
- }
- }
+ try
+ {
+ pw2.flush();
+ }
+ finally
+ {
+ pw2.close();
+ }
try
{
f1.close();
@@ -410,24 +357,22 @@ public class PasswordFile
}
/**
- * Returns the triplet: verifier, salt and configuration file index, of a + * Returns the triplet: verifier, salt and configuration file index, of a * designated user, and a designated message digest algorithm name, as an - * array of strings.
- * + * array of strings. + * * @param user the username. * @param mdName the canonical name of the SRP's message digest algorithm. * @return a string array containing, in this order, the BASE-64 encodings of - * the verifier, the salt and the index in the password configuration file of - * the MPIs N and g of the designated user. + * the verifier, the salt and the index in the password configuration + * file of the MPIs N and g of the designated user. */ public synchronized String[] lookup(final String user, final String mdName) throws IOException { checkCurrent(); - if (!entries.containsKey(user)) - { - throw new NoSuchUserException(user); - } + if (! entries.containsKey(user)) + throw new NoSuchUserException(user); final HashMap fields = (HashMap) entries.get(user); final HashMap verifiers = (HashMap) fields.get(VERIFIERS_FIELD); final String salt = (String) fields.get(SALT_FIELD); @@ -436,8 +381,6 @@ public class PasswordFile return new String[] { verifier, salt, index }; } - // Other instance methods -------------------------------------------------- - private synchronized void readOrCreateConf() throws IOException { configurations.clear(); @@ -469,13 +412,9 @@ public class PasswordFile finally { if (pw0 != null) - { - pw0.close(); - } + pw0.close(); else if (f0 != null) - { - f0.close(); - } + f0.close(); } } } @@ -511,26 +450,27 @@ public class PasswordFile { ndx = (String) it.next(); mpi = (String[]) configurations.get(ndx); - sb = new StringBuffer(ndx).append(":").append(mpi[0]).append(":").append( - mpi[1]); + sb = new StringBuffer(ndx) + .append(":").append(mpi[0]) + .append(":").append(mpi[1]); pw.println(sb.toString()); } } /** - *Compute the new verifiers for the designated username and password.
- * - *IMPORTANT: This method computes the verifiers as described in + * Compute the new verifiers for the designated username and password. + *
+ * IMPORTANT: This method computes the verifiers as described in * RFC-2945, which differs from the description given on the web page for - * SRP-6.
- * + * SRP-6. + * * @param user the user's name. * @param s the user's salt. * @param password the user's password * @param index the index of the <N, g> pair to use for this user. * @return a {@link java.util.Map} of user verifiers. * @throws UnsupportedEncodingException if the US-ASCII decoder is not - * available on this platform. + * available on this platform. */ private HashMap newVerifiers(final String user, final byte[] s, final String password, final String index) @@ -540,7 +480,6 @@ public class PasswordFile final String[] mpi = (String[]) configurations.get(index); final BigInteger N = new BigInteger(1, Util.fromBase64(mpi[0])); final BigInteger g = new BigInteger(1, Util.fromBase64(mpi[1])); - final HashMap result = new HashMap(srps.size()); BigInteger x, v; SRP srp; @@ -551,7 +490,6 @@ public class PasswordFile x = new BigInteger(1, srp.computeX(s, user, password)); v = g.modPow(x, N); final String verifier = Util.toBase64(v.toByteArray()); - result.put(digestID, verifier); } return result; @@ -560,7 +498,6 @@ public class PasswordFile private synchronized void update() throws IOException { entries.clear(); - FileInputStream fis; passwdFile = new File(pwName); lastmodPasswdFile = passwdFile.lastModified(); @@ -588,9 +525,7 @@ public class PasswordFile { if (passwdFile.lastModified() > lastmodPasswdFile || passwd2File.lastModified() > lastmodPasswd2File) - { - update(); - } + update(); } private void readPasswd(final InputStream in) throws IOException @@ -612,16 +547,13 @@ public class PasswordFile { throw new IOException("SRP base password file corrupt"); } - final HashMap verifiers = new HashMap(6); verifiers.put("0", verifier); - final HashMap fields = new HashMap(4); fields.put(USER_FIELD, user); fields.put(VERIFIERS_FIELD, verifiers); fields.put(SALT_FIELD, salt); fields.put(CONFIG_FIELD, index); - entries.put(user, fields); } } @@ -645,7 +577,6 @@ public class PasswordFile { throw new IOException("SRP extended password file corrupt"); } - fields = (HashMap) entries.get(user); if (fields != null) { @@ -667,33 +598,28 @@ public class PasswordFile { user = (String) i.next(); fields = (HashMap) entries.get(user); - if (!user.equals(fields.get(USER_FIELD))) - { - throw new IOException("Inconsistent SRP password data"); - } + if (! user.equals(fields.get(USER_FIELD))) + throw new IOException("Inconsistent SRP password data"); verifiers = (HashMap) fields.get(VERIFIERS_FIELD); - sb1 = new StringBuffer().append(user).append(":").append( - (String) verifiers.get("0")).append( - ":").append( - (String) fields.get(SALT_FIELD)).append( - ":").append( - (String) fields.get(CONFIG_FIELD)); + sb1 = new StringBuffer(user) + .append(":").append((String) verifiers.get("0")) + .append(":").append((String) fields.get(SALT_FIELD)) + .append(":").append((String) fields.get(CONFIG_FIELD)); pw1.println(sb1.toString()); // write extended information j = verifiers.keySet().iterator(); while (j.hasNext()) { digestID = (String) j.next(); - if (!"0".equals(digestID)) + if (! "0".equals(digestID)) { // #0 is the default digest, already present in tpasswd! - sb2 = new StringBuffer().append(digestID).append(":").append( - user).append( - ":").append( - (String) verifiers.get(digestID)); + sb2 = new StringBuffer(digestID) + .append(":").append(user) + .append(":").append((String) verifiers.get(digestID)); pw2.println(sb2.toString()); } } } } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRP.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRP.java index d3eb596..437e42a 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRP.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRP.java @@ -47,27 +47,18 @@ import java.math.BigInteger; import java.util.HashMap; /** - *A Factory class that returns SRP Singletons that know all SRP-related + * A Factory class that returns SRP Singletons that know all SRP-related * mathematical computations and protocol-related operations for both the - * client- and server-sides.
+ * client- and server-sides. */ public final class SRP { - - // Constants and variables - // -------------------------------------------------------------------------- - /** The map of already instantiated SRP algorithm instances. */ private static final HashMap algorithms = new HashMap(); - private static final byte COLON = (byte) 0x3A; - /** The underlying message digest algorithm used for all SRP calculations. */ private IMessageDigest mda; - // Constructor(s) - // -------------------------------------------------------------------------- - /** Trivial private constructor to enforce Singleton pattern. */ private SRP(final IMessageDigest mda) { @@ -76,25 +67,18 @@ public final class SRP this.mda = mda; } - // Class methods - // ------------------------------------------------------------------------- - /** - *Returns an instance of this object that uses the designated message - * digest algorithm as its digest function.
- * + * Returns an instance of this object that uses the designated message digest + * algorithm as its digest function. + * * @return an instance of this object for the designated digest name. */ public static synchronized SRP instance(String mdName) { if (mdName != null) - { - mdName = mdName.trim().toLowerCase(); - } + mdName = mdName.trim().toLowerCase(); if (mdName == null || mdName.equals("")) - { - mdName = SRPRegistry.SRP_DEFAULT_DIGEST_NAME; - } + mdName = SRPRegistry.SRP_DEFAULT_DIGEST_NAME; SRP result = (SRP) algorithms.get(mdName); if (result == null) { @@ -110,31 +94,24 @@ public final class SRP { final byte[] result = new byte[length]; for (int i = 0; i < length; ++i) - { - result[i] = (byte) (b1[i] ^ b2[i]); - } + result[i] = (byte)(b1[i] ^ b2[i]); return result; } - // Instance methods - // ------------------------------------------------------------------------- - /** @return the message digest algorithm name used by this instance. */ public String getAlgorithm() { return mda.name(); } - // Message Digest algorithm related methods -------------------------------- - /** - *Returns a new instance of the SRP message digest algorithm --which is + * Returns a new instance of the SRP message digest algorithm --which is * SHA-160 by default, but could be anything else provided the proper - * conditions as specified in the SRP specifications.
- * + * conditions as specified in the SRP specifications. + * * @return a new instance of the underlying SRP message digest algorithm. * @throws RuntimeException if the implementation of the message digest - * algorithm does not support cloning. + * algorithm does not support cloning. */ public IMessageDigest newDigest() { @@ -142,12 +119,12 @@ public final class SRP } /** - *Convenience method to return the result of digesting the designated - * input with a new instance of the SRP message digest algorithm.
- * + * Convenience method to return the result of digesting the designated input + * with a new instance of the SRP message digest algorithm. + * * @param src some bytes to digest. - * @return the bytes constituting the result of digesting the designated - * input with a new instance of the SRP message digest algorithm. + * @return the bytes constituting the result of digesting the designated input + * with a new instance of the SRP message digest algorithm. */ public byte[] digest(final byte[] src) { @@ -157,13 +134,13 @@ public final class SRP } /** - *Convenience method to return the result of digesting the designated - * input with a new instance of the SRP message digest algorithm.
- * + * Convenience method to return the result of digesting the designated input + * with a new instance of the SRP message digest algorithm. + * * @param src a String whose bytes (using US-ASCII encoding) are to be - * digested. - * @return the bytes constituting the result of digesting the designated - * input with a new instance of the SRP message digest algorithm. + * digested. + * @return the bytes constituting the result of digesting the designated input + * with a new instance of the SRP message digest algorithm. * @throws UnsupportedEncodingException if US-ASCII charset is not found. */ public byte[] digest(final String src) throws UnsupportedEncodingException @@ -171,17 +148,15 @@ public final class SRP return digest(src.getBytes("US-ASCII")); } - // Other methods ----------------------------------------------------------- - /** - *Convenience method to XOR N bytes from two arrays; N being the output - * size of the SRP message digest algorithm.
- * + * Convenience method to XOR N bytes from two arrays; N being the output size + * of the SRP message digest algorithm. + * * @param a the first byte array. * @param b the second one. * @return N bytes which are the result of the XOR operations on the first N - * bytes from the designated arrays. N is the size of the SRP message digest - * algorithm; eg. 20 for SHA-160. + * bytes from the designated arrays. N is the size of the SRP message + * digest algorithm; eg. 20 for SHA-160. */ public byte[] xor(final byte[] a, final byte[] b) { @@ -212,7 +187,6 @@ public final class SRP hash.update(b, 0, b.length); hash.update(cn, 0, cn.length); hash.update(cCB, 0, cCB.length); - return hash.digest(); } @@ -235,14 +209,13 @@ public final class SRP b = digest(o); hash.update(b, 0, b.length); hash.update(sid, 0, sid.length); - hash.update((byte) (ttl >>> 24)); - hash.update((byte) (ttl >>> 16)); - hash.update((byte) (ttl >>> 8)); + hash.update((byte)(ttl >>> 24)); + hash.update((byte)(ttl >>> 16)); + hash.update((byte)(ttl >>> 8)); hash.update((byte) ttl); hash.update(cIV, 0, cIV.length); hash.update(sIV, 0, sIV.length); hash.update(sCB, 0, sCB.length); - return hash.digest(); } @@ -252,7 +225,6 @@ public final class SRP hash.update(K, 0, K.length); hash.update(cn, 0, cn.length); hash.update(sn, 0, sn.length); - return hash.digest(); } @@ -276,10 +248,8 @@ public final class SRP hash.update(COLON); hash.update(p, 0, p.length); final byte[] up = hash.digest(); - hash.update(s, 0, s.length); hash.update(up, 0, up.length); - return hash.digest(); } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java index 9ea21ef..3a43a94 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java @@ -50,37 +50,21 @@ import java.util.Map; import javax.security.sasl.AuthenticationException; /** - *The SRP mechanism authentication information provider implementation.
+ * The SRP mechanism authentication information provider implementation. */ -public class SRPAuthInfoProvider implements IAuthInfoProvider +public class SRPAuthInfoProvider + implements IAuthInfoProvider { - - // Constants and variables - // ------------------------------------------------------------------------- - private PasswordFile passwordFile = null; - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-args constrcutor - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // IAuthInfoProvider interface implementation ------------------------------ - public void activate(Map context) throws AuthenticationException { try { if (context == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else { passwordFile = (PasswordFile) context.get(SRPRegistry.PASSWORD_DB); @@ -88,13 +72,9 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider { String pfn = (String) context.get(SRPRegistry.PASSWORD_FILE); if (pfn == null) - { - passwordFile = new PasswordFile(); - } + passwordFile = new PasswordFile(); else - { - passwordFile = new PasswordFile(pfn); - } + passwordFile = new PasswordFile(pfn); } } } @@ -112,10 +92,8 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider public boolean contains(String userName) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("contains()", - new IllegalStateException()); - } + throw new AuthenticationException("contains()", + new IllegalStateException()); boolean result = false; try { @@ -131,20 +109,14 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider public Map lookup(Map userID) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("lookup()", - new IllegalStateException()); - } + throw new AuthenticationException("lookup()", new IllegalStateException()); Map result = new HashMap(); try { String userName = (String) userID.get(Registry.SASL_USERNAME); if (userName == null) - { - throw new NoSuchUserException(""); - } + throw new NoSuchUserException(""); String mdName = (String) userID.get(SRPRegistry.MD_NAME_FIELD); - String[] data = passwordFile.lookup(userName, mdName); result.put(SRPRegistry.USER_VERIFIER_FIELD, data[0]); result.put(SRPRegistry.SALT_FIELD, data[1]); @@ -153,9 +125,7 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("lookup()", x); } return result; @@ -165,7 +135,6 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider { if (passwordFile == null) throw new AuthenticationException("update()", new IllegalStateException()); - try { String userName = (String) userCredentials.get(Registry.SASL_USERNAME); @@ -173,20 +142,14 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider String salt = (String) userCredentials.get(SRPRegistry.SALT_FIELD); String config = (String) userCredentials.get(SRPRegistry.CONFIG_NDX_FIELD); if (salt == null || config == null) - { - passwordFile.changePasswd(userName, password); - } + passwordFile.changePasswd(userName, password); else - { - passwordFile.add(userName, password, Util.fromBase64(salt), config); - } + passwordFile.add(userName, password, Util.fromBase64(salt), config); } catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("update()", x); } } @@ -194,10 +157,8 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider public Map getConfiguration(String mode) throws AuthenticationException { if (passwordFile == null) - { - throw new AuthenticationException("getConfiguration()", - new IllegalStateException()); - } + throw new AuthenticationException("getConfiguration()", + new IllegalStateException()); Map result = new HashMap(); try { @@ -208,11 +169,9 @@ public class SRPAuthInfoProvider implements IAuthInfoProvider catch (Exception x) { if (x instanceof AuthenticationException) - { - throw (AuthenticationException) x; - } + throw (AuthenticationException) x; throw new AuthenticationException("getConfiguration()", x); } return result; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPClient.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPClient.java index 1a1664f..f4ef4cc 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPClient.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPClient.java @@ -38,151 +38,91 @@ exception statement from your version. */ package gnu.javax.crypto.sasl.srp; +import gnu.java.security.Configuration; import gnu.java.security.Registry; import gnu.java.security.hash.MD5; import gnu.java.security.util.PRNG; import gnu.java.security.util.Util; - +import gnu.javax.crypto.assembly.Direction; +import gnu.javax.crypto.cipher.CipherFactory; +import gnu.javax.crypto.cipher.IBlockCipher; import gnu.javax.crypto.key.IKeyAgreementParty; import gnu.javax.crypto.key.IncomingMessage; -import gnu.javax.crypto.key.KeyAgreementFactory; import gnu.javax.crypto.key.KeyAgreementException; +import gnu.javax.crypto.key.KeyAgreementFactory; import gnu.javax.crypto.key.OutgoingMessage; import gnu.javax.crypto.key.srp6.SRP6KeyAgreement; -import gnu.javax.crypto.assembly.Direction; -import gnu.javax.crypto.cipher.CipherFactory; -import gnu.javax.crypto.cipher.IBlockCipher; import gnu.javax.crypto.sasl.ClientMechanism; import gnu.javax.crypto.sasl.IllegalMechanismStateException; import gnu.javax.crypto.sasl.InputBuffer; import gnu.javax.crypto.sasl.IntegrityException; import gnu.javax.crypto.sasl.OutputBuffer; - import gnu.javax.security.auth.Password; -import java.io.IOException; -import java.io.PrintWriter; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; +import java.util.logging.Logger; +import javax.security.auth.DestroyFailedException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.NameCallback; import javax.security.auth.callback.PasswordCallback; import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.DestroyFailedException; import javax.security.sasl.AuthenticationException; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; /** - *The SASL-SRP client-side mechanism.
+ * The SASL-SRP client-side mechanism. */ -public class SRPClient extends ClientMechanism implements SaslClient +public class SRPClient + extends ClientMechanism + implements SaslClient { - - // Debugging methods and variables - // ------------------------------------------------------------------------- - - private static final String NAME = "SRPClient"; - - // private static final String ERROR = "ERROR"; - // private static final String WARN = " WARN"; - private static final String INFO = " INFO"; - - private static final String TRACE = "DEBUG"; - - private static final boolean DEBUG = true; - - private static final int debuglevel = 3; - - private static final PrintWriter err = new PrintWriter(System.out, true); - - private static void debug(final String level, final Object obj) - { - err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj)); - } - - // Constants and variables - // ------------------------------------------------------------------------- - - // private static final HashMap uid2ctx = new HashMap(); - + private static final Logger log = Logger.getLogger(SRPClient.class.getName()); private String uid; // the unique key for this type of client - private String U; // the authentication identity - BigInteger N, g, A, B; - private Password password; // the authentication credentials - private byte[] s; // the user's salt - private byte[] cIV, sIV; // client+server IVs, when confidentiality is on - private byte[] M1, M2; // client+server evidences - private byte[] cn, sn; // client's and server's nonce - private SRP srp; // SRP algorithm instance used by this client - private byte[] sid; // session ID when re-used - private int ttl; // session time-to-live in seconds - private byte[] sCB; // the peer's channel binding data - private String L; // available options - private String o; - private String chosenIntegrityAlgorithm; - private String chosenConfidentialityAlgorithm; - private int rawSendSize = Registry.SASL_BUFFER_MAX_LIMIT; - private byte[] K; // shared session key - private boolean replayDetection = true; // whether Replay Detection is on - private int inCounter = 0; // messages sequence numbers - private int outCounter = 0; - private IALG inMac, outMac; // if !null, use for integrity - private CALG inCipher, outCipher; // if !null, use for confidentiality - - private IKeyAgreementParty clientHandler = KeyAgreementFactory.getPartyAInstance(Registry.SRP_SASL_KA); - + private IKeyAgreementParty clientHandler = + KeyAgreementFactory.getPartyAInstance(Registry.SRP_SASL_KA); /** Our default source of randomness. */ private PRNG prng = null; - // Constructor(s) - // ------------------------------------------------------------------------- - public SRPClient() { super(Registry.SASL_SRP_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { - // we shall keep track of the sid (and the security context of this - // SRP client) based on the initialisation parameters of an SRP session. + // we shall keep track of the sid (and the security context of this SRP + // client) based on the initialisation parameters of an SRP session. // we shall compute a unique key for those parameters and key the sid // (and the security context) accordingly. // 1. compute the mapping key. use MD5 (the fastest) for this purpose @@ -195,9 +135,8 @@ public class SRPClient extends ClientMechanism implements SaslClient b = protocol.getBytes(); md.update(b, 0, b.length); if (channelBinding.length > 0) - { - md.update(channelBinding, 0, channelBinding.length); - } + md.update(channelBinding, 0, channelBinding.length); + uid = Util.toBase64(md.digest()); if (ClientStore.instance().isAlive(uid)) { @@ -246,15 +185,12 @@ public class SRPClient extends ClientMechanism implements SaslClient sIV = null; inMac = outMac = null; inCipher = outCipher = null; - sid = null; ttl = 0; cn = null; sn = null; } - // javax.security.sasl.SaslClient interface implementation ----------------- - public boolean hasInitialResponse() { return true; @@ -282,7 +218,7 @@ public class SRPClient extends ClientMechanism implements SaslClient } return result; case 2: // should only occur if session re-use was rejected - if (!complete) + if (! complete) { state++; return receiveEvidence(challenge); @@ -296,211 +232,139 @@ public class SRPClient extends ClientMechanism implements SaslClient protected byte[] engineUnwrap(final byte[] incoming, final int offset, final int len) throws SaslException { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> engineUnwrap()"); - + if (Configuration.DEBUG) + log.entering(this.getClass().getName(), "engineUnwrap"); if (inMac == null && inCipher == null) - { - throw new IllegalStateException("connection is not protected"); - } - + throw new IllegalStateException("connection is not protected"); // at this point one, or both, of confidentiality and integrity protection // services are active. - final byte[] result; try { - // final InputBuffer frameIn = InputBuffer.getInstance(incoming, offset, len); - // result = frameIn.getEOS(); if (inMac != null) { // integrity bytes are at the end of the stream final int macBytesCount = inMac.length(); final int payloadLength = len - macBytesCount; - // final byte[] received_mac = frameIn.getOS(); final byte[] received_mac = new byte[macBytesCount]; System.arraycopy(incoming, offset + payloadLength, received_mac, 0, macBytesCount); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got C (received MAC): " - + Util.dumpString(received_mac)); - // inMac.update(result); + if (Configuration.DEBUG) + log.fine("Got C (received MAC): " + Util.dumpString(received_mac)); inMac.update(incoming, offset, payloadLength); if (replayDetection) { inCounter++; - if (DEBUG && debuglevel > 6) - debug(TRACE, "inCounter=" + String.valueOf(inCounter)); - inMac.update(new byte[] { (byte) (inCounter >>> 24), - (byte) (inCounter >>> 16), - (byte) (inCounter >>> 8), - (byte) inCounter }); + if (Configuration.DEBUG) + log.fine("inCounter=" + inCounter); + inMac.update(new byte[] { + (byte)(inCounter >>> 24), + (byte)(inCounter >>> 16), + (byte)(inCounter >>> 8), + (byte) inCounter }); } - final byte[] computed_mac = inMac.doFinal(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Computed MAC: " + Util.dumpString(computed_mac)); - if (!Arrays.equals(received_mac, computed_mac)) - { - throw new IntegrityException("engineUnwrap()"); - } - + if (Configuration.DEBUG) + log.fine("Computed MAC: " + Util.dumpString(computed_mac)); + if (! Arrays.equals(received_mac, computed_mac)) + throw new IntegrityException("engineUnwrap()"); // deal with the payload, which can be either plain or encrypted if (inCipher != null) - { - result = inCipher.doFinal(incoming, offset, payloadLength); - } + result = inCipher.doFinal(incoming, offset, payloadLength); else { result = new byte[len - macBytesCount]; System.arraycopy(incoming, offset, result, 0, result.length); } } - else - { // no integrity protection; just confidentiality - // if (inCipher != null) { - result = inCipher.doFinal(incoming, offset, len); - // } else { - // result = new byte[len]; - // System.arraycopy(incoming, offset, result, 0, len); - // } - } - // if (inCipher != null) { - // result = inCipher.doFinal(result); - // } + else // no integrity protection; just confidentiality + result = inCipher.doFinal(incoming, offset, len); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("engineUnwrap()", x); } - - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== engineUnwrap()"); + if (Configuration.DEBUG) + log.exiting(this.getClass().getName(), "engineUnwrap"); return result; } protected byte[] engineWrap(final byte[] outgoing, final int offset, final int len) throws SaslException { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> engineWrap()"); - + if (Configuration.DEBUG) + log.entering(this.getClass().getName(), "engineWrap"); if (outMac == null && outCipher == null) - { - throw new IllegalStateException("connection is not protected"); - } - + throw new IllegalStateException("connection is not protected"); // at this point one, or both, of confidentiality and integrity protection // services are active. - - // byte[] data = new byte[len]; - // System.arraycopy(outgoing, offset, data, 0, len); byte[] result; try { - // OutputBuffer frameOut = new OutputBuffer(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); // Process the data if (outCipher != null) { - // data = outCipher.doFinal(data); result = outCipher.doFinal(outgoing, offset, len); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding c (encrypted plaintext): " - + Util.dumpString(result)); - - // frameOut.setEOS(data); + if (Configuration.DEBUG) + log.fine("Encoding c (encrypted plaintext): " + + Util.dumpString(result)); out.write(result); - if (outMac != null) { outMac.update(result); if (replayDetection) { outCounter++; - if (DEBUG && debuglevel > 6) - debug(TRACE, "outCounter=" + String.valueOf(outCounter)); - outMac.update(new byte[] { (byte) (outCounter >>> 24), - (byte) (outCounter >>> 16), - (byte) (outCounter >>> 8), - (byte) outCounter }); + if (Configuration.DEBUG) + log.fine("outCounter=" + outCounter); + outMac.update(new byte[] { + (byte)(outCounter >>> 24), + (byte)(outCounter >>> 16), + (byte)(outCounter >>> 8), + (byte) outCounter }); } final byte[] C = outMac.doFinal(); - // frameOut.setOS(C); out.write(C); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding C (integrity checksum): " - + Util.dumpString(C)); - } // else confidentiality only; do nothing + if (Configuration.DEBUG) + log.fine("Encoding C (integrity checksum): " + Util.dumpString(C)); + } + // else confidentiality only; do nothing } - else - { // no confidentiality; just integrity [+ replay detection] - // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding p (plaintext): "+Util.dumpString(data)); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding p (plaintext): " - + Util.dumpString(outgoing, offset, len)); - - // frameOut.setEOS(data); + else // no confidentiality; just integrity [+ replay detection] + { + if (Configuration.DEBUG) + log.fine("Encoding p (plaintext): " + + Util.dumpString(outgoing, offset, len)); out.write(outgoing, offset, len); - - // if (outMac != null) { - // outMac.update(data); outMac.update(outgoing, offset, len); if (replayDetection) { outCounter++; - if (DEBUG && debuglevel > 6) - debug(TRACE, "outCounter=" + String.valueOf(outCounter)); - outMac.update(new byte[] { (byte) (outCounter >>> 24), - (byte) (outCounter >>> 16), - (byte) (outCounter >>> 8), - (byte) outCounter }); + if (Configuration.DEBUG) + log.fine("outCounter=" + outCounter); + outMac.update(new byte[] { + (byte)(outCounter >>> 24), + (byte)(outCounter >>> 16), + (byte)(outCounter >>> 8), + (byte) outCounter }); } final byte[] C = outMac.doFinal(); - // frameOut.setOS(C); out.write(C); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding C (integrity checksum): " - + Util.dumpString(C)); - // } + if (Configuration.DEBUG) + log.fine("Encoding C (integrity checksum): " + Util.dumpString(C)); } - - // frameOut.setEOS(data); - // - // if (outMac != null) { - // outMac.update(data); - // if (replayDetection) { - // outCounter++; - // if (DEBUG && debuglevel > 6) debug(TRACE, "outCounter="+String.valueOf(outCounter)); - // outMac.update(new byte[] { - // (byte)(outCounter >>> 24), - // (byte)(outCounter >>> 16), - // (byte)(outCounter >>> 8), - // (byte) outCounter }); - // } - // byte[] C = outMac.doFinal(); - // frameOut.setOS(C); - // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding C (integrity checksum): "+Util.dumpString(C)); - // } - - // result = frameOut.wrap(); result = out.toByteArray(); - } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("engineWrap()", x); } - - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== engineWrap()"); + if (Configuration.DEBUG) + log.exiting(this.getClass().getName(), "engineWrap"); return result; } @@ -509,13 +373,8 @@ public class SRPClient extends ClientMechanism implements SaslClient if (inMac != null) { if (inCipher != null) - { - return Registry.QOP_AUTH_CONF; - } - else - { - return Registry.QOP_AUTH_INT; - } + return Registry.QOP_AUTH_CONF; + return Registry.QOP_AUTH_INT; } return Registry.QOP_AUTH; } @@ -525,13 +384,8 @@ public class SRPClient extends ClientMechanism implements SaslClient if (inMac != null) { if (inCipher != null) - { - return Registry.STRENGTH_HIGH; - } - else - { - return Registry.STRENGTH_MEDIUM; - } + return Registry.STRENGTH_HIGH; + return Registry.STRENGTH_MEDIUM; } return Registry.STRENGTH_LOW; } @@ -546,23 +400,18 @@ public class SRPClient extends ClientMechanism implements SaslClient return Registry.REUSE_TRUE; } - // other methods ----------------------------------------------------------- - private byte[] sendIdentities() throws SaslException { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> sendIdentities()"); - + if (Configuration.DEBUG) + log.entering(this.getClass().getName(), "sendIdentities"); // If necessary, prompt the client for the username and password getUsernameAndPassword(); - - if (DEBUG && debuglevel > 6) - debug(TRACE, "Password: \"" + new String(password.getPassword()) + "\""); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding U (username): \"" + U + "\""); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding I (userid): \"" + authorizationID + "\""); - + if (Configuration.DEBUG) + { + log.fine("Password: \"" + new String(password.getPassword()) + "\""); + log.fine("Encoding U (username): \"" + U + "\""); + log.fine("Encoding I (userid): \"" + authorizationID + "\""); + } // if session re-use generate new 16-byte nonce if (sid.length != 0) { @@ -570,10 +419,7 @@ public class SRPClient extends ClientMechanism implements SaslClient getDefaultPRNG().nextBytes(cn); } else - { - cn = new byte[0]; - } - + cn = new byte[0]; final OutputBuffer frameOut = new OutputBuffer(); try { @@ -586,36 +432,30 @@ public class SRPClient extends ClientMechanism implements SaslClient catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("sendIdentities()", x); } final byte[] result = frameOut.encode(); - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== sendIdentities()"); - if (DEBUG && debuglevel > 2) - debug(INFO, "C: " + Util.dumpString(result)); - if (DEBUG && debuglevel > 2) - debug(INFO, " U = " + U); - if (DEBUG && debuglevel > 2) - debug(INFO, " I = " + authorizationID); - if (DEBUG && debuglevel > 2) - debug(INFO, "sid = " + new String(sid)); - if (DEBUG && debuglevel > 2) - debug(INFO, " cn = " + Util.dumpString(cn)); - if (DEBUG && debuglevel > 2) - debug(INFO, "cCB = " + Util.dumpString(channelBinding)); + if (Configuration.DEBUG) + { + log.fine("C: " + Util.dumpString(result)); + log.fine(" U = " + U); + log.fine(" I = " + authorizationID); + log.fine("sid = " + new String(sid)); + log.fine(" cn = " + Util.dumpString(cn)); + log.fine("cCB = " + Util.dumpString(channelBinding)); + log.exiting(this.getClass().getName(), "sendIdentities"); + } return result; } private byte[] sendPublicKey(final byte[] input) throws SaslException { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> sendPublicKey()"); - if (DEBUG && debuglevel > 6) - debug(TRACE, "S: " + Util.dumpString(input)); - + if (Configuration.DEBUG) + { + log.entering(this.getClass().getName(), "sendPublicKey"); + log.fine("S: " + Util.dumpString(input)); + } // Server sends [00], N, g, s, B, L // or [FF], sn, sCB final InputBuffer frameIn = new InputBuffer(input); @@ -623,60 +463,50 @@ public class SRPClient extends ClientMechanism implements SaslClient try { ack = (int) frameIn.getScalar(1); - if (ack == 0x00) - { // new session + if (ack == 0x00) // new session + { N = frameIn.getMPI(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got N (modulus): " + Util.dump(N)); + if (Configuration.DEBUG) + log.fine("Got N (modulus): " + Util.dump(N)); g = frameIn.getMPI(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got g (generator): " + Util.dump(g)); + if (Configuration.DEBUG) + log.fine("Got g (generator): " + Util.dump(g)); s = frameIn.getOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got s (salt): " + Util.dumpString(s)); + if (Configuration.DEBUG) + log.fine("Got s (salt): " + Util.dumpString(s)); B = frameIn.getMPI(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got B (server ephermeral public key): " - + Util.dump(B)); + if (Configuration.DEBUG) + log.fine("Got B (server ephermeral public key): " + Util.dump(B)); L = frameIn.getText(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got L (available options): \"" + L + "\""); + if (Configuration.DEBUG) + log.fine("Got L (available options): \"" + L + "\""); } - else if (ack == 0xFF) - { // session re-use + else if (ack == 0xFF) // session re-use + { sn = frameIn.getOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got sn (server nonce): " + Util.dumpString(sn)); + if (Configuration.DEBUG) + log.fine("Got sn (server nonce): " + Util.dumpString(sn)); sCB = frameIn.getEOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got sCB (server channel binding): " - + Util.dumpString(sCB)); - } - else - { // unexpected scalar - throw new SaslException("sendPublicKey(): Invalid scalar (" + ack - + ") in server's request"); + if (Configuration.DEBUG) + log.fine("Got sCB (server channel binding): " + Util.dumpString(sCB)); } + else // unexpected scalar + throw new SaslException("sendPublicKey(): Invalid scalar (" + ack + + ") in server's request"); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("sendPublicKey()", x); } - if (ack == 0x00) { // new session --------------------------------------- o = createO(L.toLowerCase()); // do this first to initialise the SRP hash - final byte[] pBytes; // use ASCII encoding to inter-operate w/ non-java pBytes = password.getBytes(); - // ---------------------------------------------------------------------- final HashMap mapA = new HashMap(); - // mapA.put(SRP6KeyAgreement.HASH_FUNCTION, srp.newDigest()); mapA.put(SRP6KeyAgreement.HASH_FUNCTION, srp.getAlgorithm()); mapA.put(SRP6KeyAgreement.USER_IDENTITY, U); mapA.put(SRP6KeyAgreement.USER_PASSWORD, pBytes); @@ -689,9 +519,6 @@ public class SRPClient extends ClientMechanism implements SaslClient { throw new SaslException("sendPublicKey()", x); } - - // ---------------------------------------------------------------------- - // ------------------------------------------------------------------- try { @@ -702,7 +529,6 @@ public class SRPClient extends ClientMechanism implements SaslClient out.writeMPI(B); IncomingMessage in = new IncomingMessage(out.toByteArray()); out = clientHandler.processMessage(in); - in = new IncomingMessage(out.toByteArray()); A = in.readMPI(); K = clientHandler.getSharedSecret(); @@ -712,13 +538,11 @@ public class SRPClient extends ClientMechanism implements SaslClient throw new SaslException("sendPublicKey()", x); } // ------------------------------------------------------------------- - - if (DEBUG && debuglevel > 6) - debug(TRACE, "K: " + Util.dumpString(K)); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding A (client ephemeral public key): " - + Util.dump(A)); - + if (Configuration.DEBUG) + { + log.fine("K: " + Util.dumpString(K)); + log.fine("Encoding A (client ephemeral public key): " + Util.dump(A)); + } try { M1 = srp.generateM1(N, g, U, s, A, B, K, authorizationID, L, cn, @@ -728,13 +552,11 @@ public class SRPClient extends ClientMechanism implements SaslClient { throw new AuthenticationException("sendPublicKey()", x); } - - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding o (client chosen options): \"" + o + "\""); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding cIV (client IV): \"" + Util.dumpString(cIV) - + "\""); - + if (Configuration.DEBUG) + { + log.fine("Encoding o (client chosen options): \"" + o + "\""); + log.fine("Encoding cIV (client IV): \"" + Util.dumpString(cIV) + "\""); + } final OutputBuffer frameOut = new OutputBuffer(); try { @@ -746,74 +568,65 @@ public class SRPClient extends ClientMechanism implements SaslClient catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("sendPublicKey()", x); } final byte[] result = frameOut.encode(); - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== sendPublicKey()"); - if (DEBUG && debuglevel > 2) - debug(INFO, "New session, or session re-use rejected..."); - if (DEBUG && debuglevel > 2) - debug(INFO, "C: " + Util.dumpString(result)); - if (DEBUG && debuglevel > 2) - debug(INFO, " A = 0x" + A.toString(16)); - if (DEBUG && debuglevel > 2) - debug(INFO, " M1 = " + Util.dumpString(M1)); - if (DEBUG && debuglevel > 2) - debug(INFO, " o = " + o); - if (DEBUG && debuglevel > 2) - debug(INFO, "cIV = " + Util.dumpString(cIV)); - + if (Configuration.DEBUG) + { + log.fine("New session, or session re-use rejected..."); + log.fine("C: " + Util.dumpString(result)); + log.fine(" A = 0x" + A.toString(16)); + log.fine(" M1 = " + Util.dumpString(M1)); + log.fine(" o = " + o); + log.fine("cIV = " + Util.dumpString(cIV)); + log.exiting(this.getClass().getName(), "sendPublicKey"); + } return result; } - else - { // session re-use accepted ------------------------------------- + else // session re-use accepted ------------------------------------------- + { setupSecurityServices(true); - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== sendPublicKey()"); - if (DEBUG && debuglevel > 2) - debug(INFO, "Session re-use accepted..."); + if (Configuration.DEBUG) + { + log.fine("Session re-use accepted..."); + log.exiting(this.getClass().getName(), "sendPublicKey"); + } return null; } } private byte[] receiveEvidence(byte[] input) throws SaslException { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> receiveEvidence()"); - if (DEBUG && debuglevel > 6) - debug(TRACE, "S: " + Util.dumpString(input)); - + if (Configuration.DEBUG) + { + log.entering(this.getClass().getName(), "receiveEvidence"); + log.fine("S: " + Util.dumpString(input)); + } // Server send M2, sIV, sCB, sid, ttl final InputBuffer frameIn = new InputBuffer(input); try { M2 = frameIn.getOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got M2 (server evidence): " + Util.dumpString(M2)); + if (Configuration.DEBUG) + log.fine("Got M2 (server evidence): " + Util.dumpString(M2)); sIV = frameIn.getOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got sIV (server IV): " + Util.dumpString(sIV)); + if (Configuration.DEBUG) + log.fine("Got sIV (server IV): " + Util.dumpString(sIV)); sid = frameIn.getEOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got sid (session ID): " + new String(sid)); + if (Configuration.DEBUG) + log.fine("Got sid (session ID): " + new String(sid)); ttl = (int) frameIn.getScalar(4); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got ttl (session time-to-live): " + ttl + "sec."); + if (Configuration.DEBUG) + log.fine("Got ttl (session time-to-live): " + ttl + "sec."); sCB = frameIn.getEOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got sCB (server channel binding): " - + Util.dumpString(sCB)); + if (Configuration.DEBUG) + log.fine("Got sCB (server channel binding): " + Util.dumpString(sCB)); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("receiveEvidence()", x); } @@ -827,18 +640,13 @@ public class SRPClient extends ClientMechanism implements SaslClient { throw new AuthenticationException("receiveEvidence()", x); } - - if (DEBUG && debuglevel > 6) - debug(TRACE, "Expected: " + Util.dumpString(expected)); - if (!Arrays.equals(M2, expected)) - { - throw new AuthenticationException("M2 mismatch"); - } - + if (Configuration.DEBUG) + log.fine("Expected: " + Util.dumpString(expected)); + if (! Arrays.equals(M2, expected)) + throw new AuthenticationException("M2 mismatch"); setupSecurityServices(false); - - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== receiveEvidence()"); + if (Configuration.DEBUG) + log.exiting(this.getClass().getName(), "receiveEvidence"); return null; } @@ -846,19 +654,15 @@ public class SRPClient extends ClientMechanism implements SaslClient { try { - if ((!properties.containsKey(Registry.SASL_USERNAME)) - && (!properties.containsKey(Registry.SASL_PASSWORD))) + if ((! properties.containsKey(Registry.SASL_USERNAME)) + && (! properties.containsKey(Registry.SASL_PASSWORD))) { final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); final PasswordCallback pwdCB = new PasswordCallback("password: ", false); handler.handle(new Callback[] { nameCB, pwdCB }); @@ -868,21 +672,15 @@ public class SRPClient extends ClientMechanism implements SaslClient else { if (properties.containsKey(Registry.SASL_USERNAME)) - { - this.U = (String) properties.get(Registry.SASL_USERNAME); - } + this.U = (String) properties.get(Registry.SASL_USERNAME); else { final NameCallback nameCB; final String defaultName = System.getProperty("user.name"); if (defaultName == null) - { - nameCB = new NameCallback("username: "); - } + nameCB = new NameCallback("username: "); else - { - nameCB = new NameCallback("username: ", defaultName); - } + nameCB = new NameCallback("username: ", defaultName); this.handler.handle(new Callback[] { nameCB }); this.U = nameCB.getName(); } @@ -897,14 +695,12 @@ public class SRPClient extends ClientMechanism implements SaslClient else if (pw instanceof String) password = new Password(((String) pw).toCharArray()); else - throw new IllegalArgumentException( - pw.getClass().getName() - + "is not a valid password class"); + throw new IllegalArgumentException(pw.getClass().getName() + + "is not a valid password class"); } else { - final PasswordCallback pwdCB = new PasswordCallback( - "password: ", + final PasswordCallback pwdCB = new PasswordCallback("password: ", false); this.handler.handle(new Callback[] { pwdCB }); password = new Password(pwdCB.getPassword()); @@ -912,13 +708,9 @@ public class SRPClient extends ClientMechanism implements SaslClient } if (U == null) - { - throw new AuthenticationException("null username supplied"); - } + throw new AuthenticationException("null username supplied"); if (password == null) - { - throw new AuthenticationException("null password supplied"); - } + throw new AuthenticationException("null password supplied"); } catch (UnsupportedCallbackException x) { @@ -935,9 +727,8 @@ public class SRPClient extends ClientMechanism implements SaslClient // to us by the client. private String createO(final String aol) throws AuthenticationException { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> createO(\"" + aol + "\")"); - + if (Configuration.DEBUG) + log.entering(this.getClass().getName(), "createO", aol); boolean replaydetectionAvailable = false; boolean integrityAvailable = false; boolean confidentialityAvailable = false; @@ -945,7 +736,6 @@ public class SRPClient extends ClientMechanism implements SaslClient int i; String mdName = SRPRegistry.SRP_DEFAULT_DIGEST_NAME; - final StringTokenizer st = new StringTokenizer(aol, ","); while (st.hasMoreTokens()) { @@ -953,55 +743,45 @@ public class SRPClient extends ClientMechanism implements SaslClient if (option.startsWith(SRPRegistry.OPTION_SRP_DIGEST + "=")) { option = option.substring(option.indexOf('=') + 1); - if (DEBUG && debuglevel > 6) - debug(TRACE, "mda: <" + option + ">"); + if (Configuration.DEBUG) + log.fine("mda: <" + option + ">"); for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++) - { - if (SRPRegistry.SRP_ALGORITHMS[i].equals(option)) - { - mdName = option; - break; - } - } + if (SRPRegistry.SRP_ALGORITHMS[i].equals(option)) + { + mdName = option; + break; + } } else if (option.equals(SRPRegistry.OPTION_REPLAY_DETECTION)) - { - replaydetectionAvailable = true; - } + replaydetectionAvailable = true; else if (option.startsWith(SRPRegistry.OPTION_INTEGRITY + "=")) { option = option.substring(option.indexOf('=') + 1); - if (DEBUG && debuglevel > 6) - debug(TRACE, "ialg: <" + option + ">"); + if (Configuration.DEBUG) + log.fine("ialg: <" + option + ">"); for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++) - { - if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option)) - { - chosenIntegrityAlgorithm = option; - integrityAvailable = true; - break; - } - } + if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option)) + { + chosenIntegrityAlgorithm = option; + integrityAvailable = true; + break; + } } else if (option.startsWith(SRPRegistry.OPTION_CONFIDENTIALITY + "=")) { option = option.substring(option.indexOf('=') + 1); - if (DEBUG && debuglevel > 6) - debug(TRACE, "calg: <" + option + ">"); + if (Configuration.DEBUG) + log.fine("calg: <" + option + ">"); for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++) - { - if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option)) - { - chosenConfidentialityAlgorithm = option; - confidentialityAvailable = true; - break; - } - } + if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option)) + { + chosenConfidentialityAlgorithm = option; + confidentialityAvailable = true; + break; + } } else if (option.startsWith(SRPRegistry.OPTION_MANDATORY + "=")) - { - mandatory = option.substring(option.indexOf('=') + 1); - } + mandatory = option.substring(option.indexOf('=') + 1); else if (option.startsWith(SRPRegistry.OPTION_MAX_BUFFER_SIZE + "=")) { final String maxBufferSize = option.substring(option.indexOf('=') + 1); @@ -1010,32 +790,27 @@ public class SRPClient extends ClientMechanism implements SaslClient rawSendSize = Integer.parseInt(maxBufferSize); if (rawSendSize > Registry.SASL_BUFFER_MAX_LIMIT || rawSendSize < 1) - { - throw new AuthenticationException( - "Illegal value for 'maxbuffersize' option"); - } + throw new AuthenticationException( + "Illegal value for 'maxbuffersize' option"); } catch (NumberFormatException x) { throw new AuthenticationException( - SRPRegistry.OPTION_MAX_BUFFER_SIZE - + "=" - + String.valueOf(maxBufferSize), - x); + SRPRegistry.OPTION_MAX_BUFFER_SIZE + "=" + maxBufferSize, x); } } } - - replayDetection = replaydetectionAvailable - && Boolean.valueOf( - (String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION)).booleanValue(); - boolean integrity = integrityAvailable - && Boolean.valueOf( - (String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION)).booleanValue(); - boolean confidentiality = confidentialityAvailable - && Boolean.valueOf( - (String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY)).booleanValue(); - + String s; + Boolean flag; + s = (String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION); + flag = Boolean.valueOf(s); + replayDetection = replaydetectionAvailable && flag.booleanValue(); + s = (String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION); + flag = Boolean.valueOf(s); + boolean integrity = integrityAvailable && flag.booleanValue(); + s = (String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY); + flag = Boolean.valueOf(s); + boolean confidentiality = confidentialityAvailable && flag.booleanValue(); // make sure we do the right thing if (SRPRegistry.OPTION_REPLAY_DETECTION.equals(mandatory)) { @@ -1043,95 +818,68 @@ public class SRPClient extends ClientMechanism implements SaslClient integrity = true; } else if (SRPRegistry.OPTION_INTEGRITY.equals(mandatory)) - { - integrity = true; - } + integrity = true; else if (SRPRegistry.OPTION_CONFIDENTIALITY.equals(mandatory)) - { - confidentiality = true; - } + confidentiality = true; + if (replayDetection) { if (chosenIntegrityAlgorithm == null) - { - throw new AuthenticationException( - "Replay detection is required but no " - + "integrity protection algorithm was chosen"); - } + throw new AuthenticationException( + "Replay detection is required but no integrity protection " + + "algorithm was chosen"); } if (integrity) { if (chosenIntegrityAlgorithm == null) - { - throw new AuthenticationException( - "Integrity protection is required but no " - + "algorithm was chosen"); - } + throw new AuthenticationException( + "Integrity protection is required but no algorithm was chosen"); } if (confidentiality) { if (chosenConfidentialityAlgorithm == null) - { - throw new AuthenticationException( - "Confidentiality protection is required " - + "but no algorithm was chosen"); - } + throw new AuthenticationException( + "Confidentiality protection is required but no algorithm was chosen"); } - // 1. check if we'll be using confidentiality; if not set IV to 0-byte if (chosenConfidentialityAlgorithm == null) - { - cIV = new byte[0]; - } + cIV = new byte[0]; else { // 2. get the block size of the cipher final IBlockCipher cipher = CipherFactory.getInstance(chosenConfidentialityAlgorithm); if (cipher == null) - { - throw new AuthenticationException("createO()", - new NoSuchAlgorithmException()); - } + throw new AuthenticationException("createO()", + new NoSuchAlgorithmException()); final int blockSize = cipher.defaultBlockSize(); // 3. generate random iv cIV = new byte[blockSize]; getDefaultPRNG().nextBytes(cIV); } - srp = SRP.instance(mdName); - // Now create the options list specifying which of the available options // we have chosen. // For now we just select the defaults. Later we need to add support for // properties (perhaps in a file) where a user can specify the list of // algorithms they would prefer to use. - final StringBuffer sb = new StringBuffer(); - sb.append(SRPRegistry.OPTION_SRP_DIGEST).append("=").append(mdName).append( - ","); + sb.append(SRPRegistry.OPTION_SRP_DIGEST) + .append("=").append(mdName).append(","); if (replayDetection) - { - sb.append(SRPRegistry.OPTION_REPLAY_DETECTION).append(","); - } + sb.append(SRPRegistry.OPTION_REPLAY_DETECTION).append(","); if (integrity) - { - sb.append(SRPRegistry.OPTION_INTEGRITY).append("=").append( - chosenIntegrityAlgorithm).append( - ","); - } + sb.append(SRPRegistry.OPTION_INTEGRITY) + .append("=").append(chosenIntegrityAlgorithm).append(","); if (confidentiality) - { - sb.append(SRPRegistry.OPTION_CONFIDENTIALITY).append("=").append( - chosenConfidentialityAlgorithm).append( - ","); - } - final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE).append( - "=").append( - Registry.SASL_BUFFER_MAX_LIMIT).toString(); - - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== createO() --> " + result); + sb.append(SRPRegistry.OPTION_CONFIDENTIALITY) + .append("=").append(chosenConfidentialityAlgorithm).append(","); + + final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE) + .append("=").append(Registry.SASL_BUFFER_MAX_LIMIT) + .toString(); + if (Configuration.DEBUG) + log.exiting(this.getClass().getName(), "createO", result); return result; } @@ -1139,33 +887,30 @@ public class SRPClient extends ClientMechanism implements SaslClient throws SaslException { complete = true; // signal end of authentication phase - if (!sessionReUse) + if (! sessionReUse) { outCounter = inCounter = 0; // instantiate cipher if confidentiality protection filter is active if (chosenConfidentialityAlgorithm != null) { - if (DEBUG && debuglevel > 2) - debug(INFO, "Activating confidentiality protection filter"); + if (Configuration.DEBUG) + log.fine("Activating confidentiality protection filter"); inCipher = CALG.getInstance(chosenConfidentialityAlgorithm); outCipher = CALG.getInstance(chosenConfidentialityAlgorithm); } // instantiate hmacs if integrity protection filter is active if (chosenIntegrityAlgorithm != null) { - if (DEBUG && debuglevel > 2) - debug(INFO, "Activating integrity protection filter"); + if (Configuration.DEBUG) + log.fine("Activating integrity protection filter"); inMac = IALG.getInstance(chosenIntegrityAlgorithm); outMac = IALG.getInstance(chosenIntegrityAlgorithm); } } - else - { // same session new Keys - K = srp.generateKn(K, cn, sn); - } + else // same session new Keys + K = srp.generateKn(K, cn, sn); final KDF kdf = KDF.getInstance(K); - // initialise in/out ciphers if confidentiality protection is used if (inCipher != null) { @@ -1178,16 +923,13 @@ public class SRPClient extends ClientMechanism implements SaslClient inMac.init(kdf); outMac.init(kdf); } - if (sid != null && sid.length != 0) { // update the security context and save in map - if (DEBUG && debuglevel > 2) - debug(INFO, "Updating security context for UID = " + uid); - ClientStore.instance().cacheSession( - uid, + if (Configuration.DEBUG) + log.fine("Updating security context for UID = " + uid); + ClientStore.instance().cacheSession(uid, ttl, - new SecurityContext( - srp.getAlgorithm(), + new SecurityContext(srp.getAlgorithm(), sid, K, cIV, @@ -1205,7 +947,6 @@ public class SRPClient extends ClientMechanism implements SaslClient { if (prng == null) prng = PRNG.getInstance(); - return prng; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPRegistry.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPRegistry.java index 262cbcb..d474cb6 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPRegistry.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPRegistry.java @@ -41,35 +41,29 @@ package gnu.javax.crypto.sasl.srp; import gnu.java.security.Registry; /** - *A list of key names designating the values exchanged between the server - * and client in an SRP communication authentication phase.
+ * A list of key names designating the values exchanged between the server + * and client in an SRP communication authentication phase. */ public interface SRPRegistry { - /** Indices of (N, g) parameter values for SRP (.conf) password database. */ String N_2048_BITS = "1"; - String N_1536_BITS = "2"; - String N_1280_BITS = "3"; - String N_1024_BITS = "4"; - String N_768_BITS = "5"; - String N_640_BITS = "6"; - String N_512_BITS = "7"; - /** Available hash algorithms for all SRP calculations. */ - String[] SRP_ALGORITHMS = { Registry.SHA160_HASH, // the default one - Registry.MD5_HASH, Registry.RIPEMD128_HASH, - Registry.RIPEMD160_HASH, - - Registry.SHA256_HASH, Registry.SHA384_HASH, - Registry.SHA512_HASH }; - + String[] SRP_ALGORITHMS = { + Registry.SHA160_HASH, // the default one + Registry.MD5_HASH, + Registry.RIPEMD128_HASH, + Registry.RIPEMD160_HASH, + + Registry.SHA256_HASH, + Registry.SHA384_HASH, + Registry.SHA512_HASH }; /** * The name of the default message digest algorithm to use when no name is * explicitely given. In this implementation it is the first among @@ -77,143 +71,95 @@ public interface SRPRegistry * 160-bit output. */ String SRP_DEFAULT_DIGEST_NAME = SRP_ALGORITHMS[0]; - /** * The property name of the message digest algorithm name to use in a given * SRP incarnation. */ String SRP_DIGEST_NAME = "srp.digest.name"; - /** The public shared modulus: n. */ String SHARED_MODULUS = "srp.N"; - /** The GF generator used: g. */ String FIELD_GENERATOR = "srp.g"; - /** The list of server's available security options. */ String AVAILABLE_OPTIONS = "srp.L"; - /** The client's chosen security options. */ String CHOSEN_OPTIONS = "srp.o"; - /** The client's username. */ String USER_NAME = "srp.U"; - /** The client's authorization ID. */ String USER_ROLE = "srp.I"; - /** The user's salt. */ String USER_SALT = "srp.s"; - /** The user's password verifier. */ String PASSWORD_VERIFIER = "srp.v"; - /** The client's public ephemeral exponent: A. */ String CLIENT_PUBLIC_KEY = "srp.A"; - /** The server's public ephemeral exponent: B. */ String SERVER_PUBLIC_KEY = "srp.B"; - /** The client's evidence: M1. */ String CLIENT_EVIDENCE = "srp.M1"; - /** The server's evidence: M2. */ String SERVER_EVIDENCE = "srp.M2"; - /** Name of underlying hash algorithm for use with all SRP calculations. */ String SRP_HASH = "gnu.crypto.sasl.srp.hash"; - /** Name of SRP mandatory service property. */ String SRP_MANDATORY = "gnu.crypto.sasl.srp.mandatory"; - /** Name of SRP replay detection property. */ String SRP_REPLAY_DETECTION = "gnu.crypto.sasl.srp.replay.detection"; - /** Name of SRP integrity protection property. */ String SRP_INTEGRITY_PROTECTION = "gnu.crypto.sasl.srp.integrity"; - /** Name of SRP confidentiality protection property. */ String SRP_CONFIDENTIALITY = "gnu.crypto.sasl.srp.confidentiality"; - /** Name of the main SRP password file pathname property. */ String PASSWORD_FILE = "gnu.crypto.sasl.srp.password.file"; - /** * Name of the SRP password database property --a reference to - * {@link gnu.crypto.sasl.srp.PasswordFile} object. + * {@link PasswordFile} object. */ String PASSWORD_DB = "gnu.crypto.sasl.srp.password.db"; - /** Default fully qualified pathname of the SRP password file. */ String DEFAULT_PASSWORD_FILE = "/etc/tpasswd"; - /** Default value for replay detection security service. */ boolean DEFAULT_REPLAY_DETECTION = true; - /** Default value for integrity protection security service. */ boolean DEFAULT_INTEGRITY = true; // implied by the previous option - /** Default value for confidentiality protection security service. */ boolean DEFAULT_CONFIDENTIALITY = false; - // constants defining HMAC names String HMAC_SHA1 = "hmac-sha1"; - String HMAC_MD5 = "hmac-md5"; - String HMAC_RIPEMD_160 = "hmac-ripemd-160"; - /** Available HMAC algorithms for integrity protection. */ String[] INTEGRITY_ALGORITHMS = { HMAC_SHA1, HMAC_MD5, HMAC_RIPEMD_160 }; - // constants defining Cipher names String AES = "aes"; - String BLOWFISH = "blowfish"; - /** Available Cipher algorithms for confidentiality protection. */ String[] CONFIDENTIALITY_ALGORITHMS = { AES, BLOWFISH }; - /** String for mandatory replay detection. */ String OPTION_MANDATORY = "mandatory"; - /** String for mda: the SRP digest algorithm name. */ String OPTION_SRP_DIGEST = "mda"; - /** String for mandatory replay detection. */ String OPTION_REPLAY_DETECTION = "replay_detection"; - /** String for mandatory integrity protection. */ String OPTION_INTEGRITY = "integrity"; - /** String for mandatory confidentiality protection. */ String OPTION_CONFIDENTIALITY = "confidentiality"; - /** String for mandatory replay detection. */ String OPTION_MAX_BUFFER_SIZE = "maxbuffersize"; - /** String for no mandatory security service. */ String MANDATORY_NONE = "none"; - /** Default mandatory security service required. */ - // String DEFAULT_MANDATORY = MANDATORY_NONE; String DEFAULT_MANDATORY = OPTION_REPLAY_DETECTION; - - // String DEFAULT_MANDATORY = OPTION_INTEGRITY; - // String DEFAULT_MANDATORY = OPTION_CONFIDENTIALITY; - /** Name of the UID field in the plain password file. */ String MD_NAME_FIELD = "srp.md.name"; - /** Name of the GID field in the plain password file. */ String USER_VERIFIER_FIELD = "srp.user.verifier"; - /** Name of the GECOS field in the plain password file. */ String SALT_FIELD = "srp.salt"; - /** Name of the SHELL field in the plain password file. */ String CONFIG_NDX_FIELD = "srp.config.ndx"; - /** Minimum bitlength of the SRP public modulus. */ int MINIMUM_MODULUS_BITLENGTH = 512; -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPServer.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPServer.java index 672660b..ff7e4e9 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPServer.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/SRPServer.java @@ -38,18 +38,18 @@ exception statement from your version. */ package gnu.javax.crypto.sasl.srp; +import gnu.java.security.Configuration; import gnu.java.security.Registry; import gnu.java.security.util.PRNG; import gnu.java.security.util.Util; - import gnu.javax.crypto.assembly.Direction; import gnu.javax.crypto.cipher.CipherFactory; import gnu.javax.crypto.cipher.IBlockCipher; import gnu.javax.crypto.key.IKeyAgreementParty; -import gnu.javax.crypto.key.KeyAgreementFactory; +import gnu.javax.crypto.key.IncomingMessage; import gnu.javax.crypto.key.KeyAgreementException; +import gnu.javax.crypto.key.KeyAgreementFactory; import gnu.javax.crypto.key.OutgoingMessage; -import gnu.javax.crypto.key.IncomingMessage; import gnu.javax.crypto.key.srp6.SRP6KeyAgreement; import gnu.javax.crypto.sasl.IllegalMechanismStateException; import gnu.javax.crypto.sasl.InputBuffer; @@ -57,114 +57,58 @@ import gnu.javax.crypto.sasl.IntegrityException; import gnu.javax.crypto.sasl.OutputBuffer; import gnu.javax.crypto.sasl.ServerMechanism; -import java.io.IOException; -import java.io.PrintWriter; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.StringTokenizer; +import java.util.logging.Logger; import javax.security.sasl.AuthenticationException; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; /** - *The SASL-SRP server-side mechanism.
+ * The SASL-SRP server-side mechanism. */ -public class SRPServer extends ServerMechanism implements SaslServer +public class SRPServer + extends ServerMechanism + implements SaslServer { - - // Debugging methods and variables - // ------------------------------------------------------------------------- - - private static final String NAME = "SRPServer"; - - // private static final String ERROR = "ERROR"; - private static final String WARN = " WARN"; - - private static final String INFO = " INFO"; - - private static final String TRACE = "DEBUG"; - - private static final boolean DEBUG = true; - - private static final int debuglevel = 3; - - private static final PrintWriter err = new PrintWriter(System.out, true); - - private static void debug(final String level, final Object obj) - { - err.println("[" + level + "] " + NAME + ": " + String.valueOf(obj)); - } - - // Constants and variables - // ------------------------------------------------------------------------- - + private static final Logger log = Logger.getLogger(SRPServer.class.getName()); private String U = null; // client's username - private BigInteger N, g, A, B; - private byte[] s; // salt - private byte[] cIV, sIV; // client+server IVs, when confidentiality is on - private byte[] cn, sn; // client's and server's nonce - private SRP srp; // SRP algorithm instance used by this server - private byte[] sid; // session ID when re-used - private int ttl = 360; // session time-to-live in seconds - private byte[] cCB; // peer's channel binding' - private String mandatory; // List of available options - private String L = null; - private String o; - private String chosenIntegrityAlgorithm; - private String chosenConfidentialityAlgorithm; - private int rawSendSize = Registry.SASL_BUFFER_MAX_LIMIT; - private byte[] K; // shared session key - private boolean replayDetection = true; // whether Replay Detection is on - private int inCounter = 0; // messages sequence numbers - private int outCounter = 0; - private IALG inMac, outMac; // if !null, use for integrity - private CALG inCipher, outCipher; // if !null, use for confidentiality - - private IKeyAgreementParty serverHandler = KeyAgreementFactory.getPartyBInstance(Registry.SRP_SASL_KA); - + private IKeyAgreementParty serverHandler = + KeyAgreementFactory.getPartyBInstance(Registry.SRP_SASL_KA); /** Our default source of randomness. */ private PRNG prng = null; - // Constructor(s) - // ------------------------------------------------------------------------- - public SRPServer() { super(Registry.SASL_SRP_MECHANISM); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // abstract methods implementation ----------------------------------------- - protected void initMechanism() throws SaslException { // TODO: @@ -183,25 +127,20 @@ public class SRPServer extends ServerMechanism implements SaslServer K = null; inMac = outMac = null; inCipher = outCipher = null; - sid = null; } - // javax.security.sasl.SaslServer interface implementation ----------------- - public byte[] evaluateResponse(final byte[] response) throws SaslException { switch (state) { case 0: if (response == null) - { - return null; - } + return null; state++; return sendProtocolElements(response); case 1: - if (!complete) + if (! complete) { state++; return sendEvidence(response); @@ -215,65 +154,15 @@ public class SRPServer extends ServerMechanism implements SaslServer protected byte[] engineUnwrap(final byte[] incoming, final int offset, final int len) throws SaslException { - // if (DEBUG && debuglevel > 8) debug(TRACE, "==> engineUnwrap()"); - // - // if (inMac == null && inCipher == null) { - // throw new IllegalStateException("connection is not protected"); - // } - // - // if (DEBUG && debuglevel > 6) debug(TRACE, "Incoming buffer (before security): "+Util.dumpString(incoming, offset, len)); - // - // byte[] data = null; - // try { - // InputBuffer frameIn = InputBuffer.getInstance(incoming, offset, len); - // data = frameIn.getEOS(); - // if (inMac != null) { - // byte[] received_mac = frameIn.getOS(); - // if (DEBUG && debuglevel > 6) debug(TRACE, "Got C (received MAC): "+Util.dumpString(received_mac)); - // inMac.update(data); - // if (replayDetection) { - // inCounter++; - // if (DEBUG && debuglevel > 6) debug(TRACE, "inCounter="+String.valueOf(inCounter)); - // inMac.update(new byte[] { - // (byte)(inCounter >>> 24), - // (byte)(inCounter >>> 16), - // (byte)(inCounter >>> 8), - // (byte) inCounter }); - // } - // final byte[] computed_mac = inMac.doFinal(); - // if (DEBUG && debuglevel > 6) debug(TRACE, "Computed MAC: "+Util.dumpString(computed_mac)); - // if (!Arrays.equals(received_mac, computed_mac)) - // throw new IntegrityException("engineUnwrap()"); - // } - // if (inCipher != null) { - // data = inCipher.doFinal(data); - // } - // } catch (IOException x) { - // if (x instanceof SaslException) { - // throw (SaslException) x; - // } - // throw new SaslException("engineUnwrap()", x); - // } - // - // if (DEBUG && debuglevel > 6) debug(TRACE, "Incoming buffer (after security): "+Util.dumpString(data)); - // if (DEBUG && debuglevel > 8) debug(TRACE, "<== engineUnwrap()"); - // return data; - - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> engineUnwrap()"); - + if (Configuration.DEBUG) + log.entering(this.getClass().getName(), "engineUnwrap"); if (inMac == null && inCipher == null) - { - throw new IllegalStateException("connection is not protected"); - } - - if (DEBUG && debuglevel > 6) - debug(TRACE, "Incoming buffer (before security): " - + Util.dumpString(incoming, offset, len)); - + throw new IllegalStateException("connection is not protected"); + if (Configuration.DEBUG) + log.fine("Incoming buffer (before security): " + + Util.dumpString(incoming, offset, len)); // at this point one, or both, of confidentiality and integrity protection // services are active. - final byte[] result; try { @@ -284,137 +173,67 @@ public class SRPServer extends ServerMechanism implements SaslServer final byte[] received_mac = new byte[macBytesCount]; System.arraycopy(incoming, offset + payloadLength, received_mac, 0, macBytesCount); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got C (received MAC): " - + Util.dumpString(received_mac)); + if (Configuration.DEBUG) + log.fine("Got C (received MAC): " + Util.dumpString(received_mac)); inMac.update(incoming, offset, payloadLength); if (replayDetection) { inCounter++; - if (DEBUG && debuglevel > 6) - debug(TRACE, "inCounter=" + String.valueOf(inCounter)); - inMac.update(new byte[] { (byte) (inCounter >>> 24), - (byte) (inCounter >>> 16), - (byte) (inCounter >>> 8), - (byte) inCounter }); + if (Configuration.DEBUG) + log.fine("inCounter=" + String.valueOf(inCounter)); + inMac.update(new byte[] { + (byte)(inCounter >>> 24), + (byte)(inCounter >>> 16), + (byte)(inCounter >>> 8), + (byte) inCounter }); } - final byte[] computed_mac = inMac.doFinal(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Computed MAC: " + Util.dumpString(computed_mac)); - if (!Arrays.equals(received_mac, computed_mac)) - { - throw new IntegrityException("engineUnwrap()"); - } - + if (Configuration.DEBUG) + log.fine("Computed MAC: " + Util.dumpString(computed_mac)); + if (! Arrays.equals(received_mac, computed_mac)) + throw new IntegrityException("engineUnwrap()"); // deal with the payload, which can be either plain or encrypted if (inCipher != null) - { - result = inCipher.doFinal(incoming, offset, payloadLength); - } + result = inCipher.doFinal(incoming, offset, payloadLength); else { result = new byte[payloadLength]; System.arraycopy(incoming, offset, result, 0, result.length); } } - else - { // no integrity protection; just confidentiality - // if (inCipher != null) { - result = inCipher.doFinal(incoming, offset, len); - // } else { - // result = new byte[len]; - // System.arraycopy(incoming, offset, result, 0, len); - // } - } + else // no integrity protection; just confidentiality + result = inCipher.doFinal(incoming, offset, len); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("engineUnwrap()", x); } - if (DEBUG && debuglevel > 6) - debug(TRACE, "Incoming buffer (after security): " - + Util.dumpString(result)); - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== engineUnwrap()"); + if (Configuration.DEBUG) + { + log.fine("Incoming buffer (after security): " + Util.dumpString(result)); + log.exiting(this.getClass().getName(), "engineUnwrap"); + } return result; } protected byte[] engineWrap(final byte[] outgoing, final int offset, final int len) throws SaslException { - // if (DEBUG && debuglevel > 8) debug(TRACE, "==> engineWrap()"); - // - // if (outMac == null && outCipher == null) { - // throw new IllegalStateException("connection is not protected"); - // } - // - // byte[] data = new byte[len]; - // System.arraycopy(outgoing, offset, data, 0, len); - // - // if (DEBUG && debuglevel > 6) debug(TRACE, "Outgoing buffer (before security) (hex): "+Util.dumpString(data)); - // if (DEBUG && debuglevel > 6) debug(TRACE, "Outgoing buffer (before security) (str): \""+new String(data)+"\""); - // - // final byte[] result; - // try { - // OutputBuffer frameOut = new OutputBuffer(); - // // Process the data - // if (outCipher != null) { - // data = outCipher.doFinal(data); - // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding c (encrypted plaintext): "+Util.dumpString(data)); - // } else { - // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding p (plaintext): "+Util.dumpString(data)); - // } - // frameOut.setEOS(data); - // if (outMac != null) { - // outMac.update(data); - // if (replayDetection) { - // outCounter++; - // if (DEBUG && debuglevel > 6) debug(TRACE, "outCounter="+String.valueOf(outCounter)); - // outMac.update(new byte[] { - // (byte)(outCounter >>> 24), - // (byte)(outCounter >>> 16), - // (byte)(outCounter >>> 8), - // (byte) outCounter}); - // } - // byte[] C = outMac.doFinal(); - // frameOut.setOS(C); - // if (DEBUG && debuglevel > 6) debug(TRACE, "Encoding C (integrity checksum): "+Util.dumpString(C)); - // } - // result = frameOut.wrap(); - // - // } catch (IOException x) { - // if (x instanceof SaslException) { - // throw (SaslException) x; - // } - // throw new SaslException("engineWrap()", x); - // } - // - // if (DEBUG && debuglevel > 8) debug(TRACE, "<== engineWrap()"); - // return result; - - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> engineWrap()"); - + if (Configuration.DEBUG) + log.entering(this.getClass().getName(), "engineWrap"); if (outMac == null && outCipher == null) + throw new IllegalStateException("connection is not protected"); + if (Configuration.DEBUG) { - throw new IllegalStateException("connection is not protected"); + log.fine("Outgoing buffer (before security) (hex): " + + Util.dumpString(outgoing, offset, len)); + log.fine("Outgoing buffer (before security) (str): \"" + + new String(outgoing, offset, len) + "\""); } - - if (DEBUG && debuglevel > 6) - debug(TRACE, "Outgoing buffer (before security) (hex): " - + Util.dumpString(outgoing, offset, len)); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Outgoing buffer (before security) (str): \"" - + new String(outgoing, offset, len) + "\""); - // at this point one, or both, of confidentiality and integrity protection // services are active. - byte[] result; try { @@ -422,74 +241,64 @@ public class SRPServer extends ServerMechanism implements SaslServer if (outCipher != null) { result = outCipher.doFinal(outgoing, offset, len); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding c (encrypted plaintext): " - + Util.dumpString(result)); - + if (Configuration.DEBUG) + log.fine("Encoding c (encrypted plaintext): " + + Util.dumpString(result)); out.write(result); - if (outMac != null) { outMac.update(result); if (replayDetection) { outCounter++; - if (DEBUG && debuglevel > 6) - debug(TRACE, "outCounter=" + String.valueOf(outCounter)); - outMac.update(new byte[] { (byte) (outCounter >>> 24), - (byte) (outCounter >>> 16), - (byte) (outCounter >>> 8), - (byte) outCounter }); + if (Configuration.DEBUG) + log.fine("outCounter=" + outCounter); + outMac.update(new byte[] { + (byte)(outCounter >>> 24), + (byte)(outCounter >>> 16), + (byte)(outCounter >>> 8), + (byte) outCounter }); } final byte[] C = outMac.doFinal(); out.write(C); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding C (integrity checksum): " - + Util.dumpString(C)); - } // else ciphertext only; do nothing + if (Configuration.DEBUG) + log.fine("Encoding C (integrity checksum): " + Util.dumpString(C)); + } + // else ciphertext only; do nothing } - else - { // no confidentiality; just integrity [+ replay detection] - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding p (plaintext): " - + Util.dumpString(outgoing, offset, len)); - + else // no confidentiality; just integrity [+ replay detection] + { + if (Configuration.DEBUG) + log.fine("Encoding p (plaintext): " + + Util.dumpString(outgoing, offset, len)); out.write(outgoing, offset, len); - - // if (outMac != null) { outMac.update(outgoing, offset, len); if (replayDetection) { outCounter++; - if (DEBUG && debuglevel > 6) - debug(TRACE, "outCounter=" + String.valueOf(outCounter)); - outMac.update(new byte[] { (byte) (outCounter >>> 24), - (byte) (outCounter >>> 16), - (byte) (outCounter >>> 8), - (byte) outCounter }); + if (Configuration.DEBUG) + log.fine("outCounter=" + outCounter); + outMac.update(new byte[] { + (byte)(outCounter >>> 24), + (byte)(outCounter >>> 16), + (byte)(outCounter >>> 8), + (byte) outCounter }); } final byte[] C = outMac.doFinal(); out.write(C); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding C (integrity checksum): " - + Util.dumpString(C)); - // } // else plaintext only; do nothing + if (Configuration.DEBUG) + log.fine("Encoding C (integrity checksum): " + Util.dumpString(C)); } - result = out.toByteArray(); - } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new SaslException("engineWrap()", x); } - - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== engineWrap()"); + if (Configuration.DEBUG) + log.exiting(this.getClass().getName(), "engineWrap"); return result; } @@ -498,13 +307,8 @@ public class SRPServer extends ServerMechanism implements SaslServer if (inMac != null) { if (inCipher != null) - { - return Registry.QOP_AUTH_CONF; - } - else - { - return Registry.QOP_AUTH_INT; - } + return Registry.QOP_AUTH_CONF; + return Registry.QOP_AUTH_INT; } return Registry.QOP_AUTH; } @@ -514,13 +318,8 @@ public class SRPServer extends ServerMechanism implements SaslServer if (inMac != null) { if (inCipher != null) - { - return Registry.STRENGTH_HIGH; - } - else - { - return Registry.STRENGTH_MEDIUM; - } + return Registry.STRENGTH_HIGH; + return Registry.STRENGTH_MEDIUM; } return Registry.STRENGTH_LOW; } @@ -535,45 +334,39 @@ public class SRPServer extends ServerMechanism implements SaslServer return Registry.REUSE_TRUE; } - // other methods ----------------------------------------------------------- - private byte[] sendProtocolElements(final byte[] input) throws SaslException { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> sendProtocolElements()"); - if (DEBUG && debuglevel > 6) - debug(TRACE, "C: " + Util.dumpString(input)); - + if (Configuration.DEBUG) + { + log.entering(this.getClass().getName(), "sendProtocolElements"); + log.fine("C: " + Util.dumpString(input)); + } // Client send U, I, sid, cn final InputBuffer frameIn = new InputBuffer(input); try { U = frameIn.getText(); // Extract username - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got U (username): \"" + U + "\""); + if (Configuration.DEBUG) + log.fine("Got U (username): \"" + U + "\""); authorizationID = frameIn.getText(); // Extract authorisation ID - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got I (userid): \"" + authorizationID + "\""); + if (Configuration.DEBUG) + log.fine("Got I (userid): \"" + authorizationID + "\""); sid = frameIn.getEOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got sid (session ID): " + new String(sid)); + if (Configuration.DEBUG) + log.fine("Got sid (session ID): " + new String(sid)); cn = frameIn.getOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got cn (client nonce): " + Util.dumpString(cn)); + if (Configuration.DEBUG) + log.fine("Got cn (client nonce): " + Util.dumpString(cn)); cCB = frameIn.getEOS(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got cCB (client channel binding): " - + Util.dumpString(cCB)); + if (Configuration.DEBUG) + log.fine("Got cCB (client channel binding): " + Util.dumpString(cCB)); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("sendProtocolElements()", x); } - // do/can we re-use? if (ServerStore.instance().isAlive(sid)) { @@ -589,15 +382,10 @@ public class SRPServer extends ServerMechanism implements SaslServer outMac = ctx.getOutMac(); inCipher = ctx.getInCipher(); outCipher = ctx.getOutCipher(); - if (sn == null || sn.length != 16) - { - sn = new byte[16]; - } + sn = new byte[16]; getDefaultPRNG().nextBytes(sn); - setupSecurityServices(false); - final OutputBuffer frameOut = new OutputBuffer(); try { @@ -608,34 +396,27 @@ public class SRPServer extends ServerMechanism implements SaslServer catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("sendProtocolElements()", x); } final byte[] result = frameOut.encode(); - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== sendProtocolElements()"); - if (DEBUG && debuglevel > 2) - debug(INFO, "Old session..."); - if (DEBUG && debuglevel > 2) - debug(INFO, "S: " + Util.dumpString(result)); - if (DEBUG && debuglevel > 2) - debug(INFO, " sn = " + Util.dumpString(sn)); - if (DEBUG && debuglevel > 2) - debug(INFO, " sCB = " + Util.dumpString(channelBinding)); + if (Configuration.DEBUG) + { + log.fine("Old session..."); + log.fine("S: " + Util.dumpString(result)); + log.fine(" sn = " + Util.dumpString(sn)); + log.fine(" sCB = " + Util.dumpString(channelBinding)); + log.exiting(this.getClass().getName(), "sendProtocolElements"); + } return result; } else { // new session authenticator.activate(properties); - // ------------------------------------------------------------------- final HashMap mapB = new HashMap(); - // mapB.put(SRP6KeyAgreement.HASH_FUNCTION, srp.newDigest()); mapB.put(SRP6KeyAgreement.HASH_FUNCTION, srp.getAlgorithm()); mapB.put(SRP6KeyAgreement.HOST_PASSWORD_DB, authenticator); - try { serverHandler.init(mapB); @@ -643,7 +424,6 @@ public class SRPServer extends ServerMechanism implements SaslServer out.writeString(U); IncomingMessage in = new IncomingMessage(out.toByteArray()); out = serverHandler.processMessage(in); - in = new IncomingMessage(out.toByteArray()); N = in.readMPI(); g = in.readMPI(); @@ -655,26 +435,22 @@ public class SRPServer extends ServerMechanism implements SaslServer throw new SaslException("sendProtocolElements()", x); } // ------------------------------------------------------------------- - - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding N (modulus): " + Util.dump(N)); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding g (generator): " + Util.dump(g)); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding s (client's salt): " + Util.dumpString(s)); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding B (server ephemeral public key): " - + Util.dump(B)); - + if (Configuration.DEBUG) + { + log.fine("Encoding N (modulus): " + Util.dump(N)); + log.fine("Encoding g (generator): " + Util.dump(g)); + log.fine("Encoding s (client's salt): " + Util.dumpString(s)); + log.fine("Encoding B (server ephemeral public key): " + Util.dump(B)); + } // The server creates an options list (L), which consists of a // comma-separated list of option strings that specify the security // service options the server supports. L = createL(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding L (available options): \"" + L + "\""); - if (DEBUG && debuglevel > 6) - debug(TRACE, "Encoding sIV (server IV): " + Util.dumpString(sIV)); - + if (Configuration.DEBUG) + { + log.fine("Encoding L (available options): \"" + L + "\""); + log.fine("Encoding sIV (server IV): " + Util.dumpString(sIV)); + } final OutputBuffer frameOut = new OutputBuffer(); try { @@ -688,69 +464,58 @@ public class SRPServer extends ServerMechanism implements SaslServer catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("sendProtocolElements()", x); } final byte[] result = frameOut.encode(); - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== sendProtocolElements()"); - if (DEBUG && debuglevel > 2) - debug(INFO, "New session..."); - if (DEBUG && debuglevel > 2) - debug(INFO, "S: " + Util.dumpString(result)); - if (DEBUG && debuglevel > 2) - debug(INFO, " N = 0x" + N.toString(16)); - if (DEBUG && debuglevel > 2) - debug(INFO, " g = 0x" + g.toString(16)); - if (DEBUG && debuglevel > 2) - debug(INFO, " s = " + Util.dumpString(s)); - if (DEBUG && debuglevel > 2) - debug(INFO, " B = 0x" + B.toString(16)); - if (DEBUG && debuglevel > 2) - debug(INFO, " L = " + L); + if (Configuration.DEBUG) + { + log.fine("New session..."); + log.fine("S: " + Util.dumpString(result)); + log.fine(" N = 0x" + N.toString(16)); + log.fine(" g = 0x" + g.toString(16)); + log.fine(" s = " + Util.dumpString(s)); + log.fine(" B = 0x" + B.toString(16)); + log.fine(" L = " + L); + log.exiting(this.getClass().getName(), "sendProtocolElements"); + } return result; } } private byte[] sendEvidence(final byte[] input) throws SaslException { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> sendEvidence()"); - if (DEBUG && debuglevel > 6) - debug(TRACE, "C: " + Util.dumpString(input)); - + if (Configuration.DEBUG) + { + log.entering(this.getClass().getName(), "sendEvidence"); + log.fine("C: " + Util.dumpString(input)); + } // Client send A, M1, o, cIV final InputBuffer frameIn = new InputBuffer(input); final byte[] M1; try { A = frameIn.getMPI(); // Extract client's ephemeral public key - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got A (client ephemeral public key): " + Util.dump(A)); + if (Configuration.DEBUG) + log.fine("Got A (client ephemeral public key): " + Util.dump(A)); M1 = frameIn.getOS(); // Extract evidence - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got M1 (client evidence): " + Util.dumpString(M1)); + if (Configuration.DEBUG) + log.fine("Got M1 (client evidence): " + Util.dumpString(M1)); o = frameIn.getText(); // Extract client's options list - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got o (client chosen options): \"" + o + "\""); + if (Configuration.DEBUG) + log.fine("Got o (client chosen options): \"" + o + "\""); cIV = frameIn.getOS(); // Extract client's IV - if (DEBUG && debuglevel > 6) - debug(TRACE, "Got cIV (client IV): " + Util.dumpString(cIV)); + if (Configuration.DEBUG) + log.fine("Got cIV (client IV): " + Util.dumpString(cIV)); } catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("sendEvidence()", x); } - // Parse client's options and set security layer variables parseO(o); - // ---------------------------------------------------------------------- try { @@ -765,10 +530,8 @@ public class SRPServer extends ServerMechanism implements SaslServer throw new SaslException("sendEvidence()", x); } // ---------------------------------------------------------------------- - - if (DEBUG && debuglevel > 6) - debug(TRACE, "K: " + Util.dumpString(K)); - + if (Configuration.DEBUG) + log.fine("K: " + Util.dumpString(K)); final byte[] expected; try { @@ -779,15 +542,10 @@ public class SRPServer extends ServerMechanism implements SaslServer { throw new AuthenticationException("sendEvidence()", x); } - // Verify client evidence - if (!Arrays.equals(M1, expected)) - { - throw new AuthenticationException("M1 mismatch"); - } - + if (! Arrays.equals(M1, expected)) + throw new AuthenticationException("M1 mismatch"); setupSecurityServices(true); - final byte[] M2; try { @@ -798,7 +556,6 @@ public class SRPServer extends ServerMechanism implements SaslServer { throw new AuthenticationException("sendEvidence()", x); } - final OutputBuffer frameOut = new OutputBuffer(); try { @@ -811,93 +568,71 @@ public class SRPServer extends ServerMechanism implements SaslServer catch (IOException x) { if (x instanceof SaslException) - { - throw (SaslException) x; - } + throw (SaslException) x; throw new AuthenticationException("sendEvidence()", x); } final byte[] result = frameOut.encode(); - if (DEBUG && debuglevel > 2) - debug(INFO, "S: " + Util.dumpString(result)); - if (DEBUG && debuglevel > 2) - debug(INFO, " M2 = " + Util.dumpString(M2)); - if (DEBUG && debuglevel > 2) - debug(INFO, " sIV = " + Util.dumpString(sIV)); - if (DEBUG && debuglevel > 2) - debug(INFO, " sid = " + new String(sid)); - if (DEBUG && debuglevel > 2) - debug(INFO, " ttl = " + ttl); - if (DEBUG && debuglevel > 2) - debug(INFO, " sCB = " + Util.dumpString(channelBinding)); - - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== sendEvidence()"); + if (Configuration.DEBUG) + { + log.fine("S: " + Util.dumpString(result)); + log.fine(" M2 = " + Util.dumpString(M2)); + log.fine(" sIV = " + Util.dumpString(sIV)); + log.fine(" sid = " + new String(sid)); + log.fine(" ttl = " + ttl); + log.fine(" sCB = " + Util.dumpString(channelBinding)); + log.exiting(this.getClass().getName(), "sendEvidence"); + } return result; } private String createL() { - if (DEBUG && debuglevel > 8) - debug(TRACE, "==> createL()"); - + if (Configuration.DEBUG) + log.entering(this.getClass().getName(), "createL()"); String s = (String) properties.get(SRPRegistry.SRP_MANDATORY); if (s == null) + s = SRPRegistry.DEFAULT_MANDATORY; + + if (! SRPRegistry.MANDATORY_NONE.equals(s) + && ! SRPRegistry.OPTION_REPLAY_DETECTION.equals(s) + && ! SRPRegistry.OPTION_INTEGRITY.equals(s) + && ! SRPRegistry.OPTION_CONFIDENTIALITY.equals(s)) { + if (Configuration.DEBUG) + log.fine("Unrecognised mandatory option (" + s + "). Using default..."); s = SRPRegistry.DEFAULT_MANDATORY; } - if (!SRPRegistry.MANDATORY_NONE.equals(s) - && !SRPRegistry.OPTION_REPLAY_DETECTION.equals(s) - && !SRPRegistry.OPTION_INTEGRITY.equals(s) - && !SRPRegistry.OPTION_CONFIDENTIALITY.equals(s)) - { - if (DEBUG && debuglevel > 4) - debug(WARN, "Unrecognised mandatory option (" + s - + "). Using default..."); - s = SRPRegistry.DEFAULT_MANDATORY; - } - mandatory = s; - s = (String) properties.get(SRPRegistry.SRP_CONFIDENTIALITY); final boolean confidentiality = (s == null ? SRPRegistry.DEFAULT_CONFIDENTIALITY - : Boolean.valueOf(s).booleanValue()); - + : Boolean.valueOf(s).booleanValue()); s = (String) properties.get(SRPRegistry.SRP_INTEGRITY_PROTECTION); boolean integrity = (s == null ? SRPRegistry.DEFAULT_INTEGRITY - : Boolean.valueOf(s).booleanValue()); - + : Boolean.valueOf(s).booleanValue()); s = (String) properties.get(SRPRegistry.SRP_REPLAY_DETECTION); final boolean replayDetection = (s == null ? SRPRegistry.DEFAULT_REPLAY_DETECTION - : Boolean.valueOf(s).booleanValue()); - + : Boolean.valueOf(s).booleanValue()); final StringBuffer sb = new StringBuffer(); - sb.append(SRPRegistry.OPTION_SRP_DIGEST).append("=").append( - srp.getAlgorithm()).append( - ","); + sb.append(SRPRegistry.OPTION_SRP_DIGEST).append("=") + .append(srp.getAlgorithm()).append(","); + + if (! SRPRegistry.MANDATORY_NONE.equals(mandatory)) + sb.append(SRPRegistry.OPTION_MANDATORY) + .append("=").append(mandatory).append(","); - if (!SRPRegistry.MANDATORY_NONE.equals(mandatory)) - { - sb.append(SRPRegistry.OPTION_MANDATORY).append("=").append(mandatory).append( - ","); - } if (replayDetection) { sb.append(SRPRegistry.OPTION_REPLAY_DETECTION).append(","); // if replay detection is on then force integrity protection integrity = true; } - int i; if (integrity) { for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++) - { - sb.append(SRPRegistry.OPTION_INTEGRITY).append("=").append( - SRPRegistry.INTEGRITY_ALGORITHMS[i]).append( - ","); - } + sb.append(SRPRegistry.OPTION_INTEGRITY).append("=") + .append(SRPRegistry.INTEGRITY_ALGORITHMS[i]).append(","); } - if (confidentiality) { IBlockCipher cipher; @@ -905,19 +640,15 @@ public class SRPServer extends ServerMechanism implements SaslServer { cipher = CipherFactory.getInstance(SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i]); if (cipher != null) - { - sb.append(SRPRegistry.OPTION_CONFIDENTIALITY).append("=").append( - SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i]).append( - ","); - } + sb.append(SRPRegistry.OPTION_CONFIDENTIALITY).append("=") + .append(SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i]).append(","); } } - - final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE).append( - "=").append( - Registry.SASL_BUFFER_MAX_LIMIT).toString(); - if (DEBUG && debuglevel > 8) - debug(TRACE, "<== createL()"); + final String result = sb.append(SRPRegistry.OPTION_MAX_BUFFER_SIZE) + .append("=").append(Registry.SASL_BUFFER_MAX_LIMIT) + .toString(); + if (Configuration.DEBUG) + log.exiting(this.getClass().getName(), "createL"); return result; } @@ -934,69 +665,51 @@ public class SRPServer extends ServerMechanism implements SaslServer while (st.hasMoreTokens()) { option = st.nextToken(); - if (DEBUG && debuglevel > 6) - debug(TRACE, "option: <" + option + ">"); + if (Configuration.DEBUG) + log.fine("option: <" + option + ">"); if (option.equals(SRPRegistry.OPTION_REPLAY_DETECTION)) - { - replayDetection = true; - } + replayDetection = true; else if (option.startsWith(SRPRegistry.OPTION_INTEGRITY + "=")) { if (integrity) + throw new AuthenticationException( + "Only one integrity algorithm may be chosen"); + option = option.substring(option.indexOf('=') + 1); + if (Configuration.DEBUG) + log.fine("algorithm: <" + option + ">"); + for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++) { - throw new AuthenticationException( - "Only one integrity algorithm may be chosen"); - } - else - { - option = option.substring(option.indexOf('=') + 1); - if (DEBUG && debuglevel > 6) - debug(TRACE, "algorithm: <" + option + ">"); - for (i = 0; i < SRPRegistry.INTEGRITY_ALGORITHMS.length; i++) - { - if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option)) - { - chosenIntegrityAlgorithm = option; - integrity = true; - break; - } - } - if (!integrity) + if (SRPRegistry.INTEGRITY_ALGORITHMS[i].equals(option)) { - throw new AuthenticationException( - "Unknown integrity algorithm: " - + option); + chosenIntegrityAlgorithm = option; + integrity = true; + break; } } + if (! integrity) + throw new AuthenticationException("Unknown integrity algorithm: " + + option); } else if (option.startsWith(SRPRegistry.OPTION_CONFIDENTIALITY + "=")) { if (confidentiality) + throw new AuthenticationException( + "Only one confidentiality algorithm may be chosen"); + option = option.substring(option.indexOf('=') + 1); + if (Configuration.DEBUG) + log.fine("algorithm: <" + option + ">"); + for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++) { - throw new AuthenticationException( - "Only one confidentiality algorithm may be chosen"); - } - else - { - option = option.substring(option.indexOf('=') + 1); - if (DEBUG && debuglevel > 6) - debug(TRACE, "algorithm: <" + option + ">"); - for (i = 0; i < SRPRegistry.CONFIDENTIALITY_ALGORITHMS.length; i++) - { - if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option)) - { - chosenConfidentialityAlgorithm = option; - confidentiality = true; - break; - } - } - if (!confidentiality) + if (SRPRegistry.CONFIDENTIALITY_ALGORITHMS[i].equals(option)) { - throw new AuthenticationException( - "Unknown confidentiality algorithm: " - + option); + chosenConfidentialityAlgorithm = option; + confidentiality = true; + break; } } + if (! confidentiality) + throw new AuthenticationException("Unknown confidentiality algorithm: " + + option); } else if (option.startsWith(SRPRegistry.OPTION_MAX_BUFFER_SIZE + "=")) { @@ -1007,70 +720,51 @@ public class SRPServer extends ServerMechanism implements SaslServer if (rawSendSize > Registry.SASL_BUFFER_MAX_LIMIT || rawSendSize < 1) throw new AuthenticationException( - "Illegal value for 'maxbuffersize' option"); + "Illegal value for 'maxbuffersize' option"); } catch (NumberFormatException x) { throw new AuthenticationException( - SRPRegistry.OPTION_MAX_BUFFER_SIZE - + "=" - + String.valueOf(maxBufferSize), - x); + SRPRegistry.OPTION_MAX_BUFFER_SIZE + "=" + maxBufferSize, x); } } } - // check if client did the right thing if (replayDetection) { - if (!integrity) - { - throw new AuthenticationException( - "Missing integrity protection algorithm " - + "but replay detection is chosen"); - } + if (! integrity) + throw new AuthenticationException( + "Missing integrity protection algorithm but replay detection is chosen"); } if (mandatory.equals(SRPRegistry.OPTION_REPLAY_DETECTION)) { - if (!replayDetection) - { - throw new AuthenticationException( - "Replay detection is mandatory but was not chosen"); - } + if (! replayDetection) + throw new AuthenticationException( + "Replay detection is mandatory but was not chosen"); } if (mandatory.equals(SRPRegistry.OPTION_INTEGRITY)) { - if (!integrity) - { - throw new AuthenticationException( - "Integrity protection is mandatory but was not chosen"); - } + if (! integrity) + throw new AuthenticationException( + "Integrity protection is mandatory but was not chosen"); } if (mandatory.equals(SRPRegistry.OPTION_CONFIDENTIALITY)) { - if (!confidentiality) - { - throw new AuthenticationException( - "Confidentiality is mandatory but was not chosen"); - } + if (! confidentiality) + throw new AuthenticationException( + "Confidentiality is mandatory but was not chosen"); } - int blockSize = 0; if (chosenConfidentialityAlgorithm != null) { final IBlockCipher cipher = CipherFactory.getInstance(chosenConfidentialityAlgorithm); if (cipher != null) - { - blockSize = cipher.defaultBlockSize(); - } - else - { // should not happen - throw new AuthenticationException("Confidentiality algorithm (" - + chosenConfidentialityAlgorithm - + ") not available"); - } + blockSize = cipher.defaultBlockSize(); + else // should not happen + throw new AuthenticationException("Confidentiality algorithm (" + + chosenConfidentialityAlgorithm + + ") not available"); } - sIV = new byte[blockSize]; if (blockSize > 0) getDefaultPRNG().nextBytes(sIV); @@ -1086,30 +780,26 @@ public class SRPServer extends ServerMechanism implements SaslServer // instantiate cipher if confidentiality protection filter is active if (chosenConfidentialityAlgorithm != null) { - if (DEBUG && debuglevel > 2) - debug(INFO, "Activating confidentiality protection filter"); + if (Configuration.DEBUG) + log.fine("Activating confidentiality protection filter"); inCipher = CALG.getInstance(chosenConfidentialityAlgorithm); outCipher = CALG.getInstance(chosenConfidentialityAlgorithm); } // instantiate hmacs if integrity protection filter is active if (chosenIntegrityAlgorithm != null) { - if (DEBUG && debuglevel > 2) - debug(INFO, "Activating integrity protection filter"); + if (Configuration.DEBUG) + log.fine("Activating integrity protection filter"); inMac = IALG.getInstance(chosenIntegrityAlgorithm); outMac = IALG.getInstance(chosenIntegrityAlgorithm); } - // generate a new sid if at least integrity is used sid = (inMac != null ? ServerStore.getNewSessionID() : new byte[0]); } - else - { // same session new keys - K = srp.generateKn(K, cn, sn); - } + else // same session new keys + K = srp.generateKn(K, cn, sn); final KDF kdf = KDF.getInstance(K); - // initialise in/out ciphers if confidentaility protection is used if (inCipher != null) { @@ -1122,15 +812,12 @@ public class SRPServer extends ServerMechanism implements SaslServer outMac.init(kdf); inMac.init(kdf); } - if (sid != null && sid.length != 0) { // update the security context and save in map - if (DEBUG && debuglevel > 2) - debug(INFO, "Updating security context for sid = " + new String(sid)); - ServerStore.instance().cacheSession( - ttl, - new SecurityContext( - srp.getAlgorithm(), + if (Configuration.DEBUG) + log.fine("Updating security context for sid = " + new String(sid)); + ServerStore.instance().cacheSession(ttl, + new SecurityContext(srp.getAlgorithm(), sid, K, cIV, @@ -1148,7 +835,6 @@ public class SRPServer extends ServerMechanism implements SaslServer { if (prng == null) prng = PRNG.getInstance(); - return prng; } } diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/SecurityContext.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/SecurityContext.java index feca25c..1111d95 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/SecurityContext.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/SecurityContext.java @@ -39,41 +39,23 @@ exception statement from your version. */ package gnu.javax.crypto.sasl.srp; /** - *A package-private placeholder for an SRP security context.
+ * A package-private placeholder for an SRP security context. */ class SecurityContext { - - // Constants and variables - // ------------------------------------------------------------------------- - private String mdName; - private byte[] sid; - private byte[] K; - private byte[] cIV; - private byte[] sIV; - private boolean replayDetection; - private int inCounter; - private int outCounter; - private IALG inMac; - private IALG outMac; - private CALG inCipher; - private CALG outCipher; - // Constructor(s) - // ------------------------------------------------------------------------- - SecurityContext(final String mdName, final byte[] sid, final byte[] K, final byte[] cIV, final byte[] sIV, final boolean replayDetection, final int inCounter, @@ -96,12 +78,6 @@ class SecurityContext this.outCipher = outCipher; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - String getMdName() { return mdName; @@ -161,4 +137,4 @@ class SecurityContext { return outCipher; } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/ServerStore.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/ServerStore.java index 99bf96a..e9b1a72 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/ServerStore.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/ServerStore.java @@ -41,32 +41,21 @@ package gnu.javax.crypto.sasl.srp; import java.util.HashMap; /** - *The server-side implementation of the SRP security context store.
+ * The server-side implementation of the SRP security context store. */ public class ServerStore { - - // Constants and variables - // ------------------------------------------------------------------------- - /** The underlying singleton. */ private static ServerStore singleton = null; - /** The map of sid --> Security Context record. */ private static final HashMap sid2ssc = new HashMap(); - /** The map of sid --> Session timing record. */ private static final HashMap sid2ttl = new HashMap(); - /** A synchronisation lock. */ private static final Object lock = new Object(); - /** A counter to generate legible SIDs. */ private static int counter = 0; - // Constructor(s) - // ------------------------------------------------------------------------- - /** Private constructor to enforce Singleton pattern. */ private ServerStore() { @@ -75,48 +64,38 @@ public class ServerStore // TODO: add a cleaning timer thread } - // Class methods - // ------------------------------------------------------------------------- - /** - *Returns the classloader Singleton.
- * + * Returns the classloader Singleton. + * * @return the classloader Singleton instance. */ static synchronized final ServerStore instance() { if (singleton == null) - { - singleton = new ServerStore(); - } + singleton = new ServerStore(); return singleton; } /** - *Returns a legible new session identifier.
- * + * Returns a legible new session identifier. + * * @return a new session identifier. */ static synchronized final byte[] getNewSessionID() { final String sid = String.valueOf(++counter); - return new StringBuffer("SID-").append( - "0000000000".substring( - 0, - 10 - sid.length())).append( - sid).toString().getBytes(); + return new StringBuffer("SID-") + .append("0000000000".substring(0, 10 - sid.length())).append(sid) + .toString().getBytes(); } - // Instance methods - // ------------------------------------------------------------------------- - /** - *Returns a boolean flag indicating if the designated session is still - * alive or not.
- * + * Returns a boolean flag indicating if the designated session is still alive + * or not. + * * @param sid the identifier of the session to check. * @returntrue
if the designated session is still alive.
- * false
otherwise.
+ * false
otherwise.
*/
boolean isAlive(final byte[] sid)
{
@@ -130,8 +109,8 @@ public class ServerStore
if (ctx != null)
{
result = ctx.isAlive();
- if (!result)
- { // invalidate it en-passant
+ if (! result) // invalidate it en-passant
+ {
sid2ssc.remove(key);
sid2ttl.remove(key);
}
@@ -142,9 +121,9 @@ public class ServerStore
}
/**
- * Records a mapping between a session identifier and the Security Context - * of the designated SRP server mechanism instance.
- * + * Records a mapping between a session identifier and the Security Context of + * the designated SRP server mechanism instance. + * * @param ttl the session's Time-To-Live indicator (in seconds). * @param ctx the server's security context. */ @@ -159,11 +138,11 @@ public class ServerStore } /** - *Updates the mapping between the designated session identifier and the - * designated server's SASL Security Context. In the process, computes - * and return the underlying mechanism server's evidence that shall be - * returned to the client in a session re-use exchange.
- * + * Updates the mapping between the designated session identifier and the + * designated server's SASL Security Context. In the process, computes and + * return the underlying mechanism server's evidence that shall be returned to + * the client in a session re-use exchange. + * * @param sid the identifier of the session to restore. * @return an SRP server's security context. */ @@ -180,8 +159,8 @@ public class ServerStore } /** - *Removes all information related to the designated session ID.
- * + * Removes all information related to the designated session ID. + * * @param sid the identifier of the seesion to invalidate. */ void invalidateSession(final byte[] sid) @@ -193,4 +172,4 @@ public class ServerStore sid2ttl.remove(key); } } -} \ No newline at end of file +} diff --git a/libjava/classpath/gnu/javax/crypto/sasl/srp/StoreEntry.java b/libjava/classpath/gnu/javax/crypto/sasl/srp/StoreEntry.java index c5041fa..130678e 100644 --- a/libjava/classpath/gnu/javax/crypto/sasl/srp/StoreEntry.java +++ b/libjava/classpath/gnu/javax/crypto/sasl/srp/StoreEntry.java @@ -39,21 +39,13 @@ exception statement from your version. */ package gnu.javax.crypto.sasl.srp; /** - *A simple timing-related object for use by SRP re-use code.
+ * A simple timing-related object for use by SRP re-use code. */ class StoreEntry { - - // Constants and variables - // ------------------------------------------------------------------------- - private boolean perenial; - private long timeToDie; - // Constructor(s) - // ------------------------------------------------------------------------- - StoreEntry(int ttl) { super(); @@ -70,20 +62,14 @@ class StoreEntry } } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - /** - *Returns true
if the Time-To_live period has not elapsed.
true
if the Time-To_live period has not elapsed.
+ *
* @return true
if the Time-To-Live period (in seconds) has not
- * elapsed yet; false
otherwise.
+ * elapsed yet; false
otherwise.
*/
boolean isAlive()
{
return (perenial ? true : (System.currentTimeMillis() < timeToDie));
}
-}
\ No newline at end of file
+}
diff --git a/libjava/classpath/gnu/javax/imageio/IIOInputStream.java b/libjava/classpath/gnu/javax/imageio/IIOInputStream.java
new file mode 100644
index 0000000..2638e2f
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/IIOInputStream.java
@@ -0,0 +1,102 @@
+/* GIFStream.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio;
+
+import java.io.InputStream;
+import java.io.IOException;
+import javax.imageio.stream.ImageInputStream;
+
+/**
+ * Implements InputStream on an ImageInputStream
+ * The purpose of this is to avoid IIO dependencies in the various decoders.
+ * (which only use read() anyway).
+ */
+public class IIOInputStream extends InputStream
+{
+ private ImageInputStream is;
+
+ public IIOInputStream( ImageInputStream is )
+ {
+ this.is = is;
+ }
+
+ public int available()
+ {
+ return 0;
+ }
+
+ public void close() throws IOException
+ {
+ is.close();
+ }
+
+ public void mark(int readlimit)
+ {
+ is.mark();
+ }
+
+ public boolean markSupported()
+ {
+ return true;
+ }
+
+ public int read() throws IOException
+ {
+ return is.read();
+ }
+
+ public int read(byte[] b) throws IOException
+ {
+ return is.read(b);
+ }
+
+ public int read(byte[] b, int offset, int length) throws IOException
+ {
+ return is.read(b, offset, length);
+ }
+
+ public void reset() throws IOException
+ {
+ is.reset();
+ }
+
+ public long skip(long n) throws IOException
+ {
+ return is.skipBytes(n);
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/gif/GIFFile.java b/libjava/classpath/gnu/javax/imageio/gif/GIFFile.java
new file mode 100644
index 0000000..a11a8c0
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/gif/GIFFile.java
@@ -0,0 +1,709 @@
+/* GIFFile.java -- GIF decoder
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.gif;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Vector;
+
+/**
+ * GIFFile - reads a GIF file.
+ *
+ * This class only does the bare minimum work, and returns the data in raw
+ * formats (described below). The class is J2ME compatible, and hopefully
+ * we can keep it that way without any significant overhead.
+ *
+ * @author Sven de Marothy.
+ */
+public class GIFFile
+{
+ // "NETSCAPE2.0" - identifier
+ private final static byte[] nsBlock = new byte[]
+ {0x4e, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2e, 0x30 };
+
+ /**
+ * Block identifiers
+ */
+ private final static int EXTENSION = 0x21;
+ private final static int LOCAL = 0x2C;
+ private final static int TERMINATOR = 0x3B;
+
+ /**
+ * Extension block types
+ */
+ private final static int EXTENSION_COMMENT = 254;
+ private final static int EXTENSION_GCONTROL = 249;
+ private final static int EXTENSION_APPLICATION = 255;
+
+ /**
+ * Undraw commands for animation.
+ */
+ private final static int UNDRAW_OVERWRITE = 1;
+ private final static int UNDRAW_RESTORE_BACKGROUND = 2;
+ private final static int UNDRAW_RESTORE_PREVIOUS = 3;
+
+ /**
+ * Image position and dimensions (images may be partial)
+ */
+ private int x, y, width, height;
+
+ /**
+ * Global dimensions
+ */
+ private int globalWidth, globalHeight;
+
+ /**
+ * Background color index.
+ */
+ private byte bgIndex;
+
+ /**
+ * Number of colors
+ */
+ private int nColors;
+
+ /**
+ * Global palette, if any
+ */
+ private byte[] globalPalette;
+
+ /**
+ * Any
+ */
+ private boolean hasGlobalColorMap;
+
+ /**
+ * Local palette, if any (used if available)
+ */
+ private byte[] localPalette;
+
+ /**
+ * Interlaced GIF or not?
+ */
+ private boolean interlaced;
+
+ /**
+ * Has transparency?
+ */
+ private boolean hasTransparency;
+
+ /**
+ * Undraw mode (animations)
+ */
+ private int undraw;
+
+ /**
+ * Transparent index;
+ */
+ private int transparentIndex;
+
+ /**
+ * The uncompressed raster
+ */
+ private byte[] raster;
+
+ /**
+ * The compressed data (freed after uncompressing)
+ */
+ private byte[] compressedData;
+
+ /**
+ * Frame delay in 100ths of a second ( centiseconds, metrically )
+ */
+ private int duration;
+
+ /**
+ * Indices used during decompression
+ */
+ private int dataBlockIndex;
+
+ /**
+ * The file comment , if a comment block exists.
+ */
+ private String comment;
+
+ /**
+ * Fields used by getBits()
+ */
+ private int remainingBits = 0;
+ private int currentBits = 0;
+
+ /**
+ * Netscape animation extension
+ */
+ private boolean isLooped = false;
+
+ /** Number of loops, 0 = infinite */
+ private int loops;
+
+ /**
+ * Additional frames if it's an animated GIF.
+ */
+ private Vector animationFrames;
+
+ /**
+ * Loads the file from an input stream, which is not closed.
+ * @throws IOException if an I/O error occured.
+ * @throws GIFException if some file parsing error occured
+ */
+ public GIFFile(InputStream in) throws IOException, GIFException
+ {
+ // Validate the signature
+ if( !readSignature( in ) )
+ throw new GIFException("Invalid GIF signature.");
+
+ {
+ byte[] data = new byte[7];
+ if (in.read(data) != 7)
+ throw new IOException("Couldn't read global descriptor.");
+
+ globalWidth = ((data[1] & 0xFF) << 8) | (data[0] & 0xFF);
+ globalHeight = ((data[3] & 0xFF) << 8) | (data[2] & 0xFF);
+ byte flags = data[4];
+ bgIndex = data[5];
+ nColors = (1 << (( flags & 0x07) + 1));
+ hasGlobalColorMap = ((flags & 0x80) != 0);
+ }
+
+ if( hasGlobalColorMap )
+ {
+ globalPalette = new byte[ nColors * 3 ];
+ if( in.read( globalPalette ) != nColors * 3 )
+ throw new IOException("Couldn't read color map.");
+ }
+
+ int c = in.read();
+ while( c == EXTENSION )
+ {
+ readExtension( in );
+ c = in.read();
+ }
+
+ if( c != LOCAL )
+ throw new GIFException("Extension blocks not followed by a local descriptor ("+c+")");
+
+ loadImage( in );
+ c = in.read();
+
+ if( c == TERMINATOR ) // Not an animated GIF.
+ return;
+
+ // Load animation frames. Just quit if an error occurs instead
+ // of throwing an exception.
+ animationFrames = new Vector();
+ try
+ {
+ while( c != TERMINATOR )
+ {
+ animationFrames.add( new GIFFile( this, in, c ) );
+ c = in.read();
+ }
+ }
+ catch(IOException ioe)
+ {
+ }
+ catch(GIFException gife)
+ {
+ }
+ }
+
+ /**
+ * Constructor for additional animation frames.
+ */
+ private GIFFile(GIFFile parent, InputStream in, int c)
+ throws IOException, GIFException
+ {
+ // Copy global properties.
+ globalWidth = parent.globalWidth;
+ globalHeight = parent.globalHeight;
+ nColors = parent.nColors;
+ globalPalette = parent.globalPalette;
+ hasGlobalColorMap = parent.hasGlobalColorMap;
+ interlaced = parent.interlaced;
+ comment = parent.comment;
+ isLooped = parent.isLooped;
+ loops = parent.loops;
+
+ while( c == EXTENSION )
+ {
+ readExtension( in );
+ c = in.read();
+ }
+
+ if( c != LOCAL )
+ throw new GIFException("Extension blocks not followed by a local descriptor ("+c+")");
+
+ loadImage( in );
+ }
+
+ /**
+ * Reads a GIF file signature from an inputstream and checks it.
+ *
+ * @param in - the stream (reads 6 bytes, does not close or reset).
+ * @return true if the signature is a valid GIF signature.
+ * @throws an IOException if the signature could not be read.
+ */
+ public static boolean readSignature( InputStream in ) throws IOException
+ {
+ byte[] data = new byte[6];
+ if (in.read(data) != 6)
+ throw new IOException("Couldn't read signature.");
+
+ if( data[0] != 0x47 || data[1] != 0x49 || data[2] != 0x46 ||
+ data[3] != 0x38 ) // GIF8
+ return false;
+
+ if( (data[4] != 0x39 && data[4] != 0x37) || // 7 | 9
+ (data[5] != 0x61 && data[5] != 0x62) ) // 'a' or 'b'
+ return false;
+ return true;
+ }
+
+
+ /**
+ * Loads the image local descriptor and then loads/decodes the image raster,
+ * and then performs any necessary postprocessing like deinterlacing.
+ */
+ private void loadImage(InputStream in)
+ throws IOException, GIFException
+ {
+ readLocal( in );
+
+ try
+ {
+ decodeRaster( in );
+ }
+ catch(ArrayIndexOutOfBoundsException aioobe)
+ {
+ throw new GIFException("Error decompressing image.");
+ }
+
+ if( interlaced ) // Clean up
+ deinterlace();
+ packPixels();
+ }
+
+ /**
+ * Pack the pixels if it's a 2, 4 or 16 color image.
+ * While GIF may support any number of colors from 2-256, we won't bother
+ * trying to pack pixels not resulting in even byte boundaries.
+ * (AWT doesn't support that anyway, and most apps do the same.)
+ */
+ private void packPixels()
+ {
+ if( nColors != 2 && nColors != 4 && nColors != 16 )
+ return;
+
+ int nbits = 1;
+ int ppbyte = 8;
+ if( nColors == 4 )
+ {
+ nbits = 2;
+ ppbyte = 4;
+ }
+ else if( nColors == 16 )
+ {
+ nbits = 4;
+ ppbyte = 2;
+ }
+
+ int rem = (width & (ppbyte - 1));
+ int w = ( rem == 0 ) ? (width / ppbyte) :
+ ((width + ppbyte - rem) / ppbyte);
+ byte[] nr = new byte[ w * height ];
+ for(int j = 0; j < height; j++)
+ {
+ for(int i = 0; i < width - ppbyte; i += ppbyte)
+ for(int k = 0; k < ppbyte; k++)
+ nr[ j * w + (i / ppbyte) ] |= (byte)((raster[ width * j + i + k ]
+ << (8 - nbits * (1 + k))));
+ for(int i = 0; i < rem; i++)
+ nr[ j * w + w - 1 ] |= (byte)((raster[ width * j + width - rem + i ]
+ << (nbits * (rem - i))));
+ }
+ raster = nr;
+ }
+
+ /**
+ * Returns the (global) width
+ */
+ public int getWidth()
+ {
+ return width;
+ }
+
+ /**
+ * Returns the image height
+ */
+ public int getHeight()
+ {
+ return height;
+ }
+
+ /**
+ * Returns the # of colors.
+ */
+ public int getNColors()
+ {
+ return nColors;
+ }
+
+ /**
+ * Returns whether the GIF has transparency.
+ */
+ public boolean hasTransparency()
+ {
+ return hasTransparency;
+ }
+
+ /**
+ * Returns the index of the transparent color.
+ */
+ public int getTransparentIndex()
+ {
+ return transparentIndex;
+ }
+
+ /**
+ * Retuns the GIF file comment, or null if none exists.
+ */
+ public String getComment()
+ {
+ return comment;
+ }
+
+ /**
+ * Get duration of the frame for animations.
+ */
+ public int getDuration()
+ {
+ return duration;
+ }
+
+ /**
+ * Deinterlaces the image.
+ */
+ private void deinterlace()
+ {
+ byte[] nr = new byte[ width * height ];
+ int n = 0;
+ for(int i = 0; i < ((height + 7) >> 3); i++)
+ {
+ System.arraycopy( raster, n, nr, width * i * 8, width );
+ n += width;
+ }
+ for(int i = 0; i < ((height + 3) >> 3); i++)
+ {
+ System.arraycopy( raster, n, nr, width * ( 8 * i + 4 ), width );
+ n += width;
+ }
+ for(int i = 0; i < (height >> 2); i++)
+ {
+ System.arraycopy( raster, n, nr, width * (4 * i + 2), width );
+ n += width;
+ }
+ for(int i = 0; i < (height >> 1); i++)
+ {
+ System.arraycopy( raster, n, nr, width * (2 * i + 1), width );
+ n += width;
+ }
+ raster = nr;
+ }
+
+ /**
+ * Reads the local descriptor
+ */
+ private void readLocal(InputStream in) throws IOException
+ {
+ byte[] data = new byte[9];
+ if (in.read(data) != 9)
+ throw new IOException("Couldn't read local descriptor.");
+ x = ((data[1] & 0xFF) << 8) | (data[0] & 0xFF);
+ y = ((data[3] & 0xFF) << 8) | (data[2] & 0xFF);
+ width = ((data[5] & 0xFF) << 8) | (data[4] & 0xFF);
+ height = ((data[7] & 0xFF) << 8) | (data[6] & 0xFF);
+ byte flags = data[8];
+ interlaced = (( flags & 0x40 ) != 0);
+ if( (flags & 0x80) != 0 )
+ { // has a local color map
+ int nLocalColors = (1 << (( flags & 0x07) + 1));
+ if( !hasGlobalColorMap )
+ nColors = nLocalColors;
+ localPalette = new byte[ nLocalColors * 3 ];
+ if( in.read( localPalette ) != nLocalColors * 3 )
+ throw new IOException("Couldn't read color map.");
+ }
+ }
+
+ /**
+ * Returns the image's palette in raw format
+ * (r0,g0,b0,r1,g1,b2..r(Ncolors-1),g(Ncolors-1),b(Ncolors-1))
+ */
+ public byte[] getRawPalette()
+ {
+ return hasGlobalColorMap ? globalPalette : localPalette;
+ }
+
+ /**
+ * Returns the image file for animated gifs.
+ */
+ public GIFFile getImage( int index )
+ {
+ if( index == 0 )
+ return this;
+ if( animationFrames == null )
+ throw new ArrayIndexOutOfBoundsException("Only one image in file");
+ return (GIFFile)animationFrames.elementAt( index - 1 );
+ }
+
+ /**
+ * Return the image's raw image data.
+ * If the color depth is 1,2 or 4 bits per pixel the pixels are packed
+ * and the scanlines padded up to the nearest byte if needed.
+ */
+ public byte[] getRawImage()
+ {
+ return raster;
+ }
+
+ /**
+ * Return the number of images in the GIF file
+ */
+ public int nImages()
+ {
+ if( animationFrames != null )
+ return 1 + animationFrames.size();
+ return 1;
+ }
+
+ /**
+ * Handles extension blocks.
+ */
+ private void readExtension(InputStream in) throws IOException, GIFException
+ {
+ int functionCode = in.read();
+ byte[] data = readData(in);
+ switch( functionCode )
+ {
+ case EXTENSION_COMMENT: // comment block
+ comment = new String(data, "8859_1");
+ break;
+
+ case EXTENSION_GCONTROL: // Graphics control extension
+ undraw = (data[0] & 0x1C) >> 2;
+ // allegedly there can be bad values of this.
+ if( undraw < 1 && undraw > 3 ) undraw = 1;
+ hasTransparency = ((data[0] & 0x01) == 1);
+ transparentIndex = (data[3] & 0xFF);
+ duration = ((data[2] & 0xFF) << 8) | (data[1] & 0xFF);
+ break;
+
+ // Application extension. We only parse the Netscape animation
+ // extension here. Which is the only one most use anyway.
+ case EXTENSION_APPLICATION:
+ boolean isNS = true;
+ for(int i = 0; i < nsBlock.length; i++ )
+ if( nsBlock[i] != data[i] )
+ isNS = false;
+ if( isNS )
+ {
+ isLooped = true;
+ loops = ((data[12] & 0xFF) << 8) | (data[13] & 0xFF);
+ }
+ break;
+
+ default:
+ break;
+ }
+ }
+
+ /**
+ * Reads a series of data blocks and merges them into a single one.
+ */
+ private byte[] readData(InputStream in) throws IOException
+ {
+ Vector v = new Vector();
+ int totalBytes = 0;
+
+ int n = in.read();
+ do
+ {
+ totalBytes += n;
+ byte[] block = new byte[ n ];
+ in.read(block);
+ v.add(block);
+ n = in.read();
+ }
+ while( n > 0 );
+
+ n = 0;
+ byte[] bigBuffer = new byte[ totalBytes ];
+ for( int i = 0; i < v.size(); i++ )
+ {
+ byte[] block = (byte[])v.elementAt(i);
+ System.arraycopy(block, 0, bigBuffer, n, block.length);
+ n += block.length;
+ }
+ return bigBuffer;
+ }
+
+ /**
+ * Loads a compressed image block and decompresses it.
+ */
+ private void decodeRaster(InputStream in) throws IOException
+ {
+ int initialCodeSize = in.read();
+ compressedData = readData( in );
+ dataBlockIndex = 0;
+
+ int rasterIndex = 0; // Index into the raster
+ int clearCode = (1 << initialCodeSize); // 256 usually
+ int endCode = clearCode + 1; // The stop code.
+
+ raster = new byte[ width * height ];
+
+ int codeSize = initialCodeSize + 1;
+ int code = getBits( codeSize ); // = clear
+ int nextCode = endCode + 1;
+
+ /*
+ * Initialize LZW dictionary
+ *
+ * First index - code #
+ * Second index:
+ * 0 = color index
+ * 1 = parent (-1 - no parent)
+ * 2 = first value
+ * 3 - depth
+ * The latter two aren't strictly necessary but make things faster, since
+ * copying the values forward is faster than going back and looking.
+ */
+ short[][] dictionary = new short[ 4096 ][ 4 ];
+
+ for(short i = 0; i < nColors; i ++ )
+ {
+ dictionary[i][0] = i; // color index
+ dictionary[i][1] = -1; // parent
+ dictionary[i][2] = i; // first
+ dictionary[i][3] = 1; // depth
+ }
+
+ code = getBits( codeSize ); // get second code
+ raster[ rasterIndex++ ] = (byte)dictionary[code][0];
+ int old = code;
+ code = getBits( codeSize ); // start at the third code
+ int c;
+
+ do
+ {
+ if( code == clearCode )
+ {
+ codeSize = initialCodeSize + 1;
+ nextCode = endCode + 1;
+ // get and output second code
+ code = getBits( codeSize );
+ raster[ rasterIndex++ ] = (byte)dictionary[code][0];
+ old = code;
+ }
+ else
+ {
+ dictionary[nextCode][1] = (short)old; // parent = old
+ dictionary[nextCode][2] = dictionary[old][2]; // first pixel
+ dictionary[nextCode][3] = (short)(dictionary[old][3] + 1); // depth
+
+ // appended pixel = first pixel of c
+ if( code < nextCode )
+ {
+ dictionary[nextCode][0] = dictionary[code][2];
+ old = code;
+ }
+ else // first of old
+ {
+ dictionary[nextCode][0] = dictionary[old][2];
+ old = nextCode;
+ }
+
+ c = old;
+ // output the code c
+ int depth = dictionary[c][3];
+ for( int i = depth - 1; i >= 0; i-- )
+ {
+ raster[ rasterIndex + i ] = (byte)dictionary[c][0];
+ c = dictionary[c][1]; // go to parent.
+ }
+ rasterIndex += depth;
+ nextCode ++;
+
+ if( codeSize < 12 && nextCode >= (1 << codeSize) )
+ codeSize++;
+ }
+ code = getBits( codeSize );
+ }
+ while( code != endCode && dataBlockIndex < compressedData.length );
+
+ compressedData = null; // throw away compressed data.
+ }
+
+ /**
+ * Returns nbits number of bits (in the LSBs) from compressedData
+ */
+ private int getBits( int nbits )
+ {
+ while( nbits > remainingBits )
+ {
+ int c = (compressedData[ dataBlockIndex++ ] & 0xFF) << remainingBits;
+ currentBits |= c;
+ remainingBits += 8;
+ }
+ int rval = (currentBits & ((1 << nbits) - 1));
+ currentBits = (currentBits >> nbits);
+ remainingBits -= nbits;
+ return rval;
+ }
+
+ /**
+ * Generic exception used by GIFFile to report decoding errors.
+ */
+ public static class GIFException extends Exception
+ {
+ public GIFException(String message)
+ {
+ super(message);
+ }
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/gif/GIFImageReader.java b/libjava/classpath/gnu/javax/imageio/gif/GIFImageReader.java
new file mode 100644
index 0000000..47108dd
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/gif/GIFImageReader.java
@@ -0,0 +1,241 @@
+/* GIFImageReader.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.gif;
+
+import gnu.javax.imageio.IIOInputStream;
+
+import java.io.IOException;
+import java.io.InputStream;
+import javax.imageio.*;
+import javax.imageio.spi.*;
+import javax.imageio.metadata.*;
+import javax.imageio.stream.ImageInputStream;
+import java.util.Iterator;
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+import java.awt.image.SampleModel;
+import java.awt.image.MultiPixelPackedSampleModel;
+import java.awt.image.SinglePixelPackedSampleModel;
+import java.awt.image.DataBuffer;
+import java.awt.image.DataBufferByte;
+import java.awt.image.Raster;
+import java.awt.image.WritableRaster;
+
+public class GIFImageReader extends ImageReader
+{
+ private GIFFile file;
+
+ protected GIFImageReader(ImageReaderSpi originatingProvider)
+ {
+ super( originatingProvider );
+ file = null;
+ }
+
+ private void readImage() throws IOException
+ {
+ if( file != null )
+ return;
+
+ try
+ {
+ if( input instanceof InputStream )
+ file = new GIFFile( (InputStream)input );
+ else
+ file = new GIFFile( new IIOInputStream((ImageInputStream)input) );
+ }
+ catch(GIFFile.GIFException ge)
+ {
+ throw new IIOException(ge.getMessage());
+ }
+ }
+
+ /**
+ * Returns the Global/Local palette as an IndexColorModel
+ */
+ private IndexColorModel getPalette(int index)
+ {
+ GIFFile f = file.getImage( index );
+ byte[] data = f.getRawPalette();
+ int nc = f.getNColors();
+ byte[] r = new byte[nc];
+ byte[] g = new byte[nc];
+ byte[] b = new byte[nc];
+
+ for(int i = 0; i < nc; i ++ )
+ {
+ r[i] = data[ i * 3 ];
+ g[i] = data[ i * 3 + 1 ];
+ b[i] = data[ i * 3 + 2 ];
+ }
+
+ if( f.hasTransparency() )
+ {
+ byte[] a = new byte[nc];
+ for(int i = 0; i < nc; i ++ )
+ a[i] = (byte)0xFF;
+ a[f.getTransparentIndex()] = 0;
+ return new IndexColorModel(8, nc, r, g, b, a);
+ }
+
+ return new IndexColorModel(8, nc, r, g, b);
+ }
+
+ private void validateIndex(int imageIndex)
+ throws IndexOutOfBoundsException
+ {
+ if( imageIndex < 0 || imageIndex >= getNumImages(false) )
+ throw new IndexOutOfBoundsException("Invalid image index.");
+ }
+
+ public void setInput(Object input)
+ {
+ super.setInput(input);
+ }
+
+ public void setInput(Object input,
+ boolean seekForwardOnly,
+ boolean ignoreMetadata)
+ {
+ super.setInput(input, seekForwardOnly, ignoreMetadata);
+ }
+
+ public void setInput(Object input, boolean isStreamable)
+ {
+ super.setInput(input, isStreamable);
+
+ if (!(input instanceof ImageInputStream) &&
+ !(input instanceof InputStream))
+ throw new IllegalArgumentException("Input not an ImageInputStream.");
+ }
+
+ private void checkStream() throws IOException
+ {
+ if (!(input instanceof ImageInputStream) &&
+ !(input instanceof InputStream))
+ throw new IllegalStateException("Input not an ImageInputStream or InputStream.");
+
+ if(input == null)
+ throw new IllegalStateException("No input stream.");
+ }
+
+ public int getWidth(int imageIndex) throws IOException
+ {
+ validateIndex( imageIndex );
+ return file.getImage( imageIndex ).getWidth();
+ }
+
+ public int getHeight(int imageIndex) throws IOException
+ {
+ validateIndex( imageIndex );
+ return file.getImage( imageIndex ).getHeight();
+ }
+
+ public Iterator getImageTypes(int imageIndex)
+ {
+ validateIndex( imageIndex );
+ return null;
+ }
+
+ /**
+ * Returns the number of images.
+ */
+ public int getNumImages(boolean allowSearch)
+ {
+ try // Image should be loaded here already. But just in case:
+ {
+ readImage();
+ }
+ catch(IOException ioe)
+ {
+ return 0; // Well, now we're in trouble. But return something anyway.
+ }
+ return file.nImages();
+ }
+
+
+ // FIXME: Support metadata
+ public IIOMetadata getImageMetadata(int imageIndex)
+ {
+ validateIndex( imageIndex );
+ return null;
+ }
+
+ // FIXME: Support metadata
+ public IIOMetadata getStreamMetadata()
+ {
+ return null;
+ }
+
+ /**
+ * Reads the image indexed by imageIndex and returns it as
+ * a complete BufferedImage, using a supplied ImageReadParam.
+ */
+ public BufferedImage read(int imageIndex, ImageReadParam param)
+ throws IOException, IIOException
+ {
+ validateIndex( imageIndex );
+ GIFFile f = file.getImage( imageIndex );
+ int width = f.getWidth();
+ int height = f.getHeight();
+ SampleModel sm;
+ switch( f.getNColors() )
+ {
+ case 16:
+ sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ width, height, 4);
+ break;
+ case 4:
+ sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ width, height, 2);
+ break;
+ case 2:
+ sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ width, height, 1);
+ break;
+ default:
+ sm = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE,
+ width, height,
+ new int[] {0xFF});
+ break;
+ }
+ DataBuffer db = new DataBufferByte(f.getRawImage(), width * height, 0);
+ WritableRaster raster = Raster.createWritableRaster(sm, db, null);
+
+ return new BufferedImage(getPalette( imageIndex ), raster, false, null);
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/gif/GIFImageReaderSpi.java b/libjava/classpath/gnu/javax/imageio/gif/GIFImageReaderSpi.java
new file mode 100644
index 0000000..a318486
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/gif/GIFImageReaderSpi.java
@@ -0,0 +1,124 @@
+/* GIFImageReaderSpi.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.gif;
+
+import gnu.javax.imageio.IIOInputStream;
+
+import java.io.InputStream;
+import java.io.IOException;
+import java.util.Locale;
+import javax.imageio.ImageReader;
+import javax.imageio.spi.ImageReaderSpi;
+import javax.imageio.stream.ImageInputStream;
+
+public class GIFImageReaderSpi extends ImageReaderSpi
+{
+ static final String vendorName = "GNU";
+ static final String version = "0.1";
+ static final String readerClassName =
+ "gnu.javax.imageio.gif.GIFImageReader";
+ static final String[] names = { "Compuserve GIF" };
+ static final String[] suffixes = { ".gif" };
+ static final String[] MIMETypes = {
+ "image/gif",
+ "image/x-gif"}; // Not sure this is legal, but it seems to be used a bit
+ static final String[] writerSpiNames = null;
+ static final boolean supportsStandardStreamMetadataFormat = false;
+ static final String nativeStreamMetadataFormatName = null;
+ static final String nativeStreamMetadataFormatClassName = null;
+ static final String[] extraStreamMetadataFormatNames = null;
+ static final String[] extraStreamMetadataFormatClassNames = null;
+ static final boolean supportsStandardImageMetadataFormat = false;
+ static final String nativeImageMetadataFormatName = null;
+ static final String nativeImageMetadataFormatClassName = null;
+ static final String[] extraImageMetadataFormatNames = null;
+ static final String[] extraImageMetadataFormatClassNames = null;
+
+ public GIFImageReaderSpi()
+ {
+ super(vendorName, version,
+ names, suffixes, MIMETypes,
+ readerClassName,
+ new Class[]{ ImageInputStream.class, InputStream.class },
+ writerSpiNames,
+ supportsStandardStreamMetadataFormat,
+ nativeStreamMetadataFormatName,
+ nativeStreamMetadataFormatClassName,
+ extraStreamMetadataFormatNames,
+ extraStreamMetadataFormatClassNames,
+ supportsStandardImageMetadataFormat,
+ nativeImageMetadataFormatName,
+ nativeImageMetadataFormatClassName,
+ extraImageMetadataFormatNames,
+ extraImageMetadataFormatClassNames);
+ }
+
+ public String getDescription(Locale locale)
+ {
+ return "Compuserve GIF";
+ }
+
+ public boolean canDecodeInput(Object input)
+ throws IOException
+ {
+ if( input == null )
+ throw new IllegalArgumentException("Input object cannot be null.");
+
+ if( !(input instanceof ImageInputStream) &&
+ !(input instanceof InputStream))
+ return false;
+
+ boolean retval;
+ InputStream in;
+ if( input instanceof ImageInputStream )
+ in = new IIOInputStream( (ImageInputStream)input );
+ else
+ in = (InputStream)input;
+
+ in.mark(10); // we read 6 bytes
+ retval = GIFFile.readSignature( in );
+ in.reset();
+
+ return retval;
+ }
+
+ public ImageReader createReaderInstance(Object extension)
+ {
+ return new GIFImageReader(this);
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/jpeg/DCT.java b/libjava/classpath/gnu/javax/imageio/jpeg/DCT.java
new file mode 100644
index 0000000..91b6eb8
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/jpeg/DCT.java
@@ -0,0 +1,347 @@
+/* DCT.java --
+ Copyright (C) 2005 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.jpeg;
+
+/**
+ * Discrete Cosine Transformations.
+ */
+public class DCT
+{
+
+ /**
+ * Cosine matrix
+ */
+ public double c[][] = new double[8][8];
+
+ /**
+ * Transformed cosine matrix
+ */
+ public double cT[][] = new double[8][8];
+
+ public DCT()
+ {
+ initMatrix();
+ }
+
+ /**
+ * Figure A.3.3 IDCT, Cu Cv on A-5 of the ISO DIS 10918-1. Requirements and
+ * Guidelines.
+ *
+ * @param u
+ * @return
+ */
+ public static double C(int u)
+ {
+ return ((u == 0) ? (double) 1 / (double) Math.sqrt((double) 2)
+ : (double) 1);
+ }
+
+ /**
+ * Initialize matrix values for the fast_idct function
+ */
+ private void initMatrix()
+ {
+ for (int j = 0; j < 8; j++)
+ {
+ double nn = (double) (8);
+ c[0][j] = 1.0 / Math.sqrt(nn);
+ cT[j][0] = c[0][j];
+ }
+ for (int i = 1; i < 8; i++)
+ {
+ for (int j = 0; j < 8; j++)
+ {
+ double jj = (double) j;
+ double ii = (double) i;
+ c[i][j] =
+ Math.sqrt(2.0 / 8.0)
+ * Math.cos(((2.0 * jj + 1.0) * ii * Math.PI) / (2.0 * 8.0));
+ cT[j][i] = c[i][j];
+ }
+ }
+ }
+
+ /**
+ * slow_idct - Figure A.3.3 IDCT (informative) on A-5 of the ISO DIS
+ * 10918-1. Requirements and Guidelines. This is a slow IDCT, there are
+ * better algorithms to use, it's fairly expensive with processor speed.
+ *
+ * @param matrix
+ * @return
+ */
+ public static double[][] slow_idct(double[][] matrix)
+ {
+ double[][] output = new double[matrix.length][matrix.length];
+ for (int y = 0; y < 8; y++)
+ {
+ for (int x = 0; x < 8; x++)
+ {
+ double val = 0;
+ for (double v = 0; v < 8; v++)
+ {
+ double innerloop = 0;
+ for (double u = 0; u < 8; u++)
+ innerloop += (DCT.C((int) u) / (double) 2)
+ * matrix[(int) v][(int) u]
+ * Math.cos((2 * x + 1) * u * Math.PI / (double) 16)
+ * Math.cos((2 * y + 1) * v * Math.PI / (double) 16);
+ val += (DCT.C((int) v) / (double) 2) * innerloop;
+ }
+ output[y][x] = (val + 128);
+ }
+ }
+ return (output);
+ }
+
+ public static float[][] slow_fdct(float[][] value)
+ {
+ float[][] buffer = new float[8][8];
+
+ for (int u = 0; u < 8; u++)
+ {
+ for (int v = 0; v < 8; v++)
+ {
+ buffer[u][v] =
+ (float) (1 / 4) * (float) C((int) u) * (float) C((int) v);
+ float innerval = 0;
+ for (int x = 0; x < 8; x++)
+ {
+ for (int y = 0; y < 8; y++)
+ {
+ innerval += value[y][x]
+ * Math.cos(((2 * x + 1) * u * Math.PI) / 16)
+ * Math.cos(((2 * y + 1) * v * Math.PI) / 16);
+ }
+ }
+ buffer[u][v] *= innerval;
+ }
+ }
+ return (buffer);
+ }
+
+ public float[][] fast_fdct(float[][] input)
+ {
+ float output[][] = new float[8][8];
+ double temp[][] = new double[8][8];
+ double temp1;
+ int i;
+ int j;
+ int k;
+
+ for (i = 0; i < 8; i++)
+ {
+ for (j = 0; j < 8; j++)
+ {
+ temp[i][j] = 0.0;
+ for (k = 0; k < 8; k++)
+ {
+ temp[i][j] += (((int) (input[i][k]) - 128) * cT[k][j]);
+ }
+ }
+ }
+
+ for (i = 0; i < 8; i++)
+ {
+ for (j = 0; j < 8; j++)
+ {
+ temp1 = 0.0;
+
+ for (k = 0; k < 8; k++)
+ {
+ temp1 += (c[i][k] * temp[k][j]);
+ }
+
+ output[i][j] = (int) Math.round(temp1) * 8;
+ }
+ }
+
+ return output;
+ }
+
+ /**
+ * fast_idct - Figure A.3.3 IDCT (informative) on A-5 of the ISO DIS
+ * 10918-1. Requires and Guidelines. This is a fast IDCT, it much more
+ * effecient and only inaccurate at about 1/1000th of a percent of values
+ * analyzed. Cannot be static because initMatrix must run before any
+ * fast_idct values can be computed.
+ *
+ * @param input
+ * @return
+ */
+ public double[][] fast_idct(double[][] input)
+ {
+ double output[][] = new double[8][8];
+ double temp[][] = new double[8][8];
+ double temp1;
+ int i, j, k;
+ for (i = 0; i < 8; i++)
+ {
+ for (j = 0; j < 8; j++)
+ {
+ temp[i][j] = 0.0;
+ for (k = 0; k < 8; k++)
+ {
+ temp[i][j] += input[i][k] * c[k][j];
+ }
+ }
+ }
+ for (i = 0; i < 8; i++)
+ {
+ for (j = 0; j < 8; j++)
+ {
+ temp1 = 0.0;
+ for (k = 0; k < 8; k++)
+ temp1 += cT[i][k] * temp[k][j];
+ temp1 += 128.0;
+ if (temp1 < 0)
+ output[i][j] = 0;
+ else if (temp1 > 255)
+ output[i][j] = 255;
+ else
+ output[i][j] = (int) Math.round(temp1);
+ }
+ }
+ return output;
+ }
+
+ public double[][] idj_fast_fdct(float input[][])
+ {
+ double output[][] = new double[8][8];
+ double tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
+ double tmp10, tmp11, tmp12, tmp13;
+ double z1, z2, z3, z4, z5, z11, z13;
+ int i;
+ int j;
+
+ // Subtracts 128 from the input values
+ for (i = 0; i < 8; i++)
+ {
+ for (j = 0; j < 8; j++)
+ {
+ output[i][j] = ((double) input[i][j] - (double) 128.0);
+ // input[i][j] -= 128;
+
+ }
+ }
+
+ for (i = 0; i < 8; i++)
+ {
+ tmp0 = output[i][0] + output[i][7];
+ tmp7 = output[i][0] - output[i][7];
+ tmp1 = output[i][1] + output[i][6];
+ tmp6 = output[i][1] - output[i][6];
+ tmp2 = output[i][2] + output[i][5];
+ tmp5 = output[i][2] - output[i][5];
+ tmp3 = output[i][3] + output[i][4];
+ tmp4 = output[i][3] - output[i][4];
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ output[i][0] = tmp10 + tmp11;
+ output[i][4] = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * (double) 0.707106781;
+ output[i][2] = tmp13 + z1;
+ output[i][6] = tmp13 - z1;
+
+ tmp10 = tmp4 + tmp5;
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ z5 = (tmp10 - tmp12) * (double) 0.382683433;
+ z2 = ((double) 0.541196100) * tmp10 + z5;
+ z4 = ((double) 1.306562965) * tmp12 + z5;
+ z3 = tmp11 * ((double) 0.707106781);
+
+ z11 = tmp7 + z3;
+ z13 = tmp7 - z3;
+
+ output[i][5] = z13 + z2;
+ output[i][3] = z13 - z2;
+ output[i][1] = z11 + z4;
+ output[i][7] = z11 - z4;
+ }
+
+ for (i = 0; i < 8; i++)
+ {
+ tmp0 = output[0][i] + output[7][i];
+ tmp7 = output[0][i] - output[7][i];
+ tmp1 = output[1][i] + output[6][i];
+ tmp6 = output[1][i] - output[6][i];
+ tmp2 = output[2][i] + output[5][i];
+ tmp5 = output[2][i] - output[5][i];
+ tmp3 = output[3][i] + output[4][i];
+ tmp4 = output[3][i] - output[4][i];
+
+ tmp10 = tmp0 + tmp3;
+ tmp13 = tmp0 - tmp3;
+ tmp11 = tmp1 + tmp2;
+ tmp12 = tmp1 - tmp2;
+
+ output[0][i] = tmp10 + tmp11;
+ output[4][i] = tmp10 - tmp11;
+
+ z1 = (tmp12 + tmp13) * (double) 0.707106781;
+ output[2][i] = tmp13 + z1;
+ output[6][i] = tmp13 - z1;
+
+ tmp10 = tmp4 + tmp5;
+ tmp11 = tmp5 + tmp6;
+ tmp12 = tmp6 + tmp7;
+
+ z5 = (tmp10 - tmp12) * (double) 0.382683433;
+ z2 = ((double) 0.541196100) * tmp10 + z5;
+ z4 = ((double) 1.306562965) * tmp12 + z5;
+ z3 = tmp11 * ((double) 0.707106781);
+
+ z11 = tmp7 + z3;
+ z13 = tmp7 - z3;
+
+ output[5][i] = z13 + z2;
+ output[3][i] = z13 - z2;
+ output[1][i] = z11 + z4;
+ output[7][i] = z11 - z4;
+ }
+
+ return output;
+ }
+
+}
diff --git a/libjava/classpath/gnu/javax/imageio/jpeg/HuffmanTable.java b/libjava/classpath/gnu/javax/imageio/jpeg/HuffmanTable.java
new file mode 100644
index 0000000..78f3c1c
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/jpeg/HuffmanTable.java
@@ -0,0 +1,207 @@
+/* HuffmanTable.java --
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.jpeg;
+
+import java.io.IOException;
+
+import javax.imageio.plugins.jpeg.JPEGHuffmanTable;
+
+
+/**
+ * This Object construct a JPEGHuffmanTable which can be used to encode/decode
+ * a scan from a JPEG codec stream. The table must be initalized with either a
+ * BITS byte amount and a Huffman Table Value for decoding or a Huffman Size
+ * and Huffman Code table for encoding.
+ */
+public class HuffmanTable
+{
+ public final static int HUFFMAN_MAX_TABLES = 4;
+
+ private short[] huffcode = new short[256];
+ private short[] huffsize = new short[256];
+ private short[] EHUFCO;
+ private short[] EHUFSI;
+ private short[] valptr = new short[16];
+ private short[] mincode = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1,-1,-1};
+ private short[] maxcode = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1};
+ private short[] huffval;
+ private short[] bits;
+
+ static byte JPEG_DC_TABLE = 0;
+ static byte JPEG_AC_TABLE = 1;
+
+ private short lastk = 0;
+
+ public HuffmanTable(JPEGHuffmanTable table)
+ {
+ huffcode = table.getValues();
+ bits = table.getLengths();
+ }
+
+ /**
+ * Generated from FIGURE C.1 - Generation of table of Huffman code sizes on
+ * ISO DIS 10918-1. Requirements and Guidelines
+ */
+ private void generateSizeTable()
+ {
+ short index=0;
+ for(short i=0; i < bits.length ; i++)
+ {
+ for(short j=0; j < bits[i] ; j++)
+ {
+ huffsize[index] = (short) (i+1);
+ index++;
+ }
+ }
+ lastk = index;
+ }
+
+ /**
+ * Generated from FIGURE C.2 - Generation of table of Huffman codes on
+ * ISO DIS 10918-1. Requirements and Guidelines
+ */
+ private void generateCodeTable()
+ {
+ short k=0;
+ short si = huffsize[0];
+ short code = 0;
+ for(short i=0; i < huffsize.length ; i++)
+ {
+ while(huffsize[k]==si)
+ {
+ huffcode[k] = code;
+ code++;
+ k++;
+ }
+ code <<= 1;
+ si++;
+ }
+ }
+
+ /**
+ * Generated from FIGURE F.15 - Generation of decode table generation on
+ * ISO DIS 10918-1. Requirements and Guidelines
+ */
+ private void generateDecoderTables()
+ {
+ short bitcount = 0;
+ for(int i=0; i < 16 ; i++)
+ {
+ if(bits[i]!=0)
+ valptr[i] = bitcount;
+ for(int j=0 ; j < bits[i] ; j++)
+ {
+ if(huffcode[j+bitcount] < mincode[i] || mincode[i] == -1)
+ mincode[i] = huffcode[j+bitcount];
+
+ if(huffcode[j+bitcount] > maxcode[i])
+ maxcode[i] = huffcode[j+bitcount];
+ }
+ if(mincode[i]!=-1)
+ valptr[i] = (short) (valptr[i] - mincode[i]);
+ bitcount += bits[i];
+ }
+ }
+
+ /**
+ * Generated from FIGURE C.3 - Generation of Order Codes and tables EHUFCO
+ * and EHUFSI from the ISO DIS 10918-1. Requirements and Guidelines
+ */
+ public void orderCodes(boolean isDC)
+ {
+ EHUFCO = new short[isDC ? 15 : 255];
+ EHUFSI = new short[isDC ? 15 : 255];
+
+ for (int p=0; p < lastk ; p++)
+ {
+ int i = huffval[p];
+ if(i < 0 || i > EHUFCO.length || EHUFSI[i]!=0)
+ System.err.println("Error, bad huffman table.");
+ EHUFCO[i] = huffcode[p];
+ EHUFSI[i] = huffsize[p];
+ }
+ }
+
+ /**
+ * Generated from FIGURE F.12 - Extending the sign bit of a decoded value in on
+ * ISO DIS 10918-1. Requirements and Guidelines
+ *
+ * @param diff TODO
+ * @param t TODO
+ * @return TODO
+ */
+ public static int extend(int diff, int t)
+ {
+ int Vt = (int)Math.pow(2,(t-1));
+ if(diff This is used exclusively in the JPEG DCT encoding.
- * 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,
- *
- * Once compiled, a regular expression object is reusable as well as
- * threadsafe: multiple threads can use the RE instance simultaneously
- * to match against different input text.
- *
- * Various methods attempt to match input text against a compiled
- * regular expression. These methods are:
- *
- *
- * These methods all have similar argument lists. The input can be a
- * CharIndexed, String, a character array, a StringBuffer, or an
- * InputStream of some sort. Note that when using an
- * 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.
- *
- * Although the input object can be of various types, it is recommended
- * that it should be a CharIndexed because {@link CharIndexed#getLastMatch()}
- * can show the last match found on this input, which helps the expression
- * \G work as the end of the previous match.
- *
- *
- *
- * 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 an InputStream, this means an
- * offset from the current read position, so subsequent calls with the
- * same index argument on 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.
- *
- *
- * You can optionally affect the execution environment by using a
- * combination of execution flags (constants listed below).
- *
- *
- * All operations on a regular expression are performed in a
- * thread-safe manner.
- *
- * @author Wes Biggs
- * @version 1.1.5-dev, to be released
- */
-
-public class RE extends REToken {
-
- private static final class IntPair implements Serializable {
- public int first, second;
- }
-
- private static final class CharUnit implements Serializable {
- public char ch;
- public boolean bk;
- }
-
- // This String will be returned by getVersion()
- private static final String VERSION = "1.1.5-dev";
-
- // The localized strings are kept in a separate file
- 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;
- private int maximumLength;
-
- /**
- * Compilation flag. Do not differentiate case. Subsequent
- * searches using this RE will be case insensitive.
- */
- public static final int REG_ICASE = 0x02;
-
- /**
- * 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 = 0x04;
-
- /**
- * 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 = 0x08;
-
- /**
- * 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.
- *
- * This example demonstrates the results of various ways of matching on
- * a substring.
- *
- *
- * // Results:
- *
- *
- * can be viewed (given that myMatch is not null) by creating
- *
- *
- * But you can save yourself that work, since the
- *
- * 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
- *
- *
- * The enumerated type is especially useful when searching on a Reader
- * or InputStream, because the InputStream read position cannot be
- * guaranteed after calling
- * 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 Wes Biggs
- * @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());
- }
- }
-}
-
-
diff --git a/libjava/classpath/gnu/xml/dom/DomIterator.java b/libjava/classpath/gnu/xml/dom/DomIterator.java
index 472c6e8..31f9982 100644
--- a/libjava/classpath/gnu/xml/dom/DomIterator.java
+++ b/libjava/classpath/gnu/xml/dom/DomIterator.java
@@ -1,5 +1,5 @@
/* DomIterator.java --
- Copyright (C) 1999,2000,2001 Free Software Foundation, Inc.
+ Copyright (C) 1999, 2000, 2001, 2006 Free Software Foundation, Inc.
This file is part of GNU Classpath.
@@ -253,7 +253,13 @@ public final class DomIterator
{
return here.getFirstChild();
}
-
+
+ // There's no way up or sideways from the root, so if we
+ // couldn't move down to a child, there's nowhere to go.
+ //
+ if (here == root)
+ return null;
+
//
// Siblings ... if forward, we visit them, if backwards
// we visit their children first.
@@ -297,7 +303,9 @@ public final class DomIterator
{
next = next.getParentNode();
}
- if (next == root)
+
+ // If we have exceeded the root node then stop traversing.
+ if (next == root.getParentNode())
{
return null;
}
diff --git a/libjava/classpath/gnu/xml/stream/SAXParser.java b/libjava/classpath/gnu/xml/stream/SAXParser.java
index fd768a4..e58d5fb 100644
--- a/libjava/classpath/gnu/xml/stream/SAXParser.java
+++ b/libjava/classpath/gnu/xml/stream/SAXParser.java
@@ -976,10 +976,56 @@ public class SAXParser
public static void main(String[] args)
throws Exception
{
- SAXParser parser = new SAXParser();
- InputSource input = new InputSource(args[0]);
- parser.parse(input, new org.xml.sax.helpers.DefaultHandler());
-
+ boolean validating = false;
+ boolean namespaceAware = false;
+ boolean xIncludeAware = false;
+ boolean expectCallbackClass = false;
+ String callbackClass = null;
+ int pos = 0;
+ while (pos < args.length && (args[pos].startsWith("-") || expectCallbackClass))
+ {
+ if ("-x".equals(args[pos]))
+ xIncludeAware = true;
+ else if ("-v".equals(args[pos]))
+ validating = true;
+ else if ("-n".equals(args[pos]))
+ namespaceAware = true;
+ else if ("-c".equals(args[pos]))
+ expectCallbackClass = true;
+ else if (expectCallbackClass)
+ {
+ callbackClass = args[pos];
+ expectCallbackClass = false;
+ }
+ pos++;
+ }
+ if (pos >= args.length || expectCallbackClass)
+ {
+ System.out.println("Syntax: SAXParser [-n] [-v] [-x] [-c true
if this PNG is indexed-color
+ */
+ public boolean isIndexed()
+ {
+ return (colorType == INDEXED);
+ }
+
+ /**
+ * Returns true
if this PNG is grayscale
+ */
+ public boolean isGrayscale()
+ {
+ return ((colorType == GRAYSCALE) || (colorType == GRAYSCALE_WITH_ALPHA));
+ }
+
+ /**
+ * Returns the color type of the image.
+ */
+ public int getColorType()
+ {
+ return colorType;
+ }
+
+ /**
+ * Returns whether the image is interlaced or not.
+ */
+ public boolean isInterlaced()
+ {
+ return (interlace != 0);
+ }
+
+ /**
+ * Returns the number of bytes per pixel.
+ */
+ public int bytesPerPixel()
+ {
+ switch( colorType )
+ {
+ case GRAYSCALE_WITH_ALPHA:
+ return ((depth * 2) >> 3);
+ case RGB:
+ return ((depth * 3) >> 3);
+ case RGB_WITH_ALPHA:
+ return ((depth * 4) >> 3);
+
+ default:
+ case GRAYSCALE:
+ case INDEXED:
+ int i = (depth >> 3);
+ if( i > 0 ) return i;
+ return 1; // if bytes per pixel < 1, return 1 anyway.
+ }
+ }
+
+ /**
+ * Returns the stride of one scanline, in bytes.
+ */
+ public int getScanlineStride()
+ {
+ long nBits = 0; // bits per scanline - scanlines are on byte offsets.
+ switch( colorType )
+ {
+ case GRAYSCALE:
+ nBits = width * depth;
+ break;
+ case RGB:
+ nBits = width * depth * 3;
+ break;
+ case INDEXED:
+ nBits = depth * width;
+ break;
+ case GRAYSCALE_WITH_ALPHA:
+ nBits = depth * width * 2;
+ break;
+ case RGB_WITH_ALPHA:
+ nBits = depth * width * 4;
+ break;
+ }
+ // Round up number of bits to the nearest byte
+ if( (nBits & 0x07) != 0 )
+ nBits += (8 - (nBits & 0x07));
+
+ return (int)(nBits >> 3); // return # of bytes.
+ }
+
+ public int getWidth()
+ {
+ return width;
+ }
+
+ public int getHeight()
+ {
+ return height;
+ }
+
+ public int getDepth()
+ {
+ return depth;
+ }
+
+ /**
+ * Debugging string.
+ */
+ public String toString()
+ {
+ return "Header Chunk. Image width:"+width+" height:"+height+
+ " depth:"+depth+" color type:"+colorType+" compression type:"+
+ compression+" filter type:"+ filter+" interlace:"+interlace;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/png/PNGICCProfile.java b/libjava/classpath/gnu/javax/imageio/png/PNGICCProfile.java
new file mode 100644
index 0000000..d2696e1
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/png/PNGICCProfile.java
@@ -0,0 +1,114 @@
+/* PNGICCProfile.java --
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.png;
+
+import java.awt.color.ICC_Profile;
+import java.awt.color.ICC_ColorSpace;
+import java.awt.color.ColorSpace;
+import java.io.UnsupportedEncodingException;
+import java.io.IOException;
+import java.io.ByteArrayInputStream;
+import java.util.zip.InflaterInputStream;
+import java.util.zip.Deflater;
+
+/**
+ * A PNG iCCP (ICC Profile) chunk.
+ */
+public class PNGICCProfile extends PNGChunk
+{
+ private String name;
+ private ICC_Profile profile;
+ // A generic profile name to use "ICC Profile"
+ private static final byte[] genericName = new byte[]
+ { 0x49, 0x43, 0x43, 0x20, 0x50, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65 };
+
+ protected PNGICCProfile( int type, byte[] data, int crc ) throws PNGException
+ {
+ super( type, data, crc );
+ int i = 0;
+ while( data[i++] != 0 );
+ try
+ {
+ name = new String(data, 0, i, "8859_1");
+ }
+ catch(UnsupportedEncodingException e)
+ {
+ name = ""; // shouldn't really happen.
+ }
+ if( data[i++] != 0 )
+ throw new PNGException("Can't handle nonzero compression types with iCCP chunks.");
+ try
+ {
+ ByteArrayInputStream bos = new ByteArrayInputStream( data, i,
+ data.length - i );
+ profile = ICC_Profile.getInstance( new InflaterInputStream( bos ) );
+ }
+ catch(IOException ioe)
+ {
+ throw new PNGException("Couldn't read iCCP profile chunk.");
+ }
+ System.out.println("Got profile:"+profile);
+ }
+
+ public PNGICCProfile( ICC_Profile profile )
+ {
+ super( TYPE_PROFILE );
+ this.profile = profile;
+ byte[] profData = profile.getData();
+ byte[] outData = new byte[ profData.length * 2 ];
+ Deflater deflater = new Deflater();
+ deflater.setInput( profData );
+ deflater.finish();
+ int n = deflater.deflate( outData );
+ data = new byte[ n + 11 + 2 ];
+ System.arraycopy(genericName, 0, data, 0, 11 );
+ data[11] = data[12] = 0; // null separator and compression type.
+ // Copy compressed data
+ System.arraycopy(outData, 0, data, 13, n );
+ }
+
+ public ColorSpace getColorSpace()
+ {
+ return new ICC_ColorSpace( profile );
+ }
+
+ public String toString()
+ {
+ return "PNG ICC Profile, name: "+name;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/png/PNGImageReader.java b/libjava/classpath/gnu/javax/imageio/png/PNGImageReader.java
new file mode 100644
index 0000000..64aa3fe
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/png/PNGImageReader.java
@@ -0,0 +1,224 @@
+/* PNGImageReader.java -- The ImageIO ImageReader for PNG
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.imageio.png;
+
+import gnu.javax.imageio.IIOInputStream;
+
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import javax.imageio.ImageReadParam;
+import javax.imageio.ImageReader;
+import javax.imageio.ImageTypeSpecifier;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.stream.ImageInputStream;
+
+/**
+ * The ImageIO ImageReader for PNG images.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class PNGImageReader
+ extends ImageReader
+{
+
+ /**
+ * The PNG file.
+ */
+ private PNGFile pngFile;
+
+ /**
+ * The decoded image.
+ */
+ private BufferedImage image;
+
+ /**
+ * The supported image types for PNG.
+ */
+ private ArrayList imageTypes;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param spi the corresponding ImageReaderSpi
+ */
+ public PNGImageReader(PNGImageReaderSpi spi)
+ {
+ super(spi);
+ }
+
+ /**
+ * Returns the height of the image.
+ */
+ public int getHeight(int imageIndex)
+ throws IOException
+ {
+ checkIndex(imageIndex);
+ readImage();
+ return image.getHeight();
+ }
+
+ /**
+ * Returns the width of the image.
+ *
+ * @param imageIndex the index of the image
+ *
+ * @return the width of the image
+ */
+ public int getWidth(int imageIndex) throws IOException
+ {
+ checkIndex(imageIndex);
+ readImage();
+ return image.getWidth();
+ }
+
+ /**
+ * Returns the image types for the image.
+ *
+ * @see ImageReader#getImageTypes(int)
+ */
+ public Iterator getImageTypes(int imageIndex)
+ throws IOException
+ {
+ checkIndex(imageIndex);
+ readImage();
+ if (imageTypes == null)
+ {
+ imageTypes = new ArrayList();
+ imageTypes.add(new ImageTypeSpecifier(image.getColorModel(),
+ image.getSampleModel()));
+ }
+ return imageTypes.iterator();
+ }
+
+ /**
+ * Returns the number of images in the stream.
+ *
+ * @return the number of images in the stream
+ *
+ * @see ImageReader#getNumImages(boolean)
+ */
+ public int getNumImages(boolean allowSearch)
+ throws IOException
+ {
+ return 1;
+ }
+
+ /**
+ * Reads the image.
+ *
+ * @param imageIndex the index of the image to read
+ * @param param additional parameters
+ */
+ public BufferedImage read(int imageIndex, ImageReadParam param)
+ throws IOException
+ {
+ checkIndex(imageIndex);
+ readImage();
+ return image;
+ }
+
+ /**
+ * Sets the input and checks the input parameter.
+ *
+ * @see ImageReader#setInput(Object, boolean, boolean)
+ */
+ public void setInput(Object input,
+ boolean seekForwardOnly,
+ boolean ignoreMetadata)
+ {
+ super.setInput(input, seekForwardOnly, ignoreMetadata);
+ if (! (input instanceof InputStream || input instanceof ImageInputStream))
+ throw new IllegalArgumentException("Input not an ImageInputStream");
+ }
+
+ public IIOMetadata getImageMetadata(int imageIndex)
+ throws IOException
+ {
+ // TODO: Not (yet) supported.
+ checkIndex(imageIndex);
+ return null;
+ }
+
+ public IIOMetadata getStreamMetadata()
+ throws IOException
+ {
+ // TODO: Not (yet) supported.
+ return null;
+ }
+
+ /**
+ * Checks the image indexa and throws and IndexOutOfBoundsException if
+ * appropriate.
+ *
+ * @param index the index to check
+ */
+ private void checkIndex(int index)
+ {
+ if (index > 0)
+ throw new IndexOutOfBoundsException("Image index out of bounds");
+ }
+
+ /**
+ * Makes sure that the image is read.
+ *
+ * @throws IOException if something goes wrong
+ */
+ private void readImage()
+ throws IOException
+ {
+ if (pngFile == null)
+ {
+ if (input instanceof InputStream)
+ pngFile = new PNGFile((InputStream) input);
+ else if (input instanceof ImageInputStream)
+ pngFile = new PNGFile(new IIOInputStream((ImageInputStream) input));
+ else
+ assert false : "Must not happen";
+ }
+
+ if (pngFile != null && image == null)
+ {
+ image = pngFile.getBufferedImage();
+ }
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/png/PNGImageReaderSpi.java b/libjava/classpath/gnu/javax/imageio/png/PNGImageReaderSpi.java
new file mode 100644
index 0000000..0092ab5
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/png/PNGImageReaderSpi.java
@@ -0,0 +1,128 @@
+/* PNGImageReaderSpi.java -- The ImageReader service provider for PNG
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.imageio.png;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Locale;
+
+import javax.imageio.ImageReader;
+import javax.imageio.spi.ImageReaderSpi;
+import javax.imageio.stream.ImageInputStream;
+
+/**
+ * The ImageIO ImageReader service provider for PNG images.
+ *
+ * @author Roman Kennke (kennke@aicas.com)
+ */
+public class PNGImageReaderSpi
+ extends ImageReaderSpi
+{
+
+ /**
+ * The PNG file signature.
+ */
+ private static final byte[] SIGNATURE = new byte[]
+ { (byte) 137, 80, 78, 71, 13, 10, 26, 10 };
+
+ private static final String VENDOR_NAME = "GNU";
+ static final String VERSION = "1.0";
+ static final String READER_CLASSNAME =
+ "gnu.javax.imageio.png.PNGImageReader";
+ static final String[] NAMES = { "Portable Network Graphics" };
+ static final String[] SUFFIXES = { ".png" , ".PNG" };
+ static final String[] MIME_TYPES = { "image/png" };
+ static final String[] WRITER_SPI_NAMES =
+ new String[] { "gnu.javax.imageio.png.PNGWriterSpi" };
+ static final Class[] INPUT_TYPES = new Class[]{ InputStream.class,
+ ImageInputStream.class};
+ public PNGImageReaderSpi()
+ {
+ super(VENDOR_NAME, VERSION, NAMES, SUFFIXES, MIME_TYPES, READER_CLASSNAME,
+ INPUT_TYPES, WRITER_SPI_NAMES, false, null, null, null, null, false,
+ null, null, null, null);
+ }
+
+ /**
+ * Determines if the PNG ImageReader can decode the specified input.
+ *
+ * @param source the source to decode
+ */
+ public boolean canDecodeInput(Object source) throws IOException
+ {
+ boolean canDecode = false;
+ if (source instanceof ImageInputStream)
+ {
+ ImageInputStream in = (ImageInputStream) source;
+ in.mark();
+ canDecode = true;
+ for (int i = 0; i < SIGNATURE.length && canDecode; i++)
+ {
+ byte sig = (byte) in.read();
+ if (sig != SIGNATURE[i]) {
+ canDecode = false;
+ }
+ }
+ in.reset();
+ }
+ return canDecode;
+ }
+
+ /**
+ * Returns a new PNGImageReader instance.
+ *
+ * @param extension the extension, ignored
+ */
+ public ImageReader createReaderInstance(Object extension)
+ throws IOException
+ {
+ return new PNGImageReader(this);
+ }
+
+ /**
+ * Returns a description.
+ *
+ * @param locale the locale
+ */
+ public String getDescription(Locale locale)
+ {
+ return "Portable Network Graphics";
+ }
+
+}
diff --git a/libjava/classpath/gnu/javax/imageio/png/PNGPalette.java b/libjava/classpath/gnu/javax/imageio/png/PNGPalette.java
new file mode 100644
index 0000000..478129d
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/png/PNGPalette.java
@@ -0,0 +1,127 @@
+/* PNGPalette.java --
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.png;
+
+import java.awt.color.ColorSpace;
+import java.awt.image.IndexColorModel;
+
+/**
+ * A PNG Palette chunk.
+ */
+public class PNGPalette extends PNGChunk
+{
+ private int[] red,green,blue;
+
+ protected PNGPalette( int type, byte[] data, int crc ) throws PNGException
+ {
+ super( type, data, crc );
+ double l = data.length;
+ l /= 3.0;
+ // Check if it's divisible by 3. (Yuck.)
+ if( l - Math.floor(l) != 0.0 )
+ throw new PNGException("Invalid size of palette chunk.");
+ int nEntries = (int)l;
+
+ red = new int[ nEntries ];
+ green = new int[ nEntries ];
+ blue = new int[ nEntries ];
+ for( int i = 0; i < nEntries; i++ )
+ {
+ red[i] = (data[ i * 3 ] & 0xFF);
+ green[i] = (data[ i * 3 + 1 ] & 0xFF);
+ blue[i] = (data[ i * 3 + 2] & 0xFF);
+ }
+ }
+
+ public PNGPalette( IndexColorModel cm )
+ {
+ super( TYPE_PALETTE );
+ int n = cm.getMapSize();
+ data = new byte[ n * 3 ];
+ red = new int[ n ];
+ green = new int[ n ];
+ blue = new int[ n ];
+ for(int i = 0; i < n; i++ )
+ {
+ red[i] = data[i * 3] = (byte)cm.getRed(i);
+ green[i] = data[i * 3 + 1] = (byte)cm.getGreen(i);
+ blue[i] = data[i * 3 + 2] = (byte)cm.getBlue(i);
+ }
+ }
+
+ public IndexColorModel getPalette( ColorSpace cs )
+ {
+ int nc = red.length;
+ byte[] r = new byte[nc];
+ byte[] g = new byte[nc];
+ byte[] b = new byte[nc];
+
+ if( cs == null )
+ {
+ for(int i = 0; i < nc; i ++ )
+ {
+ r[i] = (byte)red[i];
+ g[i] = (byte)green[i];
+ b[i] = (byte)blue[i];
+ }
+ }
+ else
+ {
+ for(int i = 0; i < nc; i ++ )
+ {
+ float[] in = new float[3];
+ in[0] = (((float)red[i]) / 255f);
+ in[1] = (((float)green[i]) / 255f);
+ in[2] = (((float)blue[i]) / 255f);
+ float[] out = cs.toRGB( in );
+ r[i] = (byte)( Math.round(out[0] * 255.0) );
+ g[i] = (byte)( Math.round(out[1] * 255.0) );
+ b[i] = (byte)( Math.round(out[2] * 255.0) );
+ }
+ }
+ return new IndexColorModel(8, nc, r, g, b);
+ }
+
+ public String toString()
+ {
+ String s = "PNG Palette:\n";
+ for( int i = 0; i < red.length; i++)
+ s = s + "Index " + i + ": ["+ red[i] +", "+green[i]+", "+blue[i]+"]\n";
+ return s;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/png/PNGPhys.java b/libjava/classpath/gnu/javax/imageio/png/PNGPhys.java
new file mode 100644
index 0000000..0a82d6a
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/png/PNGPhys.java
@@ -0,0 +1,112 @@
+/* PNGPhys.java --
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.png;
+
+/**
+ * A PNG "pHYS" chunk - pixel physical dimensions
+ */
+public class PNGPhys extends PNGChunk
+{
+ long x, y;
+ double ratio;
+ boolean usesRatio;
+
+ protected PNGPhys( int type, byte[] data, int crc ) throws PNGException
+ {
+ super( type, data, crc );
+ if( data.length < 9 )
+ throw new PNGException("Unexpected size of pHYS chunk.");
+ x = ((data[0] & 0xFF) << 24) | ( (data[1] & 0xFF) << 16 ) |
+ ((data[2] & 0xFF) << 8) | (data[3] & 0xFF);
+ y = ((data[4] & 0xFF) << 24) | ( (data[5] & 0xFF) << 16 ) |
+ ((data[6] & 0xFF) << 8) | (data[7] & 0xFF);
+ if(data[8] == 0)
+ {
+ ratio = ((double)x)/((double)y);
+ usesRatio = true;
+ }
+ }
+
+ public PNGPhys( double ratio )
+ {
+ super( TYPE_PHYS );
+
+ this.ratio = ratio;
+ usesRatio = true;
+
+ if( ratio < 1.0 )
+ {
+ y = 0xFFFFFFFF;
+ x = (long)(0xFFFFFFFFL * ratio);
+ }
+ else
+ {
+ x = 0xFFFFFFFF;
+ y = (long)(0xFFFFFFFFL * ratio);
+ }
+ makeData();
+ }
+
+ public PNGPhys( int x, int y )
+ {
+ super( TYPE_PHYS );
+ usesRatio = false;
+ this.x = x;
+ this.y = y;
+ makeData();
+ }
+
+ private void makeData()
+ {
+ data = new byte[ 9 ];
+ byte[] a = getInt( (int)x );
+ byte[] b = getInt( (int)y );
+ data[0] = a[0]; data[1] = a[1]; data[2] = a[2]; data[3] = a[3];
+ data[4] = b[0]; data[5] = b[1]; data[6] = b[2]; data[7] = b[3];
+ data[7] = (usesRatio) ? 0 : (byte)0xFF;
+ }
+
+ public String toString()
+ {
+ String s = "PNG Physical pixel size chunk.";
+ if( usesRatio )
+ return s + " Aspect ratio (x/y): " + ratio;
+ else
+ return s + " " + x + " by " + y + " pixels per meter. (x, y).";
+ }
+}
diff --git a/libjava/classpath/gnu/javax/imageio/png/PNGTime.java b/libjava/classpath/gnu/javax/imageio/png/PNGTime.java
new file mode 100644
index 0000000..9b5c033
--- /dev/null
+++ b/libjava/classpath/gnu/javax/imageio/png/PNGTime.java
@@ -0,0 +1,83 @@
+/* PNGTime.java --
+ Copyright (C) 2006 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.imageio.png;
+
+import java.util.Date;
+
+/**
+ * A PNG tIME chunk.
+ */
+public class PNGTime extends PNGChunk
+{
+ private Date date;
+
+ protected PNGTime( int type, byte[] data, int crc ) throws PNGException
+ {
+ super( type, data, crc );
+ if( data.length < 7 )
+ throw new PNGException("Unexpectedly short time chunk. ("+data.length+" bytes)");
+
+ // PNG value is absolute (2006, not 106 or 06), java is from 1900.
+ int year = ( (data[0] & 0xFF) << 8 ) | (data[1] & 0xFF);
+ int month = (data[2] & 0xFF); // java counts from 0. PNG from 1.
+ int day = (data[3] & 0xFF);
+ int hour = (data[4] & 0xFF);
+ int minute = (data[5] & 0xFF);
+ int second = (data[6] & 0xFF);
+ date = new Date( year - 1900, month - 1, day, hour, minute, second );
+ }
+
+ public PNGTime( Date d )
+ {
+ super( TYPE_TIME );
+ data = new byte[ 7 ];
+ int tmp = d.getYear() + 1900;
+ data[0] = (byte)((tmp & 0xFF00) >> 8);
+ data[1] = (byte)(tmp & 0x00FF);
+ data[2] = (byte)(d.getMonth() + 1);
+ data[3] = (byte)(d.getDay());
+ data[4] = (byte)(d.getHours());
+ data[5] = (byte)(d.getMinutes());
+ data[6] = (byte)(d.getSeconds());
+ }
+
+ public String toString()
+ {
+ return "PNG Time chunk: "+date;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/net/ssl/provider/KeyPool.java b/libjava/classpath/gnu/javax/net/ssl/provider/KeyPool.java
index e342700..18d9dc2 100644
--- a/libjava/classpath/gnu/javax/net/ssl/provider/KeyPool.java
+++ b/libjava/classpath/gnu/javax/net/ssl/provider/KeyPool.java
@@ -41,15 +41,6 @@ package gnu.javax.net.ssl.provider;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.SecureRandom;
-import java.security.Security;
-import java.util.LinkedList;
-import javax.crypto.spec.DHParameterSpec;
-
-import gnu.java.security.hash.HashFactory;
-import gnu.java.security.hash.IMessageDigest;
-import gnu.java.security.prng.IRandom;
-import gnu.java.security.prng.LimitReachedException;
-import gnu.java.security.util.Prime2;
final class KeyPool
{
@@ -92,7 +83,7 @@ final class KeyPool
nextBytes(kb);
p = new BigInteger(1, kb).setBit(0);
if (p.compareTo(lower) >= 0 && p.compareTo(upper) <= 0 &&
- Prime2.isProbablePrime(p) && p.gcd(E).equals(ONE))
+ p.isProbablePrime(80) && p.gcd(E).equals(ONE))
break;
}
@@ -101,7 +92,7 @@ final class KeyPool
nextBytes(kb);
q = new BigInteger(1, kb).setBit(0);
n = q.multiply(p);
- if (n.bitLength() == 512 && Prime2.isProbablePrime(q) &&
+ if (n.bitLength() == 512 && q.isProbablePrime(80) &&
q.gcd(E).equals(ONE))
break;
}
diff --git a/libjava/classpath/gnu/javax/print/CupsServer.java b/libjava/classpath/gnu/javax/print/CupsServer.java
index 6d9601f..0486e69 100644
--- a/libjava/classpath/gnu/javax/print/CupsServer.java
+++ b/libjava/classpath/gnu/javax/print/CupsServer.java
@@ -84,24 +84,43 @@ public class CupsServer
/**
* Creates a CupsServer
object which
- * tries to connect to the cups server on localhost.
+ * tries to connect to a cups server.
+ *
+ * If gnu.javax.print.server
is explicitly set, then
+ * that hostname will be used. Otherwise it will default to localhost.
*
* @param username the username
* @param password the password for the username.
*/
public CupsServer(String username, String password)
{
+ this.username = username;
+ this.password = password;
+
+ this.uri = null;
+ try
+ {
+ String serv = System.getProperty("gnu.javax.print.server");
+ if( serv != null )
+ this.uri = new URI("http://"+serv+":631");
+ }
+ catch(URISyntaxException use)
+ {
+ throw new RuntimeException("gnu.javax.print.CupsServer value is not a valid hostname.");
+ }
+ catch(SecurityException se)
+ {
+ }
+
try
{
- this.uri = new URI("http://localhost:631");
+ if( this.uri == null )
+ this.uri = new URI("http://localhost:631");
}
catch (URISyntaxException e)
{
// does not happen
}
-
- this.username = username;
- this.password = password;
}
/**
@@ -193,7 +212,7 @@ public class CupsServer
Map printerAttributes = (Map) prAttr.get(i);
Set uris = (Set) printerAttributes.get(PrinterUriSupported.class);
PrinterUriSupported uri = (PrinterUriSupported) uris.toArray()[0];
-
+
try
{
CupsPrintService cups = new CupsPrintService(uri.getURI(),
diff --git a/libjava/classpath/gnu/javax/print/ipp/IppRequest.java b/libjava/classpath/gnu/javax/print/ipp/IppRequest.java
index 8abab51..05a6faa 100644
--- a/libjava/classpath/gnu/javax/print/ipp/IppRequest.java
+++ b/libjava/classpath/gnu/javax/print/ipp/IppRequest.java
@@ -119,6 +119,11 @@ public class IppRequest
{
/**
+ * The printer-poll timeout.
+ */
+ private static final int timeout = 1000;
+
+ /**
* Helper class used to write the attributes of a request
* into the supplied data output stream in the correct way.
*
@@ -789,7 +794,7 @@ public class IppRequest
alreadySent = true;
- OutputStream stream = stream = connection.getOutputStream();
+ OutputStream stream = connection.getOutputStream();
DataOutputStream out = new DataOutputStream(stream);
// the header 8 bytes long
@@ -838,8 +843,13 @@ public class IppRequest
out.flush();
stream.flush();
-
- int responseCode = responseCode = connection.getResponseCode();
+
+ // Set the connection timeout, for if the printer is offline.
+ // FIXME: The print services polling should probably be done in its
+ // own thread.
+ connection.setConnectTimeout( timeout );
+
+ int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
{
diff --git a/libjava/classpath/gnu/javax/security/auth/callback/ConsoleCallbackHandler.java b/libjava/classpath/gnu/javax/security/auth/callback/ConsoleCallbackHandler.java
index 052b6c4..d4bd9ed 100644
--- a/libjava/classpath/gnu/javax/security/auth/callback/ConsoleCallbackHandler.java
+++ b/libjava/classpath/gnu/javax/security/auth/callback/ConsoleCallbackHandler.java
@@ -137,7 +137,7 @@ public class ConsoleCallbackHandler extends AbstractCallbackHandler
{
if (choices[i].equals(replies[j]))
{
- indices.add(new Integer(i));
+ indices.add(Integer.valueOf(i));
}
}
if (indices.size() == 0)
diff --git a/libjava/classpath/gnu/javax/security/auth/login/ConfigFileParser.java b/libjava/classpath/gnu/javax/security/auth/login/ConfigFileParser.java
index f6c39bb..b5b5069 100644
--- a/libjava/classpath/gnu/javax/security/auth/login/ConfigFileParser.java
+++ b/libjava/classpath/gnu/javax/security/auth/login/ConfigFileParser.java
@@ -38,12 +38,15 @@ exception statement from your version. */
package gnu.javax.security.auth.login;
+import gnu.java.security.Configuration;
+
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.logging.Logger;
import javax.security.auth.login.AppConfigurationEntry;
@@ -88,26 +91,12 @@ import javax.security.auth.login.AppConfigurationEntry;
*/
public final class ConfigFileParser
{
- // Constants and fields
- // --------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
- private static final void debug(String m) {if (DEBUG) System.err.println(m);};
-
+ private static final Logger log = Logger.getLogger(ConfigFileParser.class.getName());
private ConfigFileTokenizer cft;
private Map map = new HashMap();
- // Constructor(s)
- // --------------------------------------------------------------------------
-
// default 0-arguments constructor
- // Class methods
- // --------------------------------------------------------------------------
-
- // Instance methods
- // --------------------------------------------------------------------------
-
/**
* Returns the parse result as a {@link Map} where the keys are application
* names, and the entries are {@link List}s of {@link AppConfigurationEntry}
@@ -161,7 +150,8 @@ public final class ConfigFileParser
}
String appName = cft.sval;
- debug("DEBUG: APP_NAME_OR_OTHER = " + appName);
+ if (Configuration.DEBUG)
+ log.fine("APP_NAME_OR_OTHER = " + appName);
if (cft.nextToken() != '{')
abort("Missing '{' after APP_NAME_OR_OTHER");
@@ -202,13 +192,15 @@ public final class ConfigFileParser
}
String clazz = validateClassName(cft.sval);
- debug("DEBUG: MODULE_CLASS = " + clazz);
+ if (Configuration.DEBUG)
+ log.fine("MODULE_CLASS = " + clazz);
if (cft.nextToken() != ConfigFileTokenizer.TT_WORD)
abort("Was expecting FLAG but found none");
String flag = cft.sval;
- debug("DEBUG: FLAG = " + flag);
+ if (Configuration.DEBUG)
+ log.fine("DEBUG: FLAG = " + flag);
AppConfigurationEntry.LoginModuleControlFlag f = null;
if (flag.equalsIgnoreCase("required"))
f = AppConfigurationEntry.LoginModuleControlFlag.REQUIRED;
@@ -230,32 +222,39 @@ public final class ConfigFileParser
abort("Was expecting PARAM_NAME but got '" + ((char) c) + "'");
paramName = cft.sval;
- debug("DEBUG: PARAM_NAME = " + paramName);
+ if (Configuration.DEBUG)
+ log.fine("PARAM_NAME = " + paramName);
if (cft.nextToken() != '=')
abort("Missing '=' after PARAM_NAME");
c = cft.nextToken();
if (c != '"' && c != '\'')
- debug(" WARN: Was expecting a quoted string but got no quote " +
- "character. Assume unquoted string");
-
+ {
+ if (Configuration.DEBUG)
+ log.fine("Was expecting a quoted string but got no quote character."
+ + " Assume unquoted string");
+ }
paramValue = expandParamValue(cft.sval);
- debug("DEBUG: PARAM_VALUE = " + paramValue);
+ if (Configuration.DEBUG)
+ log.fine("PARAM_VALUE = " + paramValue);
options.put(paramName, paramValue);
c = cft.nextToken();
}
-
AppConfigurationEntry ace = new AppConfigurationEntry(clazz, f, options);
- debug("DEBUG: LOGIN_MODULE_ENTRY = " + ace);
+ if (Configuration.DEBUG)
+ log.fine("LOGIN_MODULE_ENTRY = " + ace);
listOfACEs.add(ace);
return true;
}
private void abort(String m) throws IOException
{
- debug("ERROR: " + m);
- debug("DEBUG: Map (so far) = " + String.valueOf(map));
+ if (Configuration.DEBUG)
+ {
+ log.fine(m);
+ log.fine("Map (so far) = " + String.valueOf(map));
+ }
throw new IOException(m);
}
@@ -264,12 +263,13 @@ public final class ConfigFileParser
if (cn.startsWith(".") || cn.endsWith("."))
abort("MODULE_CLASS MUST NOT start or end with a '.'");
- String[] tokens = cn.split(".");
+ String[] tokens = cn.split("\\.");
for (int i = 0; i < tokens.length; i++)
{
String t = tokens[i];
- if (Character.isJavaIdentifierStart(cn.toCharArray()[0]))
- abort("");
+ if (! Character.isJavaIdentifierStart(t.charAt(0)))
+ abort("Class name [" + cn
+ + "] contains an invalid sub-package identifier: " + t);
// we dont check the rest of the characters for isJavaIdentifierPart()
// because that's what the tokenizer does.
@@ -311,14 +311,17 @@ public final class ConfigFileParser
int j = s.indexOf("}", i + 2);
if (j == -1)
{
- debug(" WARN: Found a ${ prefix with no } suffix. Ignore");
+ if (Configuration.DEBUG)
+ log.fine("Found a ${ prefix with no } suffix. Ignore");
break;
}
String sysPropName = s.substring(i + 2, j);
- debug("DEBUG: Found a reference to System property " + sysPropName);
+ if (Configuration.DEBUG)
+ log.fine("Found a reference to System property " + sysPropName);
String sysPropValue = System.getProperty(sysPropName);
- debug("DEBUG: Resolved " + sysPropName + " to '" + sysPropValue + "'");
+ if (Configuration.DEBUG)
+ log.fine("Resolved " + sysPropName + " to '" + sysPropValue + "'");
if (sysPropValue != null)
{
result = s.substring(0, i) + sysPropValue + s.substring(j + 1);
@@ -330,7 +333,8 @@ public final class ConfigFileParser
}
catch (Exception x)
{
- debug(" WARN: Exception while expanding " + s + ". Ignore: " + x);
+ if (Configuration.DEBUG)
+ log.fine("Exception (ignored) while expanding " + s + ": " + x);
}
return result;
diff --git a/libjava/classpath/gnu/javax/security/auth/login/ConfigFileTokenizer.java b/libjava/classpath/gnu/javax/security/auth/login/ConfigFileTokenizer.java
index 2cfe916..06a1d2c 100644
--- a/libjava/classpath/gnu/javax/security/auth/login/ConfigFileTokenizer.java
+++ b/libjava/classpath/gnu/javax/security/auth/login/ConfigFileTokenizer.java
@@ -38,14 +38,17 @@ exception statement from your version. */
package gnu.javax.security.auth.login;
+import gnu.java.security.Configuration;
+
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
+import java.util.logging.Logger;
/**
* A UTF-8 friendly, JAAS Login Module Configuration file tokenizer written in
* the deault syntax. This class emulates, to a certain extent, the behavior of
- * a {@link java.io.SrteamTokenizer} instance st
, when set as
+ * a {@link java.io.StreamTokenizer} instance st
, when set as
* follows:
*
*
@@ -76,12 +79,7 @@ import java.io.Reader;
*/
public class ConfigFileTokenizer
{
- // Constants and fields
- // --------------------------------------------------------------------------
-
- private static final boolean DEBUG = false;
- private static final void debug(String m) {if (DEBUG) System.err.println(m);};
-
+ private static final Logger log = Logger.getLogger(ConfigFileParser.class.getName());
/** A constant indicating that the end of the stream has been read. */
public static final int TT_EOF = -1;
/** A constant indicating that a word token has been read. */
@@ -235,9 +233,12 @@ public class ConfigFileTokenizer
private void abort(String m) throws IOException
{
- debug("DEBUG: " + m);
- debug("DEBUG: sb = " + sb);
- debug("DEBUG: sbNdx = " + sbNdx);
+ if (Configuration.DEBUG)
+ {
+ log.fine(m);
+ log.fine("sb = " + sb);
+ log.fine("sbNdx = " + sbNdx);
+ }
throw new IOException(m);
}
}
diff --git a/libjava/classpath/gnu/javax/security/auth/login/GnuConfiguration.java b/libjava/classpath/gnu/javax/security/auth/login/GnuConfiguration.java
index f0b8594..8cd61c9 100644
--- a/libjava/classpath/gnu/javax/security/auth/login/GnuConfiguration.java
+++ b/libjava/classpath/gnu/javax/security/auth/login/GnuConfiguration.java
@@ -50,6 +50,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.logging.Logger;
import javax.security.auth.AuthPermission;
import javax.security.auth.login.AppConfigurationEntry;
@@ -127,12 +128,7 @@ import javax.security.auth.login.Configuration;
*/
public final class GnuConfiguration extends Configuration
{
- // Constants and fields
- // --------------------------------------------------------------------------
-
- private static final boolean DEBUG = true;
- private static final void debug(String m) {if (DEBUG) System.err.println(m);};
-
+ private static final Logger log = Logger.getLogger(GnuConfiguration.class.getName());
/**
* The internal map of login modules keyed by application name. Each entry in
* this map is a {@link List} of {@link AppConfigurationEntry}s for that
@@ -179,7 +175,8 @@ public final class GnuConfiguration extends Configuration
if (loginModules == null || loginModules.size() == 0)
return null;
- debug("DEBUG: " + appName + " -> " + loginModules.size() + " entry(ies)");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine(appName + " -> " + loginModules.size() + " entry(ies)");
return (AppConfigurationEntry[]) loginModules.toArray(new AppConfigurationEntry[0]);
}
@@ -193,7 +190,7 @@ public final class GnuConfiguration extends Configuration
* @throws SecurityException if the caller does not have an
* {@link AuthPermission} for the action named
*
refreshLoginConfiguration
.
- * @see {@link AuthPermission}
+ * @see AuthPermission
*/
public void refresh()
{
@@ -215,13 +212,25 @@ public final class GnuConfiguration extends Configuration
private void init()
{
if (processSecurityProperties())
- debug(" INFO: Using login configuration defined by Security property(ies)");
+ {
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("Using login configuration defined by Security property(ies)");
+ }
else if (processSystemProperty())
- debug(" INFO: Using login configuration defined by System property");
+ {
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("Using login configuration defined by System property");
+ }
else if (processUserHome())
- debug(" INFO: Using login configuration defined in ${user.home}");
+ {
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("Using login configuration defined in ${user.home}");
+ }
else
- debug(" WARN: No login configuration file found");
+ {
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("No login configuration file found");
+ }
}
/**
@@ -249,16 +258,18 @@ public final class GnuConfiguration extends Configuration
s = s.trim();
if (s.length() != 0)
{
- debug("DEBUG: java.security.auth.login.config.url." + counter
- + " = " + s);
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("java.security.auth.login.config.url." + counter
+ + " = " + s);
parseConfig(getInputStreamFromURL(s));
result = true;
}
}
catch (Throwable t)
{
- debug(" WARN: Exception while handling Security property at #"
- + counter + ". Continue: " + t);
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("Exception while handling Security property at #"
+ + counter + ". Continue: " + t);
}
return result;
}
@@ -287,7 +298,8 @@ public final class GnuConfiguration extends Configuration
}
catch (MalformedURLException x)
{
- debug(" WARN: Failed opening as URL: " + s + ". Will try as File");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("Failed opening as URL: " + s + ". Will try as File");
result = new FileInputStream(s);
}
return result;
@@ -311,7 +323,8 @@ public final class GnuConfiguration extends Configuration
s = s.trim();
if (s.length() != 0)
{
- debug("DEBUG: java.security.auth.login.config = " + s);
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("java.security.auth.login.config = " + s);
parseConfig(getInputStreamFromURL(s));
result = true;
}
@@ -319,7 +332,8 @@ public final class GnuConfiguration extends Configuration
}
catch (Throwable t)
{
- debug(" WARN: Exception while handling System property. Continue: " + t);
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("Exception while handling System property. Continue: " + t);
}
return result;
}
@@ -349,8 +363,9 @@ public final class GnuConfiguration extends Configuration
if (jaasFile == null)
{
- debug(" WARN: Login Configuration file, in " + userHome
- + ", does not exist or is inaccessible");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("Login Configuration file, in " + userHome
+ + ", does not exist or is inaccessible");
return result;
}
@@ -360,7 +375,8 @@ public final class GnuConfiguration extends Configuration
}
catch (Throwable t)
{
- debug(" WARN: Exception while handling ${user.home}: " + t);
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("Exception (ignored) while handling ${user.home}: " + t);
}
return result;
}
@@ -397,54 +413,54 @@ public final class GnuConfiguration extends Configuration
String uh = System.getProperty("user.home");
if (uh == null || uh.trim().length() == 0)
{
- debug(" WARN: User home path is not set or is empty");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("User home path is not set or is empty");
return null;
}
-
uh = uh.trim();
File result = new File(uh);
- if (!result.exists())
+ if (! result.exists())
{
- debug(" WARN: User home '" + uh + "' does not exist");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("User home '" + uh + "' does not exist");
return null;
}
-
- if (!result.isDirectory())
+ if (! result.isDirectory())
{
- debug(" WARN: User home '" + uh + "' is not a directory");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("User home '" + uh + "' is not a directory");
return null;
}
-
- if (!result.canRead())
+ if (! result.canRead())
{
- debug(" WARN: User home '" + uh + "' is not readable");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("User home '" + uh + "' is not readable");
return null;
}
-
return result;
}
private File getConfigFromUserHome(File userHome, String fileName)
{
File result = new File(userHome, fileName);
- if (!result.exists())
+ if (! result.exists())
{
- debug(" WARN: File '" + fileName + "' does not exist in user's home");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("File '" + fileName + "' does not exist in user's home");
return null;
}
-
- if (!result.isFile())
+ if (! result.isFile())
{
- debug(" WARN: File '" + fileName + "' in user's home is not a file");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("File '" + fileName + "' in user's home is not a file");
return null;
}
-
- if (!result.canRead())
+ if (! result.canRead())
{
- debug(" WARN: File '" + fileName + "' in user's home is not readable");
+ if (gnu.java.security.Configuration.DEBUG)
+ log.fine("File '" + fileName + "' in user's home is not readable");
return null;
}
-
return result;
}
}
diff --git a/libjava/classpath/gnu/javax/sound/midi/file/ExtendedMidiFileFormat.java b/libjava/classpath/gnu/javax/sound/midi/file/ExtendedMidiFileFormat.java
new file mode 100644
index 0000000..cb5a8e8
--- /dev/null
+++ b/libjava/classpath/gnu/javax/sound/midi/file/ExtendedMidiFileFormat.java
@@ -0,0 +1,77 @@
+/* ExtendedMidiFileFormat.java -- extended with track count info.
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.sound.midi.file;
+
+/**
+ * ExtendedMidiFileFormat is a package private class that simply
+ * adds the number of MIDI tracks for the MidiFileFormat class.
+ *
+ * @author Anthony Green (green@redhat.com)
+ */
+class ExtendedMidiFileFormat
+ extends javax.sound.midi.MidiFileFormat
+{
+ private int ntracks;
+
+ /**
+ * Get the number of tracks for this MIDI file.
+ *
+ * @return the number of tracks for this MIDI file
+ */
+ public int getNumberTracks()
+ {
+ return ntracks;
+ }
+
+ /**
+ * Create an ExtendedMidiFileFormat object from the given parameters.
+ *
+ * @param type the MIDI file type (0, 1, or 2)
+ * @param divisionType the MIDI file division type
+ * @param resolution the MIDI file timing resolution
+ * @param bytes the MIDI file size in bytes
+ * @param microseconds the MIDI file length in microseconds
+ * @param ntracks the number of tracks
+ */
+ public ExtendedMidiFileFormat(int type, float divisionType, int resolution,
+ int bytes, long microseconds, int ntracks)
+ {
+ super(type, divisionType, resolution, bytes, microseconds);
+ this.ntracks = ntracks;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/sound/midi/file/MidiDataInputStream.java b/libjava/classpath/gnu/javax/sound/midi/file/MidiDataInputStream.java
new file mode 100644
index 0000000..010d170
--- /dev/null
+++ b/libjava/classpath/gnu/javax/sound/midi/file/MidiDataInputStream.java
@@ -0,0 +1,83 @@
+/* MidiDataInputStream.java -- adds variable length MIDI ints
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.sound.midi.file;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * MidiDataInputStream is simply a DataInputStream with the addition
+ * of special variable length int reading as defined by the MIDI spec.
+ *
+ * @author Anthony Green (green@redhat.com)
+ */
+public class MidiDataInputStream
+ extends DataInputStream
+{
+ /**
+ * Create a MidiDataInputStream.
+ */
+ public MidiDataInputStream(InputStream is)
+ {
+ super(is);
+ }
+
+ /**
+ * Read an int encoded in the MIDI-style variable length
+ * encoding format.
+ *
+ * @return an int
+ */
+ public int readVariableLengthInt()
+ throws IOException
+ {
+ int c, value = readByte();
+
+ if ((value & 0x80) != 0)
+ {
+ value &= 0x7F;
+ do
+ {
+ value = (value << 7) + ((c = readByte()) & 0x7F);
+ } while ((c & 0x80) != 0);
+ }
+
+ return value;
+ }
+}
diff --git a/libjava/classpath/gnu/javax/sound/midi/file/MidiDataOutputStream.java b/libjava/classpath/gnu/javax/sound/midi/file/MidiDataOutputStream.java
new file mode 100644
index 0000000..f9a3dac
--- /dev/null
+++ b/libjava/classpath/gnu/javax/sound/midi/file/MidiDataOutputStream.java
@@ -0,0 +1,114 @@
+/* MidiDataOutputStream.java -- adds variable length MIDI ints
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.sound.midi.file;
+
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * MidiDataOutputStream is simply a DataOutputStream with the addition
+ * of special variable length int writing as defined by the MIDI spec.
+ *
+ * @author Anthony Green (green@redhat.com)
+ */
+public class MidiDataOutputStream
+ extends DataOutputStream
+{
+ /**
+ * Create a MidiDataOutputStream.
+ */
+ public MidiDataOutputStream(OutputStream os)
+ {
+ super(os);
+ }
+
+ /**
+ * Return the length of a variable length encoded int without
+ * writing it out.
+ *
+ * @return the length of the encoding
+ */
+ public int variableLengthIntLength (int value)
+ {
+ int length = 0;
+ int buffer = value & 0x7F;
+
+ while ((value >>= 7) != 0)
+ {
+ buffer <<= 8;
+ buffer |= ((value & 0x7F) | 0x80);
+ }
+
+ while (true)
+ {
+ length++;
+ if ((buffer & 0x80) != 0)
+ buffer >>>= 8;
+ else
+ break;
+ }
+
+ return length;
+ }
+
+ /**
+ * Write an int encoded in the MIDI-style variable length
+ * encoding format.
+ */
+ public synchronized void writeVariableLengthInt (int value)
+ throws IOException
+ {
+ int buffer = value & 0x7F;
+
+ while ((value >>= 7) != 0)
+ {
+ buffer <<= 8;
+ buffer |= ((value & 0x7F) | 0x80);
+ }
+
+ while (true)
+ {
+ writeByte(buffer & 0xff);
+ if ((buffer & 0x80) != 0)
+ buffer >>>= 8;
+ else
+ break;
+ }
+ }
+}
diff --git a/libjava/classpath/gnu/javax/sound/midi/file/MidiFileReader.java b/libjava/classpath/gnu/javax/sound/midi/file/MidiFileReader.java
new file mode 100644
index 0000000..cb640e1
--- /dev/null
+++ b/libjava/classpath/gnu/javax/sound/midi/file/MidiFileReader.java
@@ -0,0 +1,378 @@
+/* MidiFileReader.java -- Read MIDI files.
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.sound.midi.file;
+
+import java.io.DataInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+import javax.sound.midi.InvalidMidiDataException;
+import javax.sound.midi.MetaMessage;
+import javax.sound.midi.MidiEvent;
+import javax.sound.midi.MidiFileFormat;
+import javax.sound.midi.MidiMessage;
+import javax.sound.midi.Sequence;
+import javax.sound.midi.ShortMessage;
+import javax.sound.midi.SysexMessage;
+import javax.sound.midi.Track;
+
+/**
+ * A MIDI file reader.
+ *
+ * This code reads MIDI file types 0 and 1.
+ *
+ * There are many decent documents on the web describing the MIDI file
+ * format. I didn't bother looking for the official document. If it
+ * exists, I'm not even sure if it is freely available. We should
+ * update this comment if we find out anything helpful here.
+ *
+ * @author Anthony Green (green@redhat.com)
+ *
+ */
+public class MidiFileReader extends javax.sound.midi.spi.MidiFileReader
+{
+ /* Get the MidiFileFormat for the given input stream.
+ * @see javax.sound.midi.spi.MidiFileReader#getMidiFileFormat(java.io.InputStream)
+ */
+ public MidiFileFormat getMidiFileFormat(InputStream in)
+ throws InvalidMidiDataException, IOException
+ {
+ DataInputStream din;
+ if (in instanceof DataInputStream)
+ din = (DataInputStream) in;
+ else
+ din = new DataInputStream(in);
+
+ int type, ntracks, division, resolution, bytes;
+ float divisionType;
+
+ if (din.readInt() != 0x4d546864) // "MThd"
+ throw new InvalidMidiDataException("Invalid MIDI chunk header.");
+
+ bytes = din.readInt();
+ if (bytes < 6)
+ throw new
+ InvalidMidiDataException("Invalid MIDI chunk header length: " + bytes);
+
+ type = din.readShort();
+ if (type < 0 || type > 2)
+ throw new
+ InvalidMidiDataException("Invalid MIDI file type value: " + type);
+
+ ntracks = din.readShort();
+ if (ntracks <= 0)
+ throw new
+ InvalidMidiDataException("Invalid number of MIDI tracks: " + ntracks);
+
+ division = din.readShort();
+ if ((division & 0x8000) != 0)
+ {
+ division = -((division >>> 8) & 0xFF);
+ switch (division)
+ {
+ case 24:
+ divisionType = Sequence.SMPTE_24;
+ break;
+
+ case 25:
+ divisionType = Sequence.SMPTE_25;
+ break;
+
+ case 29:
+ divisionType = Sequence.SMPTE_30DROP;
+ break;
+
+ case 30:
+ divisionType = Sequence.SMPTE_30;
+ break;
+
+ default:
+ throw new
+ InvalidMidiDataException("Invalid MIDI frame division type: "
+ + division);
+ }
+ resolution = division & 0xff;
+ }
+ else
+ {
+ divisionType = Sequence.PPQ;
+ resolution = division & 0x7fff;
+ }
+
+ // If we haven't read every byte in the header now, just skip the rest.
+ din.skip(bytes - 6);
+
+ return new ExtendedMidiFileFormat(type, divisionType, resolution,
+ MidiFileFormat.UNKNOWN_LENGTH,
+ MidiFileFormat.UNKNOWN_LENGTH, ntracks);
+ }
+
+ /* Get the MidiFileFormat from the given URL.
+ * @see javax.sound.midi.spi.MidiFileReader#getMidiFileFormat(java.net.URL)
+ */
+ public MidiFileFormat getMidiFileFormat(URL url)
+ throws InvalidMidiDataException, IOException
+ {
+ InputStream is = url.openStream();
+ try
+ {
+ return getMidiFileFormat(is);
+ }
+ finally
+ {
+ is.close();
+ }
+ }
+
+ /* Get the MidiFileFormat from the given file.
+ * @see javax.sound.midi.spi.MidiFileReader#getMidiFileFormat(java.io.File)
+ */
+ public MidiFileFormat getMidiFileFormat(File file)
+ throws InvalidMidiDataException, IOException
+ {
+ InputStream is = new FileInputStream(file);
+ try
+ {
+ return getMidiFileFormat(is);
+ }
+ finally
+ {
+ is.close();
+ }
+ }
+
+ /* Get the MIDI Sequence found in this input stream.
+ * @see javax.sound.midi.spi.MidiFileReader#getSequence(java.io.InputStream)
+ */
+ public Sequence getSequence(InputStream is) throws InvalidMidiDataException,
+ IOException
+ {
+ MidiDataInputStream din = new MidiDataInputStream(is);
+ ExtendedMidiFileFormat mff = (ExtendedMidiFileFormat) getMidiFileFormat(din);
+
+ Sequence seq = new Sequence(mff.getDivisionType(), mff.getResolution());
+
+ int ntracks = mff.getNumberTracks();
+
+ while (ntracks-- > 0)
+ {
+ Track track = seq.createTrack();
+ int Mtrk = din.readInt();
+ if (Mtrk != 0x4d54726b)
+ throw new InvalidMidiDataException("Invalid MIDI track header.");
+ int length = din.readInt();
+
+ int runningStatus = -1;
+ int click = 0;
+
+ // Set this to true when we've hit an End of Track meta event.
+ boolean done = false;
+
+ // Read all events.
+ while (! done)
+ {
+ MidiMessage mm;
+ int dtime = din.readVariableLengthInt();
+ click += dtime;
+
+ int sbyte = din.readUnsignedByte();
+
+ if (sbyte < 0xf0)
+ {
+ ShortMessage sm;
+ switch (sbyte & 0xf0)
+ {
+ case ShortMessage.NOTE_OFF:
+ case ShortMessage.NOTE_ON:
+ case ShortMessage.POLY_PRESSURE:
+ case ShortMessage.CONTROL_CHANGE:
+ case ShortMessage.PITCH_BEND:
+ case ShortMessage.SONG_POSITION_POINTER:
+ sm = new ShortMessage();
+ sm.setMessage(sbyte, din.readByte(), din.readByte());
+ runningStatus = sbyte;
+ break;
+
+ case ShortMessage.PROGRAM_CHANGE:
+ case ShortMessage.CHANNEL_PRESSURE:
+ case ShortMessage.SONG_SELECT:
+ case 0xF5: // FIXME: unofficial bus select. Not in spec??
+ sm = new ShortMessage();
+ sm.setMessage(sbyte, din.readByte(), 0);
+ runningStatus = sbyte;
+ break;
+
+ case ShortMessage.TUNE_REQUEST:
+ case ShortMessage.END_OF_EXCLUSIVE:
+ case ShortMessage.TIMING_CLOCK:
+ case ShortMessage.START:
+ case ShortMessage.CONTINUE:
+ case ShortMessage.STOP:
+ case ShortMessage.ACTIVE_SENSING:
+ case ShortMessage.SYSTEM_RESET:
+ sm = new ShortMessage();
+ sm.setMessage(sbyte, 0, 0);
+ runningStatus = sbyte;
+ break;
+
+ default:
+ if (runningStatus != - 1)
+ {
+ switch (runningStatus & 0xf0)
+ {
+ case ShortMessage.NOTE_OFF:
+ case ShortMessage.NOTE_ON:
+ case ShortMessage.POLY_PRESSURE:
+ case ShortMessage.CONTROL_CHANGE:
+ case ShortMessage.PITCH_BEND:
+ case ShortMessage.SONG_POSITION_POINTER:
+ sm = new ShortMessage();
+ sm.setMessage(runningStatus, sbyte, din.readByte());
+ break;
+
+ case ShortMessage.PROGRAM_CHANGE:
+ case ShortMessage.CHANNEL_PRESSURE:
+ case ShortMessage.SONG_SELECT:
+ case 0xF5: // FIXME: unofficial bus select. Not in
+ // spec??
+ sm = new ShortMessage();
+ sm.setMessage(runningStatus, sbyte, 0);
+ continue;
+
+ case ShortMessage.TUNE_REQUEST:
+ case ShortMessage.END_OF_EXCLUSIVE:
+ case ShortMessage.TIMING_CLOCK:
+ case ShortMessage.START:
+ case ShortMessage.CONTINUE:
+ case ShortMessage.STOP:
+ case ShortMessage.ACTIVE_SENSING:
+ case ShortMessage.SYSTEM_RESET:
+ sm = new ShortMessage();
+ sm.setMessage(runningStatus, 0, 0);
+ continue;
+
+ default:
+ throw new
+ InvalidMidiDataException("Invalid Short MIDI Event: "
+ + sbyte);
+ }
+ }
+ else
+ throw new
+ InvalidMidiDataException("Invalid Short MIDI Event: "
+ + sbyte);
+ }
+ mm = sm;
+ }
+ else if (sbyte == 0xf0 || sbyte == 0xf7)
+ {
+ // System Exclusive event
+ int slen = din.readVariableLengthInt();
+ byte sysex[] = new byte[slen];
+ din.readFully(sysex);
+ SysexMessage sm = new SysexMessage();
+ sm.setMessage(sbyte, sysex, slen);
+ mm = sm;
+ runningStatus = - 1;
+ }
+ else if (sbyte == 0xff)
+ {
+ // Meta Message
+ byte mtype = din.readByte();
+ int mlen = din.readVariableLengthInt();
+ byte meta[] = new byte[mlen];
+ din.readFully(meta);
+ MetaMessage metam = new MetaMessage();
+ metam.setMessage(mtype, meta, mlen);
+ mm = metam;
+
+ if (mtype == 0x2f) // End of Track
+ done = true;
+
+ runningStatus = - 1;
+ }
+ else
+ {
+ throw new InvalidMidiDataException("Invalid status byte: "
+ + sbyte);
+ }
+
+ track.add(new MidiEvent(mm, click));
+ }
+ }
+
+ return seq;
+ }
+
+ /* Get the MIDI Sequence found at the given URL.
+ * @see javax.sound.midi.spi.MidiFileReader#getSequence(java.net.URL)
+ */
+ public Sequence getSequence(URL url) throws InvalidMidiDataException,
+ IOException
+ {
+ InputStream is = url.openStream();
+ try
+ {
+ return getSequence(is);
+ }
+ finally
+ {
+ is.close();
+ }
+ }
+
+ /* Get the MIDI Sequence found in the given file.
+ * @see javax.sound.midi.spi.MidiFileReader#getSequence(java.io.File)
+ */
+ public Sequence getSequence(File file) throws InvalidMidiDataException,
+ IOException
+ {
+ InputStream is = new FileInputStream(file);
+ try
+ {
+ return getSequence(is);
+ }
+ finally
+ {
+ is.close();
+ }
+ }
+}
diff --git a/libjava/classpath/gnu/javax/sound/midi/file/MidiFileWriter.java b/libjava/classpath/gnu/javax/sound/midi/file/MidiFileWriter.java
new file mode 100644
index 0000000..71970d5
--- /dev/null
+++ b/libjava/classpath/gnu/javax/sound/midi/file/MidiFileWriter.java
@@ -0,0 +1,199 @@
+/* MidiFileWriter.java -- Write MIDI files.
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.sound.midi.file;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import javax.sound.midi.MetaMessage;
+import javax.sound.midi.MidiEvent;
+import javax.sound.midi.Sequence;
+import javax.sound.midi.Track;
+
+/**
+ * A MIDI file writer.
+ *
+ * This code writes MIDI file types 0 and 1.
+ *
+ * There are many decent documents on the web describing the MIDI file
+ * format. I didn't bother looking for the official document. If it
+ * exists, I'm not even sure if it is freely available. We should
+ * update this comment if we find out anything helpful here.
+ *
+ * @author Anthony Green (green@redhat.com)
+ *
+ */
+public class MidiFileWriter
+ extends javax.sound.midi.spi.MidiFileWriter
+{
+ /* Return an array indicating which midi file types are supported.
+ * @see javax.sound.midi.spi.MidiFileWriter#getMidiFileTypes()
+ */
+ public int[] getMidiFileTypes()
+ {
+ return new int[]{0, 1};
+ }
+
+ /* Return an array indicating which midi file types are supported
+ * for a given Sequence.
+ * @see javax.sound.midi.spi.MidiFileWriter#getMidiFileTypes(javax.sound.midi.Sequence)
+ */
+ public int[] getMidiFileTypes(Sequence sequence)
+ {
+ if (sequence.getTracks().length == 1)
+ return new int[]{0};
+ else
+ return new int[]{1};
+ }
+
+ /* Write a sequence to an output stream in standard midi format.
+ * @see javax.sound.midi.spi.MidiFileWriter#write(javax.sound.midi.Sequence, int, java.io.OutputStream)
+ */
+ public int write(Sequence in, int fileType, OutputStream out)
+ throws IOException
+ {
+ MidiDataOutputStream dos = new MidiDataOutputStream (out);
+ Track[] tracks = in.getTracks();
+ dos.writeInt(0x4d546864); // MThd
+ dos.writeInt(6);
+ dos.writeShort(fileType);
+ dos.writeShort(tracks.length);
+ float divisionType = in.getDivisionType();
+ int resolution = in.getResolution();
+ // FIXME: division computation is incomplete.
+ int division = 0;
+ if (divisionType == Sequence.PPQ)
+ division = resolution & 0x7fff;
+ dos.writeShort(division);
+ int length = 14;
+ for (int i = 0; i < tracks.length; i++)
+ length += writeTrack(tracks[i], dos);
+ return length;
+ }
+
+ /**
+ * Compute the length of a track as it will be written to the
+ * output stream.
+ *
+ * @param track the track to measure
+ * @param dos a MidiDataOutputStream used for helper method
+ * @return the length of the track
+ */
+ private int computeTrackLength(Track track, MidiDataOutputStream dos)
+ {
+ int count = 0, length = 0, i = 0, eventCount = track.size();
+ long ptick = 0;
+ while (i < eventCount)
+ {
+ MidiEvent me = track.get(i);
+ long tick = me.getTick();
+ length += dos.variableLengthIntLength((int) (tick - ptick));
+ ptick = tick;
+ length += me.getMessage().getLength();
+ i++;
+ }
+ return length;
+ }
+
+ /**
+ * Write a track to an output stream.
+ *
+ * @param track the track to write
+ * @param dos a MidiDataOutputStream to write to
+ * @return the number of bytes written
+ */
+ private int writeTrack(Track track, MidiDataOutputStream dos)
+ throws IOException
+ {
+ int i = 0, elength = track.size(), trackLength;
+ MidiEvent pme = null;
+ dos.writeInt(0x4d54726b); // "MTrk"
+ trackLength = computeTrackLength(track, dos);
+ dos.writeInt(trackLength);
+ while (i < elength)
+ {
+ MidiEvent me = track.get(i);
+ int dtime = 0;
+ if (pme != null)
+ dtime = (int) (me.getTick() - pme.getTick());
+ dos.writeVariableLengthInt(dtime);
+ // FIXME: use running status byte
+ byte msg[] = me.getMessage().getMessage();
+ dos.write(msg);
+ pme = me;
+ i++;
+ }
+
+ // We're done if the last event was an End of Track meta message.
+ if (pme != null && (pme.getMessage() instanceof MetaMessage))
+ {
+ MetaMessage mm = (MetaMessage) pme.getMessage();
+ if (mm.getType() == 0x2f) // End of Track message
+ return trackLength + 8;
+ }
+
+ // Write End of Track meta message
+ dos.writeVariableLengthInt(0); // Delta time of 0
+ dos.writeByte(0xff); // Meta Message
+ dos.writeByte(0x2f); // End of Track message
+ dos.writeVariableLengthInt(0); // Length of 0
+
+ return trackLength + 8 + 4;
+ }
+
+ /* Write a Sequence to a file.
+ * @see javax.sound.midi.spi.MidiFileWriter#write(javax.sound.midi.Sequence, int, java.io.File)
+ */
+ public int write(Sequence in, int fileType, File out) throws IOException
+ {
+ OutputStream os = new FileOutputStream(out);
+ try
+ {
+ return write(in, fileType, os);
+ }
+ finally
+ {
+ os.close();
+ }
+ }
+
+}
diff --git a/libjava/classpath/gnu/javax/sound/sampled/AU/AUReader.java b/libjava/classpath/gnu/javax/sound/sampled/AU/AUReader.java
new file mode 100644
index 0000000..c9035df
--- /dev/null
+++ b/libjava/classpath/gnu/javax/sound/sampled/AU/AUReader.java
@@ -0,0 +1,212 @@
+/* AUReader.java -- Read AU files.
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.sound.sampled.AU;
+
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioSystem;
+import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.UnsupportedAudioFileException;
+import javax.sound.sampled.spi.AudioFileReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.BufferedInputStream;
+import java.io.InputStream;
+import java.io.DataInputStream;
+import java.io.FileInputStream;
+import java.net.URL;
+import java.nio.ByteBuffer;
+
+public class AUReader extends AudioFileReader
+{
+ private static class AUHeader
+ {
+ // Magic number identifying the file. '.snd'
+ private static final int MAGIC = 0x2e736e64;
+
+ public static final int SIZE = 24; // size of the header
+
+ // Encoding types
+ public static final int ULAW = 1; // 8-bit u-law
+ public static final int PCM8 = 2; // 8-bit PCM
+ public static final int PCM16 = 3; // 16-bit PCM
+ public static final int PCM24 = 4; // 24-bit PCM
+ public static final int PCM32 = 5; // 32-bit PCM
+ public static final int IEEE32 = 6; // 32-bit IEEE f.p.
+ public static final int IEEE64 = 7; // 64-bit IEEE f.p.
+ public static final int G721 = 23;
+ public static final int G722 = 24;
+ public static final int G723 = 25;
+ public static final int G723_5BIT = 26;
+ public static final int ALAW = 27; // 8-bit a-law
+
+ // Header data.
+ public int headerSize;
+ public int fileSize; // this value may not be set.
+ public int encoding;
+ public int sampleRate;
+ public int channels;
+ public int sampleSizeInBits;
+
+ public AUHeader(InputStream stream)
+ throws IOException, UnsupportedAudioFileException
+ {
+ byte[] hdr = new byte[24];
+ stream.read( hdr );
+ ByteBuffer buf = ByteBuffer.wrap(hdr);
+
+ if( buf.getInt() != MAGIC )
+ throw new UnsupportedAudioFileException("Not an AU format audio file.");
+ headerSize = buf.getInt();
+ fileSize = buf.getInt();
+ encoding = buf.getInt();
+ sampleRate = buf.getInt();
+ channels = buf.getInt();
+
+ switch(encoding)
+ {
+ case ULAW:
+ case PCM8:
+ case ALAW:
+ sampleSizeInBits = 8;
+ break;
+ case PCM16:
+ sampleSizeInBits = 16;
+ break;
+ case PCM24:
+ sampleSizeInBits = 24;
+ break;
+ case PCM32:
+ sampleSizeInBits = 32;
+ break;
+ default: // other types exist but are not supported. Yet.
+ throw new UnsupportedAudioFileException("Unsupported encoding.");
+ }
+ }
+
+ public AudioFormat getAudioFormat()
+ {
+ AudioFormat.Encoding encType = AudioFormat.Encoding.PCM_SIGNED;
+ if(encoding == 1)
+ encType = AudioFormat.Encoding.ULAW;
+ if(encoding == 27)
+ encType = AudioFormat.Encoding.ALAW;
+
+ return new AudioFormat(encType,
+ (float)sampleRate,
+ sampleSizeInBits,
+ channels,
+ (sampleSizeInBits >> 3) * channels,
+ (float)sampleRate,
+ true);
+ }
+
+ public AudioFileFormat getAudioFileFormat()
+ {
+ return new AudioFileFormat(new AUFormatType(),
+ getAudioFormat(),
+ AudioSystem.NOT_SPECIFIED);
+ }
+ }
+
+ public static class AUFormatType extends AudioFileFormat.Type
+ {
+ public AUFormatType()
+ {
+ super("AU", ".au");
+ }
+ }
+
+ public AudioFileFormat getAudioFileFormat(File file)
+ throws IOException, UnsupportedAudioFileException
+ {
+ return getAudioFileFormat(new FileInputStream(file));
+ }
+
+ public AudioFileFormat getAudioFileFormat(InputStream stream)
+ throws IOException, UnsupportedAudioFileException
+ {
+ if(!stream.markSupported())
+ throw new IOException("Stream must support marking.");
+
+ stream.mark(25);
+ AUHeader header = new AUHeader(stream);
+ stream.reset();
+
+ return header.getAudioFileFormat();
+ }
+
+ public AudioFileFormat getAudioFileFormat(URL url)
+ throws IOException, UnsupportedAudioFileException
+ {
+ return getAudioFileFormat(new BufferedInputStream(url.openStream()));
+ }
+
+ public AudioInputStream getAudioInputStream(File file)
+ throws IOException, UnsupportedAudioFileException
+ {
+ InputStream stream = new FileInputStream(file);
+ long length = file.length();
+
+ AUHeader header = new AUHeader( stream );
+ if( header.headerSize > AUHeader.SIZE )
+ stream.skip(header.headerSize - AUHeader.SIZE);
+
+ length -= header.headerSize;
+
+ return new AudioInputStream(stream, header.getAudioFormat(), length);
+ }
+
+ public AudioInputStream getAudioInputStream(InputStream stream)
+ throws IOException, UnsupportedAudioFileException
+ {
+ AUHeader header = new AUHeader( stream );
+ if( header.headerSize > AUHeader.SIZE )
+ stream.skip(header.headerSize - AUHeader.SIZE);
+
+ return new AudioInputStream(stream, header.getAudioFormat(),
+ AudioSystem.NOT_SPECIFIED);
+ }
+
+ public AudioInputStream getAudioInputStream(URL url)
+ throws IOException, UnsupportedAudioFileException
+ {
+ return getAudioInputStream(new BufferedInputStream(url.openStream()));
+ }
+}
+
diff --git a/libjava/classpath/gnu/javax/sound/sampled/WAV/WAVReader.java b/libjava/classpath/gnu/javax/sound/sampled/WAV/WAVReader.java
new file mode 100644
index 0000000..0cf3c13
--- /dev/null
+++ b/libjava/classpath/gnu/javax/sound/sampled/WAV/WAVReader.java
@@ -0,0 +1,236 @@
+/* WAVReader.java -- Read WAV files.
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.javax.sound.sampled.WAV;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.DataInputStream;
+import java.io.FileInputStream;
+import java.net.URL;
+
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.UnsupportedAudioFileException;
+import javax.sound.sampled.spi.AudioFileReader;
+
+/**
+ * A WAV file reader.
+ *
+ * This code reads WAV files.
+ *
+ * There are many decent documents on the web describing the WAV file
+ * format. I didn't bother looking for the official document. If it
+ * exists, I'm not even sure if it is freely available. We should
+ * update this comment if we find out anything helpful here. I used
+ * http://www.sonicspot.com/guide/wavefiles.html
+ *
+ * @author Anthony Green (green@redhat.com)
+ *
+ */
+public class WAVReader extends AudioFileReader
+{
+ private static long readUnsignedIntLE (DataInputStream is)
+ throws IOException
+ {
+ byte[] buf = new byte[4];
+ is.readFully(buf);
+ return (buf[0] & 0xFF
+ | ((buf[1] & 0xFF) << 8)
+ | ((buf[2] & 0xFF) << 16)
+ | ((buf[3] & 0xFF) << 24));
+ }
+
+ private static short readUnsignedShortLE (DataInputStream is)
+ throws IOException
+ {
+ byte[] buf = new byte[2];
+ is.readFully(buf);
+ return (short) (buf[0] & 0xFF
+ | ((buf[1] & 0xFF) << 8));
+ }
+
+ /* Get an AudioFileFormat from the given File.
+ * @see javax.sound.sampled.spi.AudioFileReader#getAudioFileFormat(java.io.File)
+ */
+ public AudioFileFormat getAudioFileFormat(File file)
+ throws UnsupportedAudioFileException, IOException
+ {
+ InputStream is = new FileInputStream(file);
+ try
+ {
+ return getAudioFileFormat(is);
+ }
+ finally
+ {
+ is.close();
+ }
+ }
+
+ /* Get an AudioFileFormat from the given InputStream.
+ * @see javax.sound.sampled.spi.AudioFileReader#getAudioFileFormat(java.io.InputStream)
+ */
+ public AudioFileFormat getAudioFileFormat(InputStream in)
+ throws UnsupportedAudioFileException, IOException
+ {
+ DataInputStream din;
+
+ if (in instanceof DataInputStream)
+ din = (DataInputStream) in;
+ else
+ din = new DataInputStream(in);
+
+ if (din.readInt() != 0x52494646) // "RIFF"
+ throw new UnsupportedAudioFileException("Invalid WAV chunk header.");
+
+ // Read the length of this RIFF thing.
+ readUnsignedIntLE(din);
+
+ if (din.readInt() != 0x57415645) // "WAVE"
+ throw new UnsupportedAudioFileException("Invalid WAV chunk header.");
+
+ boolean foundFmt = false;
+ boolean foundData = false;
+
+ short compressionCode = 0, numberChannels = 0, blockAlign = 0, bitsPerSample = 0;
+ long sampleRate = 0, bytesPerSecond = 0;
+ long chunkLength = 0;
+
+ while (! foundData)
+ {
+ int chunkId = din.readInt();
+ chunkLength = readUnsignedIntLE(din);
+ switch (chunkId)
+ {
+ case 0x666D7420: // "fmt "
+ foundFmt = true;
+ compressionCode = readUnsignedShortLE(din);
+ numberChannels = readUnsignedShortLE(din);
+ sampleRate = readUnsignedIntLE(din);
+ bytesPerSecond = readUnsignedIntLE(din);
+ blockAlign = readUnsignedShortLE(din);
+ bitsPerSample = readUnsignedShortLE(din);
+ din.skip(chunkLength - 16);
+ break;
+ case 0x66616374: // "fact"
+ // FIXME: hold compression format dependent data.
+ din.skip(chunkLength);
+ break;
+ case 0x64617461: // "data"
+ if (! foundFmt)
+ throw new UnsupportedAudioFileException("This implementation requires WAV fmt chunks precede data chunks.");
+ foundData = true;
+ break;
+ default:
+ // Unrecognized chunk. Skip it.
+ din.skip(chunkLength);
+ }
+ }
+
+ AudioFormat.Encoding encoding;
+
+ switch (compressionCode)
+ {
+ case 1: // PCM/uncompressed
+ if (bitsPerSample <= 8)
+ encoding = AudioFormat.Encoding.PCM_UNSIGNED;
+ else
+ encoding = AudioFormat.Encoding.PCM_SIGNED;
+ break;
+
+ default:
+ throw new UnsupportedAudioFileException("Unrecognized WAV compression code: 0x"
+ + Integer.toHexString(compressionCode));
+ }
+
+ return new AudioFileFormat (AudioFileFormat.Type.WAVE,
+ new AudioFormat(encoding,
+ (float) sampleRate,
+ bitsPerSample,
+ numberChannels,
+ ((bitsPerSample + 7) / 8) * numberChannels,
+ (float) bytesPerSecond, false),
+ (int) chunkLength);
+ }
+
+ /* Get an AudioFileFormat from the given URL.
+ * @see javax.sound.sampled.spi.AudioFileReader#getAudioFileFormat(java.net.URL)
+ */
+ public AudioFileFormat getAudioFileFormat(URL url)
+ throws UnsupportedAudioFileException, IOException
+ {
+ InputStream is = url.openStream();
+ try
+ {
+ return getAudioFileFormat(is);
+ }
+ finally
+ {
+ is.close();
+ }
+ }
+
+ /* Get an AudioInputStream from the given File.
+ * @see javax.sound.sampled.spi.AudioFileReader#getAudioInputStream(java.io.File)
+ */
+ public AudioInputStream getAudioInputStream(File file)
+ throws UnsupportedAudioFileException, IOException
+ {
+ return getAudioInputStream(new FileInputStream(file));
+ }
+
+ /* Get an AudioInputStream from the given InputStream.
+ * @see javax.sound.sampled.spi.AudioFileReader#getAudioInputStream(java.io.InputStream)
+ */
+ public AudioInputStream getAudioInputStream(InputStream stream)
+ throws UnsupportedAudioFileException, IOException
+ {
+ AudioFileFormat aff = getAudioFileFormat(stream);
+ return new AudioInputStream(stream, aff.getFormat(), (long) aff.getFrameLength());
+ }
+
+ /* Get an AudioInputStream from the given URL.
+ * @see javax.sound.sampled.spi.AudioFileReader#getAudioInputStream(java.net.URL)
+ */
+ public AudioInputStream getAudioInputStream(URL url)
+ throws UnsupportedAudioFileException, IOException
+ {
+ return getAudioInputStream(url.openStream());
+ }
+}
diff --git a/libjava/classpath/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java b/libjava/classpath/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java
index 67d6332..a9b504a 100644
--- a/libjava/classpath/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java
+++ b/libjava/classpath/gnu/javax/swing/plaf/gnu/GNULookAndFeel.java
@@ -71,6 +71,7 @@ public class GNULookAndFeel extends BasicLookAndFeel
"ScrollBar.background", new ColorUIResource(blueGray),
"CheckBox.icon", new CheckBoxIcon(),
"RadioButton.icon", new RadioButtonIcon(),
+ "Tree.hash", new ColorUIResource(Color.black),
"Tree.closedIcon",
new IconUIResource(new ImageIcon
diff --git a/libjava/classpath/gnu/javax/swing/text/html/CharacterAttributeTranslator.java b/libjava/classpath/gnu/javax/swing/text/html/CharacterAttributeTranslator.java
index 5f73095..06732e4 100644
--- a/libjava/classpath/gnu/javax/swing/text/html/CharacterAttributeTranslator.java
+++ b/libjava/classpath/gnu/javax/swing/text/html/CharacterAttributeTranslator.java
@@ -83,7 +83,7 @@ public class CharacterAttributeTranslator
* @param colorName the color to convert.
* @return the matching java.awt.color
*/
- private static Color getColor(String colorName)
+ public static Color getColor(String colorName)
{
colorName = colorName.toLowerCase();
try
diff --git a/libjava/classpath/gnu/javax/swing/text/html/parser/GnuParserDelegator.java b/libjava/classpath/gnu/javax/swing/text/html/parser/GnuParserDelegator.java
new file mode 100644
index 0000000..841db66
--- /dev/null
+++ b/libjava/classpath/gnu/javax/swing/text/html/parser/GnuParserDelegator.java
@@ -0,0 +1,178 @@
+/* GnuParserDelegator.java -- The parser delegator which uses Swing DTD
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.swing.text.html.parser;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Serializable;
+
+import javax.swing.text.BadLocationException;
+import javax.swing.text.html.HTMLEditorKit;
+import javax.swing.text.html.HTMLEditorKit.ParserCallback;
+import javax.swing.text.html.parser.DTD;
+import javax.swing.text.html.parser.ParserDelegator;
+import javax.swing.text.html.parser.TagElement;
+
+/**
+ * This parser delegator uses the different DTD ({@link HTML_401Swing}).
+ * It is derived from the ParserDelegator for the compatibility reasons.
+ *
+ * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
+ */
+public class GnuParserDelegator extends ParserDelegator implements Serializable
+{
+ class gnuParser
+ extends gnu.javax.swing.text.html.parser.support.Parser
+ {
+ private static final long serialVersionUID = 1;
+
+ gnuParser(DTD d)
+ {
+ super(d);
+ }
+
+ protected final void handleComment(char[] comment)
+ {
+ callBack.handleComment(comment, hTag.where.startPosition);
+ }
+
+ protected final void handleEmptyTag(TagElement tag)
+ throws javax.swing.text.ChangedCharSetException
+ {
+ callBack.handleSimpleTag(tag.getHTMLTag(), getAttributes(),
+ hTag.where.startPosition
+ );
+ }
+
+ protected final void handleEndTag(TagElement tag)
+ {
+ callBack.handleEndTag(tag.getHTMLTag(), hTag.where.startPosition);
+ }
+
+ protected final void handleError(int line, String message)
+ {
+ callBack.handleError(message, hTag.where.startPosition);
+ }
+
+ protected final void handleStartTag(TagElement tag)
+ {
+ htmlAttributeSet attributes = gnu.getAttributes();
+
+ if (tag.fictional())
+ attributes.addAttribute(ParserCallback.IMPLIED, Boolean.TRUE);
+
+ callBack.handleStartTag(tag.getHTMLTag(), attributes,
+ hTag.where.startPosition
+ );
+ }
+
+ protected final void handleText(char[] text)
+ {
+ callBack.handleText(text, hTag.where.startPosition);
+ }
+
+ DTD getDTD()
+ {
+ // Accessing the inherited gnu.javax.swing.text.html.parser.support.Parser
+ // field. super. is a workaround, required to support JDK1.3's javac.
+ return super.dtd;
+ }
+ }
+
+ /**
+ * Use serialVersionUID for interoperability.
+ */
+ private static final long serialVersionUID = -1276686502624777206L;
+
+ private DTD theDtd;
+
+ /**
+ * The callback.
+ * This is package-private to avoid an accessor method.
+ */
+ HTMLEditorKit.ParserCallback callBack;
+
+ /**
+ * The reference to the working class of HTML parser that is
+ * actually used to parse the document.
+ * This is package-private to avoid an accessor method.
+ */
+ gnuParser gnu;
+
+ /**
+ * Create the parser that uses the given DTD to parse the document.
+ *
+ * @param theDtd the DTD
+ */
+ public GnuParserDelegator(DTD theDtd)
+ {
+ this.theDtd = theDtd;
+ gnu = new gnuParser(theDtd);
+ }
+
+ /**
+ * Parses the HTML document, calling methods of the provided callback. This
+ * method must be multithread - safe.
+ *
+ * @param reader The reader to read the HTML document from
+ * @param a_callback The callback that is notifyed about the presence of HTML
+ * elements in the document.
+ * @param ignoreCharSet If thrue, any charset changes during parsing are
+ * ignored.
+ * @throws java.io.IOException
+ */
+ public void parse(Reader reader,
+ HTMLEditorKit.ParserCallback a_callback,
+ boolean ignoreCharSet) throws IOException
+ {
+ callBack = a_callback;
+ gnu.parse(reader);
+
+ callBack.handleEndOfLineString(gnu.getEndOfLineSequence());
+ try
+ {
+ callBack.flush();
+ }
+ catch (BadLocationException ex)
+ {
+ // Convert this into the supported type of exception.
+ throw new IOException(ex.getMessage());
+ }
+ }
+}
diff --git a/libjava/classpath/gnu/javax/swing/text/html/parser/HTML_401F.java b/libjava/classpath/gnu/javax/swing/text/html/parser/HTML_401F.java
index 1ed42a2..c3c347e 100644
--- a/libjava/classpath/gnu/javax/swing/text/html/parser/HTML_401F.java
+++ b/libjava/classpath/gnu/javax/swing/text/html/parser/HTML_401F.java
@@ -759,23 +759,8 @@ public class HTML_401F
defElement(BODY, 0, true, true, null,
NONE
,
- new String[] {
- PCDATA, A, ABBR, ACRONYM,
- APPLET, B, BASEFONT, BDO, BIG,
- BR, BUTTON, CITE, CODE, DFN,
- EM, FONT, I, IFRAME, IMG,
- INPUT, KBD, LABEL, MAP, OBJECT,
- Q, S, SAMP, SCRIPT, SELECT,
- SMALL, SPAN, STRIKE, STRONG, SUB,
- SUP, TEXTAREA, TT, U, VAR,
- ADDRESS, BLOCKQUOTE, CENTER, DEL, DIR,
- DIV, DL, FIELDSET, FORM, H1,
- H2, H3, H4, H5, H6,
- HR, INS, ISINDEX, MENU, NOFRAMES,
- NOSCRIPT, OL, P, PRE, TABLE,
- UL
- }
- ,
+ getBodyElements()
+ ,
new AttributeList[] {
attr(sID, null, null, ID, IMPLIED),
attr(CLASS, null, null, 0, IMPLIED),
@@ -3634,7 +3619,7 @@ public class HTML_401F
* Crate a content model, consisting of the single
* element, specified by name.
*/
- private ContentModel model(String element)
+ protected ContentModel model(String element)
{
return new ContentModel(getElement(element));
}
@@ -3653,7 +3638,7 @@ public class HTML_401F
/**
* Create the model HEAD, BODY
- * @return
+ * @return the HTML content model of the whole document
*/
protected ContentModel createHtmlContentModel()
{
@@ -3725,5 +3710,27 @@ public class HTML_401F
li.type = ul.type = ol.type = '|';
return li;
}
-
+
+ /**
+ * Get elements that are allowed in the document body, at the zero level.
+ */
+ protected String[] getBodyElements()
+ {
+ return new String[] {
+ PCDATA, A, ABBR, ACRONYM,
+ APPLET, B, BASEFONT, BDO, BIG,
+ BR, BUTTON, CITE, CODE, DFN,
+ EM, FONT, I, IFRAME, IMG,
+ INPUT, KBD, LABEL, MAP, OBJECT,
+ Q, S, SAMP, SCRIPT, SELECT,
+ SMALL, SPAN, STRIKE, STRONG, SUB,
+ SUP, TEXTAREA, TT, U, VAR,
+ ADDRESS, BLOCKQUOTE, CENTER, DEL, DIR,
+ DIV, DL, FIELDSET, FORM, H1,
+ H2, H3, H4, H5, H6,
+ HR, INS, ISINDEX, MENU, NOFRAMES,
+ NOSCRIPT, OL, P, PRE, TABLE,
+ UL
+ };
+ }
}
diff --git a/libjava/classpath/gnu/javax/swing/text/html/parser/HTML_401Swing.java b/libjava/classpath/gnu/javax/swing/text/html/parser/HTML_401Swing.java
new file mode 100644
index 0000000..9c934f6
--- /dev/null
+++ b/libjava/classpath/gnu/javax/swing/text/html/parser/HTML_401Swing.java
@@ -0,0 +1,91 @@
+/* HTML_401Swing.java -- The HTML 4.01 DTD, adapted for HTML rendering in Swing
+ Copyright (C) 2006 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
+02110-1301 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package gnu.javax.swing.text.html.parser;
+
+import javax.swing.text.html.parser.DTD;
+
+/**
+ * This class is necessary because the current implementation of the GNU
+ * Classpath Swing requires always enclose the text into paragraphs.
+ *
+ * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
+ */
+public class HTML_401Swing extends HTML_401F
+{
+ /**
+ * The singleton instance;
+ */
+ final static HTML_401Swing singleton = new HTML_401Swing();
+
+ /**
+ * Either takes the document (by name) from DTD table, or
+ * creates a new instance and registers it in the tabe.
+ * The document is registerd under name "-//W3C//DTD HTML 4.01 Frameset//EN".
+ * @return The new or existing DTD for parsing HTML 4.01 Frameset.
+ */
+ public static DTD getInstance()
+ {
+ return singleton;
+ }
+
+ /**
+ * Get elements that are allowed in the document body, at the zero level.
+ * This list disallows the text at this level (the implied P tag will be
+ * generated). It also disallows A, B, I, U, CITE and other similar
+ * elements that have the plain text inside. They will also be placed
+ * inside the generated implied P tags.
+ */
+ protected String[] getBodyElements()
+ {
+ return new String[] {
+ APPLET, BASEFONT,
+ BR, BUTTON,
+ IFRAME, IMG,
+ INPUT, LABEL, MAP, OBJECT,
+ SCRIPT, SELECT,
+ TEXTAREA,
+ BLOCKQUOTE, CENTER, DEL, DIR,
+ DIV, DL, FIELDSET, FORM, H1,
+ H2, H3, H4, H5, H6,
+ HR, INS, ISINDEX, MENU, NOFRAMES,
+ NOSCRIPT, OL, P, PRE, TABLE,
+ UL
+ };
+ }
+}
diff --git a/libjava/classpath/gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java b/libjava/classpath/gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java
index 45e1dce..930a324 100644
--- a/libjava/classpath/gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java
+++ b/libjava/classpath/gnu/javax/swing/text/html/parser/SmallHtmlAttributeSet.java
@@ -100,8 +100,6 @@ public class SmallHtmlAttributeSet
key = en.nextElement();
keys[i] = key;
value = copyFrom.getAttribute(key);
- if (value instanceof String)
- value = ((String) value).toLowerCase();
values[i] = value;
}
}
diff --git a/libjava/classpath/gnu/javax/swing/text/html/parser/htmlValidator.java b/libjava/classpath/gnu/javax/swing/text/html/parser/htmlValidator.java
index 1f9eee0..4d287a6 100644
--- a/libjava/classpath/gnu/javax/swing/text/html/parser/htmlValidator.java
+++ b/libjava/classpath/gnu/javax/swing/text/html/parser/htmlValidator.java
@@ -233,7 +233,9 @@ public abstract class htmlValidator
Element fe = (Element) v;
// notify the content model that we add the proposed tag
- getCurrentContentModel().show(fe);
+ node ccm = getCurrentContentModel();
+ if (ccm != null)
+ ccm.show(fe);
openFictionalTag(fe);
Object vv = tagIsValidForContext(tElement);
@@ -301,13 +303,12 @@ public abstract class htmlValidator
}
/**
- * Check if this tag is valid for the current context.
- * Return Boolean.True if it is OK, Boolean.False
- * if it is surely not OK or the Element that the
- * content model recommends to insert making the situation
- * ok. If Boolean.True is returned, the content model current
- * position is moved forward. Otherwise this position remains
- * the same.
+ * Check if this tag is valid for the current context. Return Boolean.True if
+ * it is OK, Boolean.False if it is surely not OK or the Element that the
+ * content model recommends to insert making the situation ok. If Boolean.True
+ * is returned, the content model current position is moved forward. Otherwise
+ * this position remains the same.
+ *
* @param tElement
* @return
*/
@@ -321,7 +322,7 @@ public abstract class htmlValidator
// Check exclusions and inclusions.
ListIterator iter = stack.listIterator(stack.size());
- hTag t;
+ hTag t = null;
final int idx = tElement.getElement().index;
// Check only known tags.
@@ -331,19 +332,27 @@ public abstract class htmlValidator
while (iter.hasPrevious())
{
t = (hTag) iter.previous();
- if (!t.forcibly_closed)
+ if (! t.forcibly_closed)
{
- if (t.element.exclusions != null &&
- t.element.exclusions.get(idx)
- )
+ if (t.element.exclusions != null
+ && t.element.exclusions.get(idx))
return Boolean.FALSE;
if (t.element.inclusions != null)
inclusions.or(t.element.inclusions);
}
}
- if (!inclusions.get(idx))
- return Boolean.FALSE;
+ if (! inclusions.get(idx))
+ {
+ // If we need to insert something, and cannot do this, but
+ // it is allowed to insert the paragraph here, insert the
+ // paragraph.
+ Element P = dtd.getElement(HTML_401F.P);
+ if (inclusions.get(P.index))
+ return P;
+ else
+ return Boolean.FALSE;
+ }
}
return Boolean.TRUE;
}
diff --git a/libjava/classpath/gnu/regexp/BacktrackStack.java b/libjava/classpath/gnu/regexp/BacktrackStack.java
deleted file mode 100644
index 0fc73f0..0000000
--- a/libjava/classpath/gnu/regexp/BacktrackStack.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/* gnu/regexp/BacktrackStack.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-package gnu.regexp;
-
-/**
- * An instance of this class represents a stack
- * used for backtracking.
- *
- * @author Ito Kazumitsu
- */
-final class BacktrackStack {
-
- /** A set of data to be used for backtracking. */
- static class Backtrack {
- /** REToken to which to go back */
- REToken token;
- /** CharIndexed on which matches are being searched for. */
- CharIndexed input;
- /** REMatch to be used by the REToken token. */
- REMatch match;
- /** Some parameter used by the token's backtrack method. */
- Object param;
- Backtrack(REToken token, CharIndexed input, REMatch match, Object param) {
- this.token = token;
- this.input = input;
- // REMatch may change before backtracking is needed. So we
- // keep a clone of it.
- this.match = (REMatch) match.clone();
- this.param = param;
- }
- }
-
- Backtrack[] stack;
- private int size;
- private int capacity;
- private static final int INITIAL_CAPACITY = 32;
- private static final int CAPACITY_INCREMENT = 16;
-
- BacktrackStack() {
- stack = new Backtrack[INITIAL_CAPACITY];
- size = 0;
- capacity = INITIAL_CAPACITY;
- }
-
- boolean empty() {
- return size == 0;
- }
-
- Backtrack peek() {
- return stack[size - 1];
- }
-
- Backtrack pop() {
- Backtrack bt = stack[--size];
- stack[size] = null;
- return bt;
- }
-
- void clear() {
- for (int i = 0; i < size; i++) {
- stack[i] = null;
- }
- size = 0;
- }
-
- void push(Backtrack bt) {
- if (size >= capacity) {
- capacity += CAPACITY_INCREMENT;
- Backtrack[] newStack = new Backtrack[capacity];
- System.arraycopy(stack, 0, newStack, 0, size);
- stack = newStack;
- }
- stack[size++] = bt;
- }
-
-}
diff --git a/libjava/classpath/gnu/regexp/CharIndexed.java b/libjava/classpath/gnu/regexp/CharIndexed.java
deleted file mode 100644
index 8aedc49..0000000
--- a/libjava/classpath/gnu/regexp/CharIndexed.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/* gnu/regexp/CharIndexed.java
- Copyright (C) 1998-2001, 2004, 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-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 Wes Biggs
- */
-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();
-
- /**
- * Returns another CharIndexed containing length characters to the left
- * of the given index. The given length is an expected maximum and
- * the returned CharIndexed may not necessarily contain so many characters.
- */
- CharIndexed lookBehind(int index, int length);
-
- /**
- * Returns the effective length of this CharIndexed
- */
- int length();
-
- /**
- * Sets the REMatch last found on this input.
- */
- void setLastMatch(REMatch match);
-
- /**
- * Returns the REMatch last found on this input.
- */
- REMatch getLastMatch();
-
- /**
- * Returns the anchor.
- */
- int getAnchor();
-
- /**
- * Sets the anchor.
- */
- void setAnchor(int anchor);
-}
diff --git a/libjava/classpath/gnu/regexp/CharIndexedCharArray.java b/libjava/classpath/gnu/regexp/CharIndexedCharArray.java
deleted file mode 100644
index 96a609b..0000000
--- a/libjava/classpath/gnu/regexp/CharIndexedCharArray.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/* gnu/regexp/CharIndexedCharArray.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package gnu.regexp;
-import java.nio.CharBuffer;
-
-class CharIndexedCharArray extends CharIndexedCharSequence {
-
- CharIndexedCharArray(char[] str, int index) {
- super(CharBuffer.wrap(str), index);
- }
-}
diff --git a/libjava/classpath/gnu/regexp/CharIndexedCharSequence.java b/libjava/classpath/gnu/regexp/CharIndexedCharSequence.java
deleted file mode 100644
index 5bbe4ab..0000000
--- a/libjava/classpath/gnu/regexp/CharIndexedCharSequence.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/* gnu/regexp/CharIndexedCharSequence.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package gnu.regexp;
-import java.io.Serializable;
-
-class CharIndexedCharSequence implements CharIndexed, Serializable {
- private CharSequence s;
- private int anchor;
- private int len;
-
- CharIndexedCharSequence(CharSequence s, int index) {
- this.s = s;
- 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);
- }
-
- public CharIndexed lookBehind(int index, int length) {
- if (length > (anchor + index)) length = anchor + index;
- return new CharIndexedCharSequence(s, anchor + index - length);
- }
-
- public int length() {
- return len - anchor;
- }
-
- private REMatch lastMatch;
- public void setLastMatch(REMatch match) {
- lastMatch = (REMatch)match.clone();
- lastMatch.anchor = anchor;
- }
- public REMatch getLastMatch() { return lastMatch; }
- public int getAnchor() { return anchor; }
- public void setAnchor(int anchor) { this.anchor = anchor; }
-}
diff --git a/libjava/classpath/gnu/regexp/CharIndexedInputStream.java b/libjava/classpath/gnu/regexp/CharIndexedInputStream.java
deleted file mode 100644
index 290a94e..0000000
--- a/libjava/classpath/gnu/regexp/CharIndexedInputStream.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/* gnu/regexp/CharIndexedInputStream.java
- Copyright (C) 1998-2001, 2004, 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package gnu.regexp;
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-// 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);
- }
-
- public CharIndexed lookBehind(int index, int length) {
- throw new UnsupportedOperationException(
- "difficult to look behind for an input stream");
- }
-
- public int length() {
- throw new UnsupportedOperationException(
- "difficult to tell the length for an input stream");
- }
-
- public void setLastMatch(REMatch match) {
- throw new UnsupportedOperationException(
- "difficult to support setLastMatch for an input stream");
- }
-
- public REMatch getLastMatch() {
- throw new UnsupportedOperationException(
- "difficult to support getLastMatch for an input stream");
- }
-
- public int getAnchor() {
- throw new UnsupportedOperationException(
- "difficult to support getAnchor for an input stream");
- }
-
- public void setAnchor(int anchor) {
- throw new UnsupportedOperationException(
- "difficult to support setAnchor for an input stream");
- }
-
-
-}
-
diff --git a/libjava/classpath/gnu/regexp/CharIndexedString.java b/libjava/classpath/gnu/regexp/CharIndexedString.java
deleted file mode 100644
index 2498265..0000000
--- a/libjava/classpath/gnu/regexp/CharIndexedString.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/* gnu/regexp/CharIndexedString.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package gnu.regexp;
-
-class CharIndexedString extends CharIndexedCharSequence {
- CharIndexedString(String str, int index) {
- super(str, index);
- }
-}
diff --git a/libjava/classpath/gnu/regexp/CharIndexedStringBuffer.java b/libjava/classpath/gnu/regexp/CharIndexedStringBuffer.java
deleted file mode 100644
index d6b03bb..0000000
--- a/libjava/classpath/gnu/regexp/CharIndexedStringBuffer.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/* gnu/regexp/CharIndexedStringBuffer.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package gnu.regexp;
-
-class CharIndexedStringBuffer extends CharIndexedCharSequence {
-
- CharIndexedStringBuffer(StringBuffer str, int index) {
- super(str, index);
- }
-}
diff --git a/libjava/classpath/gnu/regexp/RE.java b/libjava/classpath/gnu/regexp/RE.java
deleted file mode 100644
index e0665f0..0000000
--- a/libjava/classpath/gnu/regexp/RE.java
+++ /dev/null
@@ -1,2102 +0,0 @@
-/* gnu/regexp/RE.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package gnu.regexp;
-import java.io.InputStream;
-import java.io.Serializable;
-import java.util.Locale;
-import java.util.PropertyResourceBundle;
-import java.util.ResourceBundle;
-import java.util.Stack;
-import java.util.Vector;
-
-/**
- * RE provides the user interface for compiling and matching regular
- * expressions.
- * RESyntax.RE_SYNTAX_PERL5
is used).
- * isMatch
: returns true if the input text in its
- * entirety matches the regular expression pattern.
- * getMatch
: returns the first match found in the
- * input text, or null if no match is found.
- * getAllMatches
: returns an array of all
- * non-overlapping matches found in the input text. If no matches are
- * found, the array is zero-length.
- * substitute
: substitute the first occurence of the
- * pattern in the input text with a replacement string (which may
- * include metacharacters $0-$9, see REMatch.substituteInto).
- * substituteAll
: same as above, but repeat for each
- * match before returning.
- * getMatchEnumeration
: 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 getAllMatches
.
- *
- * String s = "food bar fool";
- */
- public static final int REG_NOTBOL = 0x10;
-
- /**
- * 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 = 0x20;
-
- /**
- * 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 = 0x40;
-
- /**
- * 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 = 0x80;
-
- /**
- * Execution flag.
- * Try to match the whole input string. An implicit match-end operator
- * is added to this regexp.
- */
- public static final int REG_TRY_ENTIRE_MATCH = 0x0100;
-
- /**
- * Execution flag.
- * The substitute and substituteAll methods will treat the
- * character '\' in the replacement as an escape to a literal
- * character. In this case "\n", "\$", "\\", "\x40" and "\012"
- * will become "n", "$", "\", "x40" and "012" respectively.
- * This flag has no effect if REG_NO_INTERPOLATE is set on.
- */
- public static final int REG_REPLACE_USE_BACKSLASHESCAPE = 0x0200;
-
- /**
- * Compilation flag. Allow whitespace and comments in pattern.
- * This is equivalent to the "/x" operator in Perl.
- */
- public static final int REG_X_COMMENTS = 0x0400;
-
- /**
- * Compilation flag. If set, REG_ICASE is effective only for US-ASCII.
- */
- public static final int REG_ICASE_USASCII = 0x0800;
-
- /** Returns a string representing the version of the gnu.regexp package. */
- public static final String version() {
- return VERSION;
- }
-
- // Retrieves a message from the ResourceBundle
- static final String getLocalizedMessage(String key) {
- 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, int maxLength) {
- super(subIndex);
- firstToken = first;
- lastToken = last;
- numSubs = subs;
- minimumLength = minLength;
- maximumLength = maxLength;
- 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);
- boolean insensUSASCII = ((cflags & REG_ICASE_USASCII) > 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;
- boolean quot = false;
-
- // Saved syntax and flags.
- RESyntax savedSyntax = null;
- int savedCflags = 0;
- boolean flagsSaved = false;
-
- while (index < pLength) {
- // read the next character unit (including backslash escapes)
- index = getCharUnit(pattern,index,unit,quot);
-
- if (unit.bk)
- if (unit.ch == 'Q') {
- quot = true;
- continue;
- } else if (unit.ch == 'E') {
- quot = false;
- continue;
- }
- if (quot)
- unit.bk = false;
-
- if (((cflags & REG_X_COMMENTS) > 0) && (!unit.bk) && (!quot)) {
- if (Character.isWhitespace(unit.ch)) {
- continue;
- }
- if (unit.ch == '#') {
- for (int i = index; i < pLength; i++) {
- if (pattern[i] == '\n') {
- index = i + 1;
- continue;
- }
- else if (pattern[i] == '\r') {
- if (i + 1 < pLength && pattern[i + 1] == '\n') {
- index = i + 2;
- }
- else {
- index = i + 1;
- }
- continue;
- }
- }
- index = pLength;
- continue;
- }
- }
-
- // 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 || quot)))
- || (syntax.get(RESyntax.RE_NEWLINE_ALT) && (unit.ch == '\n') && !(unit.bk || quot)) )
- && !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, maximumLength);
- minimumLength = 0;
- maximumLength = 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?
- //
- // This method used to check "repeat.empty.token" to avoid such regexp
- // as "(a*){2,}", but now "repeat.empty.token" is allowed.
-
- else if ((unit.ch == '{') && syntax.get(RESyntax.RE_INTERVALS) && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ (unit.bk || quot))) {
- 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);
- index = newIndex;
- currentToken = setRepeated(currentToken,minMax.first,minMax.second,index);
- }
- else {
- addToken(currentToken);
- currentToken = new RETokenChar(subIndex,unit.ch,insens);
- if (insensUSASCII) currentToken.unicodeAware = false;
- }
- }
-
- // LIST OPERATOR:
- // [...] | [^...]
-
- else if ((unit.ch == '[') && !(unit.bk || quot)) {
- // Create a new RETokenOneOf
- ParseCharClassResult result = parseCharClass(
- subIndex, pattern, index, pLength, cflags, syntax, 0);
- addToken(currentToken);
- currentToken = result.token;
- index = result.index;
- }
-
- // SUBEXPRESSIONS
- // (...) | \(...\) depending on RE_NO_BK_PARENS
-
- else if ((unit.ch == '(') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) {
- boolean pure = false;
- boolean comment = false;
- boolean lookAhead = false;
- boolean lookBehind = false;
- boolean independent = false;
- boolean negativelh = false;
- boolean negativelb = 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 '<':
- // We assume that if the syntax supports look-ahead,
- // it also supports look-behind.
- if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
- index++;
- switch (pattern[index +1]) {
- case '!':
- pure = true;
- negativelb = true;
- lookBehind = true;
- index += 2;
- break;
- case '=':
- pure = true;
- lookBehind = true;
- index += 2;
- }
- }
- break;
- case '>':
- // We assume that if the syntax supports look-ahead,
- // it also supports independent group.
- if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
- pure = true;
- independent = true;
- index += 2;
- }
- break;
- case 'i':
- case 'd':
- case 'm':
- case 's':
- case 'u':
- case 'x':
- case '-':
- if (!syntax.get(RESyntax.RE_EMBEDDED_FLAGS)) break;
- // Set or reset syntax flags.
- int flagIndex = index + 1;
- int endFlag = -1;
- RESyntax newSyntax = new RESyntax(syntax);
- int newCflags = cflags;
- boolean negate = false;
- while (flagIndex < pLength && endFlag < 0) {
- switch(pattern[flagIndex]) {
- case 'i':
- if (negate)
- newCflags &= ~REG_ICASE;
- else
- newCflags |= REG_ICASE;
- flagIndex++;
- break;
- case 'd':
- if (negate)
- newSyntax.setLineSeparator(RESyntax.DEFAULT_LINE_SEPARATOR);
- else
- newSyntax.setLineSeparator("\n");
- flagIndex++;
- break;
- case 'm':
- if (negate)
- newCflags &= ~REG_MULTILINE;
- else
- newCflags |= REG_MULTILINE;
- flagIndex++;
- break;
- case 's':
- if (negate)
- newCflags &= ~REG_DOT_NEWLINE;
- else
- newCflags |= REG_DOT_NEWLINE;
- flagIndex++;
- break;
- case 'u':
- if (negate)
- newCflags |= REG_ICASE_USASCII;
- else
- newCflags &= ~REG_ICASE_USASCII;
- flagIndex++;
- break;
- case 'x':
- if (negate)
- newCflags &= ~REG_X_COMMENTS;
- else
- newCflags |= REG_X_COMMENTS;
- flagIndex++;
- break;
- case '-':
- negate = true;
- flagIndex++;
- break;
- case ':':
- case ')':
- endFlag = pattern[flagIndex];
- break;
- default:
- throw new REException(getLocalizedMessage("repeat.no.token"), REException.REG_BADRPT, index);
- }
- }
- if (endFlag == ')') {
- syntax = newSyntax;
- cflags = newCflags;
- insens = ((cflags & REG_ICASE) > 0);
- insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
- // This can be treated as though it were a comment.
- comment = true;
- index = flagIndex - 1;
- break;
- }
- if (endFlag == ':') {
- savedSyntax = syntax;
- savedCflags = cflags;
- flagsSaved = true;
- syntax = newSyntax;
- cflags = newCflags;
- insens = ((cflags & REG_ICASE) > 0);
- insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
- index = flagIndex -1;
- // Fall through to the next case.
- }
- else {
- throw new REException(getLocalizedMessage("unmatched.paren"), REException.REG_ESUBREG,index);
- }
- 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,false)) > 0)
- && !(nested == 0 && (unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) ) {
- if ((endIndex = nextIndex) >= pLength)
- throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
- else if ((unit.ch == '[') && !(unit.bk || quot)) {
- // I hate to do something similar to the LIST OPERATOR matters
- // above, but ...
- int listIndex = nextIndex;
- if (listIndex < pLength && pattern[listIndex] == '^') listIndex++;
- if (listIndex < pLength && pattern[listIndex] == ']') listIndex++;
- int listEndIndex = -1;
- int listNest = 0;
- while (listIndex < pLength && listEndIndex < 0) {
- switch(pattern[listIndex++]) {
- case '\\':
- listIndex++;
- break;
- case '[':
- // Sun's API document says that regexp like "[a-d[m-p]]"
- // is legal. Even something like "[[[^]]]]" is accepted.
- listNest++;
- if (listIndex < pLength && pattern[listIndex] == '^') listIndex++;
- if (listIndex < pLength && pattern[listIndex] == ']') listIndex++;
- break;
- case ']':
- if (listNest == 0)
- listEndIndex = listIndex;
- listNest--;
- break;
- }
- }
- if (listEndIndex >= 0) {
- nextIndex = listEndIndex;
- if ((endIndex = nextIndex) >= pLength)
- throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
- else
- continue;
- }
- throw new REException(getLocalizedMessage("subexpr.no.end"),REException.REG_ESUBREG,nextIndex);
- }
- else if (unit.ch == '(' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))
- nested++;
- else if (unit.ch == ')' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))
- 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 || lookBehind || independent) ?
- 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);
- }
- else if (lookBehind) {
- currentToken = new RETokenLookBehind(currentToken,negativelb);
- }
- else if (independent) {
- currentToken = new RETokenIndependent(currentToken);
- }
-
- index = nextIndex;
- if (flagsSaved) {
- syntax = savedSyntax;
- cflags = savedCflags;
- insens = ((cflags & REG_ICASE) > 0);
- insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
- flagsSaved = false;
- }
- } // 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 || quot)))) {
- throw new REException(getLocalizedMessage("unmatched.paren"),REException.REG_EPAREN,index);
- }
-
- // START OF LINE OPERATOR
- // ^
-
- else if ((unit.ch == '^') && !(unit.bk || quot)) {
- 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 || quot)) {
- 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 || quot)) {
- 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
- // *
- //
- // This method used to check "repeat.empty.token" to avoid such regexp
- // as "(a*)*", but now "repeat.empty.token" is allowed.
-
- else if ((unit.ch == '*') && !(unit.bk || quot)) {
- 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);
- currentToken = setRepeated(currentToken,0,Integer.MAX_VALUE,index);
- }
-
- // ONE-OR-MORE REPEAT OPERATOR / POSSESSIVE MATCHING OPERATOR
- // + | \+ depending on RE_BK_PLUS_QM
- // not available if RE_LIMITED_OPS is set
- //
- // This method used to check "repeat.empty.token" to avoid such regexp
- // as "(a*)+", but now "repeat.empty.token" is allowed.
-
- else if ((unit.ch == '+') && !syntax.get(RESyntax.RE_LIMITED_OPS) && (!syntax.get(RESyntax.RE_BK_PLUS_QM) ^ (unit.bk || quot))) {
- if (currentToken == null)
- throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
-
- // Check for possessive matching on RETokenRepeated
- if (currentToken instanceof RETokenRepeated) {
- RETokenRepeated tokenRep = (RETokenRepeated)currentToken;
- if (syntax.get(RESyntax.RE_POSSESSIVE_OPS) && !tokenRep.isPossessive() && !tokenRep.isStingy())
- tokenRep.makePossessive();
- 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,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 || quot))) {
- if (currentToken == null) throw new REException(getLocalizedMessage("repeat.no.token"),REException.REG_BADRPT,index);
-
- // Check for stingy matching on RETokenRepeated
- if (currentToken instanceof RETokenRepeated) {
- RETokenRepeated tokenRep = (RETokenRepeated)currentToken;
- if (syntax.get(RESyntax.RE_STINGY_OPS) && !tokenRep.isStingy() && !tokenRep.isPossessive())
- tokenRep.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);
- }
-
- // OCTAL CHARACTER
- // \0377
-
- else if (unit.bk && (unit.ch == '0') && syntax.get(RESyntax.RE_OCTAL_CHAR)) {
- CharExpression ce = getCharExpression(pattern, index - 2, pLength, syntax);
- if (ce == null)
- throw new REException("invalid octal character", REException.REG_ESCAPE, index);
- index = index - 2 + ce.len;
- addToken(currentToken);
- currentToken = new RETokenChar(subIndex,ce.ch,insens);
- if (insensUSASCII) currentToken.unicodeAware = false;
- }
-
- // BACKREFERENCE OPERATOR
- // \1 \2 ... \9 and \10 \11 \12 ...
- // not available if RE_NO_BK_REFS is set
- // Perl recognizes \10, \11, and so on only if enough number of
- // parentheses have opened before it, otherwise they are treated
- // as aliases of \010, \011, ... (octal characters). In case of
- // Sun's JDK, octal character expression must always begin with \0.
- // We will do as JDK does. But FIXME, take a look at "(a)(b)\29".
- // JDK treats \2 as a back reference to the 2nd group because
- // there are only two groups. But in our poor implementation,
- // we cannot help but treat \29 as a back reference to the 29th group.
-
- else if (unit.bk && Character.isDigit(unit.ch) && !syntax.get(RESyntax.RE_NO_BK_REFS)) {
- addToken(currentToken);
- int numBegin = index - 1;
- int numEnd = pLength;
- for (int i = index; i < pLength; i++) {
- if (! Character.isDigit(pattern[i])) {
- numEnd = i;
- break;
- }
- }
- int num = parseInt(pattern, numBegin, numEnd-numBegin, 10);
-
- currentToken = new RETokenBackRef(subIndex,num,insens);
- if (insensUSASCII) currentToken.unicodeAware = false;
- index = numEnd;
- }
-
- // 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);
- if (insensUSASCII) currentToken.unicodeAware = 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);
- if (insensUSASCII) currentToken.unicodeAware = false;
- }
-
- // 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);
- if (insensUSASCII) currentToken.unicodeAware = 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);
- if (insensUSASCII) currentToken.unicodeAware = false;
- }
-
- // 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);
- if (insensUSASCII) currentToken.unicodeAware = 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);
- if (insensUSASCII) currentToken.unicodeAware = false;
- }
-
- // END OF STRING OPERATOR
- // \Z, \z
-
- // FIXME: \Z and \z are different in that if the input string
- // ends with a line terminator, \Z matches the position before
- // the final terminator. This special behavior of \Z is yet
- // to be implemented.
-
- else if (unit.bk && (unit.ch == 'Z' || unit.ch == 'z') &&
- syntax.get(RESyntax.RE_STRING_ANCHORS)) {
- addToken(currentToken);
- currentToken = new RETokenEnd(subIndex,null);
- }
-
- // HEX CHARACTER, UNICODE CHARACTER
- // \x1B, \u1234
-
- else if ((unit.bk && (unit.ch == 'x') && syntax.get(RESyntax.RE_HEX_CHAR)) ||
- (unit.bk && (unit.ch == 'u') && syntax.get(RESyntax.RE_UNICODE_CHAR))) {
- CharExpression ce = getCharExpression(pattern, index - 2, pLength, syntax);
- if (ce == null)
- throw new REException("invalid hex character", REException.REG_ESCAPE, index);
- index = index - 2 + ce.len;
- addToken(currentToken);
- currentToken = new RETokenChar(subIndex,ce.ch,insens);
- if (insensUSASCII) currentToken.unicodeAware = false;
- }
-
- // NAMED PROPERTY
- // \p{prop}, \P{prop}
-
- else if ((unit.bk && (unit.ch == 'p') && syntax.get(RESyntax.RE_NAMED_PROPERTY)) ||
- (unit.bk && (unit.ch == 'P') && syntax.get(RESyntax.RE_NAMED_PROPERTY))) {
- NamedProperty np = getNamedProperty(pattern, index - 2, pLength);
- if (np == null)
- throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
- index = index - 2 + np.len;
- addToken(currentToken);
- currentToken = getRETokenNamedProperty(subIndex,np,insens,index);
- if (insensUSASCII) currentToken.unicodeAware = false;
- }
-
- // END OF PREVIOUS MATCH
- // \G
-
- else if (unit.bk && (unit.ch == 'G') &&
- syntax.get(RESyntax.RE_STRING_ANCHORS)) {
- addToken(currentToken);
- currentToken = new RETokenEndOfPreviousMatch(subIndex);
- }
-
- // 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);
- if (insensUSASCII) currentToken.unicodeAware = false;
- }
- } // end while
-
- // Add final buffered token and an EndSub marker
- addToken(currentToken);
-
- if (branches != null) {
- branches.addElement(new RE(firstToken,lastToken,numSubs,subIndex,minimumLength, maximumLength));
- branches.trimToSize(); // compact the Vector
- minimumLength = 0;
- maximumLength = 0;
- firstToken = lastToken = null;
- addToken(new RETokenOneOf(subIndex,branches,false));
- }
- else addToken(new RETokenEndSub(subIndex));
-
- }
-
- private static class ParseCharClassResult {
- RETokenOneOf token;
- int index;
- boolean returnAtAndOperator = false;
- }
-
- /**
- * Parse [...] or [^...] and make an RETokenOneOf instance.
- * @param subIndex subIndex to be given to the created RETokenOneOf instance.
- * @param pattern Input array of characters to be parsed.
- * @param index Index pointing to the character next to the beginning '['.
- * @param pLength Limit of the input array.
- * @param cflags Compilation flags used to parse the pattern.
- * @param pflags Flags that affect the behavior of this method.
- * @param syntax Syntax used to parse the pattern.
- */
- private static ParseCharClassResult parseCharClass(int subIndex,
- char[] pattern, int index,
- int pLength, int cflags, RESyntax syntax, int pflags)
- throws REException {
-
- boolean insens = ((cflags & REG_ICASE) > 0);
- boolean insensUSASCII = ((cflags & REG_ICASE_USASCII) > 0);
- Vector options = new Vector();
- Vector addition = new Vector();
- boolean additionAndAppeared = false;
- final int RETURN_AT_AND = 0x01;
- boolean returnAtAndOperator = ((pflags & RETURN_AT_AND) != 0);
- boolean negative = false;
- char ch;
-
- char lastChar = 0;
- boolean lastCharIsSet = false;
- 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; lastCharIsSet = true;
- if (++index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
- }
-
- while ((ch = pattern[index++]) != ']') {
- if ((ch == '-') && (lastCharIsSet)) {
- if (index == pLength) throw new REException(getLocalizedMessage("class.no.end"),REException.REG_EBRACK,index);
- if ((ch = pattern[index]) == ']') {
- RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
- if (insensUSASCII) t.unicodeAware = false;
- options.addElement(t);
- lastChar = '-';
- } else {
- if ((ch == '\\') && syntax.get(RESyntax.RE_BACKSLASH_ESCAPE_IN_LISTS)) {
- CharExpression ce = getCharExpression(pattern, index, pLength, syntax);
- if (ce == null)
- throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
- ch = ce.ch;
- index = index + ce.len - 1;
- }
- RETokenRange t = new RETokenRange(subIndex,lastChar,ch,insens);
- if (insensUSASCII) t.unicodeAware = false;
- options.addElement(t);
- lastChar = 0; lastCharIsSet = false;
- 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;
- boolean asciiEscIsSet = false;
- NamedProperty np = null;
- 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;
- }
- }
- if (("pP".indexOf(pattern[index]) != -1) && syntax.get(RESyntax.RE_NAMED_PROPERTY)) {
- np = getNamedProperty(pattern, index - 1, pLength);
- if (np == null)
- throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
- index = index - 1 + np.len - 1;
- }
- else {
- CharExpression ce = getCharExpression(pattern, index - 1, pLength, syntax);
- if (ce == null)
- throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
- asciiEsc = ce.ch; asciiEscIsSet = true;
- index = index - 1 + ce.len - 1;
- }
- if (lastCharIsSet) {
- RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
- if (insensUSASCII) t.unicodeAware = false;
- options.addElement(t);
- }
-
- if (posixID != -1) {
- RETokenPOSIX t = new RETokenPOSIX(subIndex,posixID,insens,negate);
- if (insensUSASCII) t.unicodeAware = false;
- options.addElement(t);
- } else if (np != null) {
- RETokenNamedProperty t = getRETokenNamedProperty(subIndex,np,insens,index);
- if (insensUSASCII) t.unicodeAware = false;
- options.addElement(t);
- } else if (asciiEscIsSet) {
- lastChar = asciiEsc; lastCharIsSet = true;
- } else {
- lastChar = pattern[index]; lastCharIsSet = true;
- }
- ++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) {
- RETokenPOSIX t = new RETokenPOSIX(subIndex,posixId,insens,false);
- if (insensUSASCII) t.unicodeAware = false;
- options.addElement(t);
- }
- } else if ((ch == '[') && (syntax.get(RESyntax.RE_NESTED_CHARCLASS))) {
- ParseCharClassResult result = parseCharClass(
- subIndex, pattern, index, pLength, cflags, syntax, 0);
- addition.addElement(result.token);
- addition.addElement("|");
- index = result.index;
- } else if ((ch == '&') &&
- (syntax.get(RESyntax.RE_NESTED_CHARCLASS)) &&
- (index < pLength) && (pattern[index] == '&')) {
- if (returnAtAndOperator) {
- ParseCharClassResult result = new ParseCharClassResult();
- options.trimToSize();
- if (additionAndAppeared) addition.addElement("&");
- if (addition.size() == 0) addition = null;
- result.token = new RETokenOneOf(subIndex,
- options, addition, negative);
- result.index = index - 1;
- result.returnAtAndOperator = true;
- return result;
- }
- // The precedence of the operator "&&" is the lowest.
- // So we postpone adding "&" until other elements
- // are added. And we insert Boolean.FALSE at the
- // beginning of the list of tokens following "&&".
- // So, "&&[a-b][k-m]" will be stored in the Vecter
- // addition in this order:
- // Boolean.FALSE, [a-b], "|", [k-m], "|", "&"
- if (additionAndAppeared) addition.addElement("&");
- addition.addElement(Boolean.FALSE);
- additionAndAppeared = true;
-
- // The part on which "&&" operates may be either
- // (1) explicitly enclosed by []
- // or
- // (2) not enclosed by [] and terminated by the
- // next "&&" or the end of the character list.
- // Let the preceding else if block do the case (1).
- // We must do something in case of (2).
- if ((index + 1 < pLength) && (pattern[index + 1] != '[')) {
- ParseCharClassResult result = parseCharClass(
- subIndex, pattern, index+1, pLength, cflags, syntax,
- RETURN_AT_AND);
- addition.addElement(result.token);
- addition.addElement("|");
- // If the method returned at the next "&&", it is OK.
- // Otherwise we have eaten the mark of the end of this
- // character list "]". In this case we must give back
- // the end mark.
- index = (result.returnAtAndOperator ?
- result.index: result.index - 1);
- }
- } else {
- if (lastCharIsSet) {
- RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
- if (insensUSASCII) t.unicodeAware = false;
- options.addElement(t);
- }
- lastChar = ch; lastCharIsSet = true;
- }
- 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 (lastCharIsSet) {
- RETokenChar t = new RETokenChar(subIndex,lastChar,insens);
- if (insensUSASCII) t.unicodeAware = false;
- options.addElement(t);
- }
-
- ParseCharClassResult result = new ParseCharClassResult();
- // Create a new RETokenOneOf
- options.trimToSize();
- if (additionAndAppeared) addition.addElement("&");
- if (addition.size() == 0) addition = null;
- result.token = new RETokenOneOf(subIndex,options, addition, negative);
- result.index = index;
- return result;
- }
-
- private static int getCharUnit(char[] input, int index, CharUnit unit, boolean quot) throws REException {
- unit.ch = input[index++];
- unit.bk = (unit.ch == '\\'
- && (!quot || index >= input.length || input[index] == 'E'));
- if (unit.bk)
- if (index < input.length)
- unit.ch = input[index++];
- else throw new REException(getLocalizedMessage("ends.with.backslash"),REException.REG_ESCAPE,index);
- return index;
- }
-
- private static int parseInt(char[] input, int pos, int len, int radix) {
- int ret = 0;
- for (int i = pos; i < pos + len; i++) {
- ret = ret * radix + Character.digit(input[i], radix);
- }
- return ret;
- }
-
- /**
- * This class represents various expressions for a character.
- * "a" : 'a' itself.
- * "\0123" : Octal char 0123
- * "\x1b" : Hex char 0x1b
- * "\u1234" : Unicode char \u1234
- */
- private static class CharExpression {
- /** character represented by this expression */
- char ch;
- /** String expression */
- String expr;
- /** length of this expression */
- int len;
- public String toString() { return expr; }
- }
-
- private static CharExpression getCharExpression(char[] input, int pos, int lim,
- RESyntax syntax) {
- CharExpression ce = new CharExpression();
- char c = input[pos];
- if (c == '\\') {
- if (pos + 1 >= lim) return null;
- c = input[pos + 1];
- switch(c) {
- case 't':
- ce.ch = '\t';
- ce.len = 2;
- break;
- case 'n':
- ce.ch = '\n';
- ce.len = 2;
- break;
- case 'r':
- ce.ch = '\r';
- ce.len = 2;
- break;
- case 'x':
- case 'u':
- if ((c == 'x' && syntax.get(RESyntax.RE_HEX_CHAR)) ||
- (c == 'u' && syntax.get(RESyntax.RE_UNICODE_CHAR))) {
- int l = 0;
- int expectedLength = (c == 'x' ? 2 : 4);
- for (int i = pos + 2; i < pos + 2 + expectedLength; i++) {
- if (i >= lim) break;
- if (!((input[i] >= '0' && input[i] <= '9') ||
- (input[i] >= 'A' && input[i] <= 'F') ||
- (input[i] >= 'a' && input[i] <= 'f')))
- break;
- l++;
- }
- if (l != expectedLength) return null;
- ce.ch = (char)(parseInt(input, pos + 2, l, 16));
- ce.len = l + 2;
- }
- else {
- ce.ch = c;
- ce.len = 2;
- }
- break;
- case '0':
- if (syntax.get(RESyntax.RE_OCTAL_CHAR)) {
- int l = 0;
- for (int i = pos + 2; i < pos + 2 + 3; i++) {
- if (i >= lim) break;
- if (input[i] < '0' || input[i] > '7') break;
- l++;
- }
- if (l == 3 && input[pos + 2] > '3') l--;
- if (l <= 0) return null;
- ce.ch = (char)(parseInt(input, pos + 2, l, 8));
- ce.len = l + 2;
- }
- else {
- ce.ch = c;
- ce.len = 2;
- }
- break;
- default:
- ce.ch = c;
- ce.len = 2;
- break;
- }
- }
- else {
- ce.ch = input[pos];
- ce.len = 1;
- }
- ce.expr = new String(input, pos, ce.len);
- return ce;
- }
-
- /**
- * This class represents a substring in a pattern string expressing
- * a named property.
- * "\pA" : Property named "A"
- * "\p{prop}" : Property named "prop"
- * "\PA" : Property named "A" (Negated)
- * "\P{prop}" : Property named "prop" (Negated)
- */
- private static class NamedProperty {
- /** Property name */
- String name;
- /** Negated or not */
- boolean negate;
- /** length of this expression */
- int len;
- }
-
- private static NamedProperty getNamedProperty(char[] input, int pos, int lim) {
- NamedProperty np = new NamedProperty();
- char c = input[pos];
- if (c == '\\') {
- if (++pos >= lim) return null;
- c = input[pos++];
- switch(c) {
- case 'p':
- np.negate = false;
- break;
- case 'P':
- np.negate = true;
- break;
- default:
- return null;
- }
- c = input[pos++];
- if (c == '{') {
- int p = -1;
- for (int i = pos; i < lim; i++) {
- if (input[i] == '}') {
- p = i;
- break;
- }
- }
- if (p < 0) return null;
- int len = p - pos;
- np.name = new String(input, pos, len);
- np.len = len + 4;
- }
- else {
- np.name = new String(input, pos - 1, 1);
- np.len = 3;
- }
- return np;
- }
- else return null;
- }
-
- private static RETokenNamedProperty getRETokenNamedProperty(
- int subIndex, NamedProperty np, boolean insens, int index)
- throws REException {
- try {
- return new RETokenNamedProperty(subIndex, np.name, insens, np.negate);
- }
- catch (REException e) {
- REException ree;
- ree = new REException(e.getMessage(), REException.REG_ESCAPE, index);
- ree.initCause(e);
- throw ree;
- }
- }
-
- /**
- * 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)) {
- if (m != null) {
- if (input.charAt(m.index) == CharIndexed.OUT_OF_BOUNDS) {
- return true;
- }
- }
- }
- 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;
- }
-
- public int getMaximumLength() {
- return maximumLength;
- }
-
- /**
- * 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.start1[subIndex] = mymatch.index;
-
- return firstToken.match(input, mymatch);
- }
-
- REMatch findMatch(CharIndexed input, REMatch mymatch) {
- if (mymatch.backtrackStack == null)
- mymatch.backtrackStack = new BacktrackStack();
- boolean b = match(input, mymatch);
- if (b) {
- return mymatch;
- }
- return null;
- }
-
- /**
- * 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) {
- boolean tryEntireMatch = ((eflags & REG_TRY_ENTIRE_MATCH) != 0);
- RE re = (tryEntireMatch ? (RE) this.clone() : this);
- if (tryEntireMatch) {
- re.chain(new RETokenEnd(0, null));
- }
- // 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 (re.match(input, mymatch)) {
- REMatch best = mymatch;
- // We assume that the match that coms first is the best.
- // And the following "The longer, the better" rule has
- // been commented out. The longest is not neccesarily
- // the best. For example, "a" out of "aaa" is the best
- // match for /a+?/.
- /*
- // Find best match of them all to observe leftmost longest
- while ((mymatch = mymatch.next) != null) {
- if (mymatch.index > best.index) {
- best = mymatch;
- }
- }
- */
- best.end[0] = best.index;
- best.finish(input);
- input.setLastMatch(best);
- return best;
- }
- }
- 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));
-
- // Special handling at end of input for e.g. "$"
- if (minimumLength == 0) {
- if (match(input, mymatch)) {
- mymatch.finish(input);
- return mymatch;
- }
- }
-
- 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(getReplacement(replace, m, eflags));
- 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(getReplacement(replace, m, eflags));
- 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();
- }
-
- public static String getReplacement(String replace, REMatch m, int eflags) {
- if ((eflags & REG_NO_INTERPOLATE) > 0)
- return replace;
- else {
- if ((eflags & REG_REPLACE_USE_BACKSLASHESCAPE) > 0) {
- StringBuffer sb = new StringBuffer();
- int l = replace.length();
- for (int i = 0; i < l; i++) {
- char c = replace.charAt(i);
- switch(c) {
- case '\\':
- i++;
- // Let StringIndexOutOfBoundsException be thrown.
- sb.append(replace.charAt(i));
- break;
- case '$':
- int i1 = i + 1;
- while (i1 < replace.length() &&
- Character.isDigit(replace.charAt(i1))) i1++;
- sb.append(m.substituteInto(replace.substring(i, i1)));
- i = i1 - 1;
- break;
- default:
- sb.append(c);
- }
- }
- return sb.toString();
- }
- else
- return m.substituteInto(replace);
- }
- }
-
- /* Helper function for constructor */
- private void addToken(REToken next) {
- if (next == null) return;
- minimumLength += next.getMinimumLength();
- int nmax = next.getMaximumLength();
- if (nmax < Integer.MAX_VALUE && maximumLength < Integer.MAX_VALUE)
- maximumLength += nmax;
- else
- maximumLength = Integer.MAX_VALUE;
-
- 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,false);
- 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,false)) != 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("(?#startRE subIndex=" + subIndex + ")");
- if (subIndex == 0)
- os.append("?:");
- if (firstToken != null)
- firstToken.dumpAll(os);
- if (subIndex == 0)
- os.append(")");
- os.append("(?#endRE subIndex=" + subIndex + ")");
- }
-
- // Cast input appropriately or throw exception
- // This method was originally a private method, but has been made
- // public because java.util.regex.Matcher uses this.
- public static CharIndexed makeCharIndexed(Object input, int index) {
- // The case where input is already a CharIndexed is supposed
- // be the most likely because this is the case with
- // java.util.regex.Matcher.
- // We could let a String or a CharSequence fall through
- // to final input, but since it'a very likely input type,
- // we check it first.
- if (input instanceof CharIndexed) {
- CharIndexed ci = (CharIndexed) input;
- ci.setAnchor(index);
- return ci;
- }
- else if (input instanceof CharSequence)
- return new CharIndexedCharSequence((CharSequence) input,index);
- else 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
- return new CharIndexedString(input.toString(), index);
- }
-}
diff --git a/libjava/classpath/gnu/regexp/REException.java b/libjava/classpath/gnu/regexp/REException.java
deleted file mode 100644
index 73f86fa..0000000
--- a/libjava/classpath/gnu/regexp/REException.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/* gnu/regexp/REException.java
- Copyright (C) 1998-2001, 2004 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package gnu.regexp;
-
-import java.text.MessageFormat;
-
-/**
- * This is the regular expression exception class. An exception of this type
- * defines the three attributes:
- *
- * RE exp = new RE("^foo.");
- * REMatch m0 = exp.getMatch(s);
- * REMatch m1 = exp.getMatch(s.substring(8));
- * REMatch m2 = exp.getMatch(s.substring(8),0,RE.REG_NOTBOL);
- * REMatch m3 = exp.getMatch(s,8);
- * REMatch m4 = exp.getMatch(s,8,RE.REG_ANCHORINDEX);
- *
- * // m0.toString(): "food"
- * // m1.toString(): "fool"
- * // m2.toString(): null
- * // m3.toString(): null
- * // m4.toString(): "fool"
- *
- *
- *
- * @author Wes Biggs
- */
-
-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. Not implemented.
- */
- 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. Not implemented.
- */
- public static final int REG_EEND = 9;
-
- /**
- * Error flag.
- * Invalid escape sequence. Not implemented.
- */
- 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. Not implemented.
- */
- public static final int REG_ESIZE = 12;
-
- /**
- * Error flag.
- * The regex routines ran out of memory. Not implemented.
- */
- 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();
- }
-}
diff --git a/libjava/classpath/gnu/regexp/REFilterInputStream.java b/libjava/classpath/gnu/regexp/REFilterInputStream.java
deleted file mode 100644
index 485de56..0000000
--- a/libjava/classpath/gnu/regexp/REFilterInputStream.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/* gnu/regexp/REFilterInputStream.java
- Copyright (C) 1998-2001, 2004 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-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 Wes Biggs
- * @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);
- }
-}
diff --git a/libjava/classpath/gnu/regexp/REMatch.java b/libjava/classpath/gnu/regexp/REMatch.java
deleted file mode 100644
index 140a9c4..0000000
--- a/libjava/classpath/gnu/regexp/REMatch.java
+++ /dev/null
@@ -1,324 +0,0 @@
-/* gnu/regexp/REMatch.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-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 Wes Biggs
- */
-public final class REMatch implements Serializable, Cloneable {
- private String matchedText;
- private CharIndexed matchedCharIndexed;
-
- // 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
- // start1[i] is set when the i-th subexp starts. And start1[i] is copied
- // to start[i] when the i-th subexp ends. So start[i] keeps the previously
- // assigned value while the i-th subexp is being processed. This makes
- // backreference to the i-th subexp within the i-th subexp possible.
- int[] start; // start positions (relative to offset) for each (sub)exp.
- int[] start1; // start positions (relative to offset) for each (sub)exp.
- int[] end; // end positions for the same
- // start[i] == -1 or end[i] == -1 means that the start/end position is void.
- // start[i] == p or end[i] == p where p < 0 and p != -1 means that
- // the actual start/end position is (p+1). Start/end positions may
- // become negative when the subexpression is in a RETokenLookBehind.
- boolean empty; // empty string matched. This flag is used only within
- // RETokenRepeated.
-
- BacktrackStack backtrackStack;
-
- public Object clone() {
- try {
- REMatch copy = (REMatch) super.clone();
-
- copy.start = (int[]) start.clone();
- copy.start1 = (int[]) start1.clone();
- copy.end = (int[]) end.clone();
-
- return copy;
- } catch (CloneNotSupportedException e) {
- throw new Error(); // doesn't happen
- }
- }
-
- void assignFrom(REMatch other) {
- start = other.start;
- start1 = other.start1;
- end = other.end;
- index = other.index;
- backtrackStack = other.backtrackStack;
- }
-
- REMatch(int subs, int anchor, int eflags) {
- start = new int[subs+1];
- start1 = 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();
- matchedCharIndexed = text;
- 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;
- }
- }
- backtrackStack = null;
- }
-
- /** 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] = start1[i] = end[i] = -1;
- }
- backtrackStack = null;
- }
-
- /**
- * Returns the string matching the pattern. This makes it convenient
- * to write code like the following:
- *
- * REMatch myMatch = myExpression.getMatch(myString);
- */
- 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:
- *
- *
- * if (myMatch != null) System.out.println("Regexp found: "+myMatch);
- * REMatch myMatch = myExpression.getMatch(myString);
- * String theMatch = myString.substring(myMatch.getStartIndex(),
- * myMatch.getEndIndex());
- * toString()
- * 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) || sub < 0)
- throw new IndexOutOfBoundsException("No group " + sub);
- if (start[sub] == -1) return null;
- if (start[sub] >= 0 && end[sub] <= matchedText.length())
- return (matchedText.substring(start[sub],end[sub]));
- else {
- // This case occurs with RETokenLookAhead or RETokenLookBehind.
- StringBuffer sb = new StringBuffer();
- int s = start[sub];
- int e = end[sub];
- if (s < 0) s += 1;
- if (e < 0) e += 1;
- for (int i = start[0] + s; i < start[0] + e; i++)
- sb.append(matchedCharIndexed.charAt(i));
- return sb.toString();
- }
- }
-
- /**
- * Returns the index within the input string used to generate this match
- * where subexpression number sub begins, or -1
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 :
- (x >= 0) ? offset + x : offset + x + 1;
- }
-
- /**
- * Returns the index within the input string used to generate this match
- * where subexpression number sub begins, or -1
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 :
- (x >= 0) ? offset + x : offset + x + 1;
- }
-
- /**
- * Returns the index within the input string used to generate this match
- * where subexpression number sub ends, or -1
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 :
- (x >= 0) ? offset + x : offset + x + 1;
- }
-
- /**
- * Returns the index within the input string used to generate this match
- * where subexpression number sub ends, or -1
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 :
- (x >= 0) ? offset + x : offset + x + 1;
- }
-
- /**
- * Substitute the results of this match to create a new string.
- * This is patterned after PERL, so the tokens to watch out for are
- * $0
through $9
. $0
matches
- * the full substring matched; $n
matches
- * subexpression number n.
- * $10, $11, ...
may match the 10th, 11th, ... subexpressions
- * if such subexpressions exist.
- *
- * @param input A string consisting of literals and $n
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);
- int pos1 = pos + 1;
- while (pos1 < input.length() &&
- Character.isDigit(input.charAt(pos1))) {
- int val1 = val*10 + Character.digit(input.charAt(pos1),10);
- if (val1 >= start.length) break;
- pos1++;
- val = val1;
- }
- pos = pos1 - 1;
-
- 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();
- }
-
-/* The following are used for debugging purpose
- static String d(REMatch m) {
- if (m == null) return "null";
- else return "[" + m.index + "]";
- }
-
- String substringUptoIndex(CharIndexed input) {
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < index; i++) {
- sb.append(input.charAt(i));
- }
- return sb.toString();
- }
-*/
-
-}
diff --git a/libjava/classpath/gnu/regexp/REMatchEnumeration.java b/libjava/classpath/gnu/regexp/REMatchEnumeration.java
deleted file mode 100644
index f164a69..0000000
--- a/libjava/classpath/gnu/regexp/REMatchEnumeration.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/* gnu/regexp/REMatchEnumeration.java
- Copyright (C) 1998-2001, 2004 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-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 getMatchEnumeration()
methods on an instance of
- * RE.
- *
- * getAllMatches()
methods on RE. However, using an
- * enumeration can help speed performance when the entire text does
- * not need to be searched immediately.
- *
- * getMatch()
(see the
- * description of that method for an explanation of why). Enumeration
- * also saves a lot of overhead required when calling
- * getMatch()
multiple times.
- *
- * @author Wes Biggs
- */
-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();
- }
-}
-
diff --git a/libjava/classpath/gnu/regexp/RESyntax.java b/libjava/classpath/gnu/regexp/RESyntax.java
deleted file mode 100644
index 81fd999..0000000
--- a/libjava/classpath/gnu/regexp/RESyntax.java
+++ /dev/null
@@ -1,563 +0,0 @@
-/* gnu/regexp/RESyntax.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-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 Wes Biggs
- */
-
-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.
- * Not implemented.
- */
- public static final int RE_CONTEXT_INDEP_ANCHORS = 3;
-
- /**
- * Syntax bit. Repetition operators are only special in valid positions.
- * Not implemented.
- */
- 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.
- * Not implemented.
- */
- 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. Not implemented.
- */
- 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. Not implemented.
- */
- 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;
-
- /**
- * Syntax bit. Possessive matching is allowed (++, *+, ?+, {x,y}+).
- */
- public static final int RE_POSSESSIVE_OPS = 25;
-
- /**
- * Syntax bit. Allow embedded flags, (?is-x), as in Perl5.
- */
- public static final int RE_EMBEDDED_FLAGS = 26;
-
- /**
- * Syntax bit. Allow octal char (\0377), as in Perl5.
- */
- public static final int RE_OCTAL_CHAR = 27;
-
- /**
- * Syntax bit. Allow hex char (\x1b), as in Perl5.
- */
- public static final int RE_HEX_CHAR = 28;
-
- /**
- * Syntax bit. Allow Unicode char (\u1234), as in Java 1.4.
- */
- public static final int RE_UNICODE_CHAR = 29;
-
- /**
- * Syntax bit. Allow named property (\p{P}, \P{p}), as in Perl5.
- */
- public static final int RE_NAMED_PROPERTY = 30;
-
- /**
- * Syntax bit. Allow nested characterclass ([a-z&&[^p-r]]), as in Java 1.4.
- */
- public static final int RE_NESTED_CHARCLASS = 31;
-
- private static final int BIT_TOTAL = 32;
-
- /**
- * 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;
-
- /**
- * Predefined syntax.
- * Emulates regular expression support in Java 1.4's java.util.regex
- * package.
- */
- public static final RESyntax RE_SYNTAX_JAVA_1_4;
-
- 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) // (?#)
- .set(RE_EMBEDDED_FLAGS) // (?imsx-imsx)
- .set(RE_OCTAL_CHAR) // \0377
- .set(RE_HEX_CHAR) // \x1b
- .set(RE_NAMED_PROPERTY) // \p{prop}, \P{prop}
- .makeFinal();
-
- RE_SYNTAX_PERL5_S = new RESyntax(RE_SYNTAX_PERL5)
- .set(RE_DOT_NEWLINE)
- .makeFinal();
-
- RE_SYNTAX_JAVA_1_4 = new RESyntax(RE_SYNTAX_PERL5)
- // XXX
- .set(RE_POSSESSIVE_OPS) // *+,?+,++,{}+
- .set(RE_UNICODE_CHAR) // \u1234
- .set(RE_NESTED_CHARCLASS) // [a-z&&[^p-r]]
- .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;
- }
-}
diff --git a/libjava/classpath/gnu/regexp/REToken.java b/libjava/classpath/gnu/regexp/REToken.java
deleted file mode 100644
index f2abc02..0000000
--- a/libjava/classpath/gnu/regexp/REToken.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/* gnu/regexp/REToken.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-package gnu.regexp;
-import java.io.Serializable;
-
-abstract class REToken implements Serializable, Cloneable {
-
- protected REToken next = null;
- protected REToken uncle = null;
- protected int subIndex;
- protected boolean unicodeAware = true;
-
- public Object clone() {
- try {
- REToken copy = (REToken) super.clone();
- return copy;
- } catch (CloneNotSupportedException e) {
- throw new Error(); // doesn't happen
- }
- }
-
- protected REToken(int subIndex) {
- this.subIndex = subIndex;
- }
-
- int getMinimumLength() {
- return 0;
- }
-
- int getMaximumLength() {
- return Integer.MAX_VALUE;
- }
-
- void setUncle(REToken anUncle) {
- uncle = anUncle;
- }
-
- /** Returns true if the match succeeded, false if it failed. */
- boolean match(CharIndexed input, REMatch mymatch) {
- REMatch m = matchThis(input, mymatch);
- if (m == null) return false;
- if (next(input, m)) {
- mymatch.assignFrom(m);
- return true;
- }
- return false;
- }
-
- /** Returns true if the match succeeded, false if it failed.
- * The matching is done against this REToken only. Chained
- * tokens are not checked.
- * This method is used to define the default match method.
- * Simple subclasses of REToken, for example, such that
- * matches only one character, should implement this method.
- * Then the default match method will work. But complicated
- * subclasses of REToken, which needs a special match method,
- * do not have to implement this method.
- */
- REMatch matchThis(CharIndexed input, REMatch mymatch) {
- throw new UnsupportedOperationException(
- "This REToken does not have a matchThis method");
- }
-
- /** Returns true if the rest of the tokens match, false if they fail. */
- protected boolean next(CharIndexed input, REMatch mymatch) {
- REToken nextToken = getNext();
- if (nextToken == null) return true;
- return nextToken.match(input, mymatch);
- }
-
- /** Returns the next REToken chained to this REToken. */
- REToken getNext() {
- return (next != null ? next : uncle);
- }
-
- /** Finds a match at the position specified by the given REMatch.
- * If necessary, adds a BacktrackStack.Backtrack object to backtrackStack
- * of the REmatch found this time so that another possible match
- * may be found when backtrack is called.
- * By default, nothing is added to the backtrackStack.
- * @param CharIndexed input Input character sequence.
- * @param mymatch Position at which a match should be found
- * @return REMatch object if a match was found, null otherwise.
- */
- REMatch findMatch(CharIndexed input, REMatch mymatch) {
- boolean b = match(input, mymatch);
- if (b) return mymatch;
- return null;
- }
-
- boolean returnsFixedLengthMatches() {
- return false;
- }
-
- int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
- throw new UnsupportedOperationException(
- "This token does not support findFixedLengthMatches");
- }
-
- /**
- * Backtrack to another possibility.
- * Ordinary REToken cannot do anything if this method is called.
- */
- REMatch backtrack(CharIndexed input, REMatch mymatch, Object param) {
- throw new IllegalStateException("This token cannot be backtracked to");
- }
-
- 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);
- }
-
- public String toString() {
- StringBuffer os = new StringBuffer();
- dump(os);
- return os.toString();
- }
-
- /**
- * Converts the character argument to lowercase.
- * @param ch the character to be converted.
- * @param unicodeAware If true, use java.lang.Character#toLowerCase;
- * otherwise, only US-ASCII charactes can be converted.
- * @return the lowercase equivalent of the character, if any;
- * otherwise, the character itself.
- */
- public static char toLowerCase(char ch, boolean unicodeAware) {
- if (unicodeAware) return Character.toLowerCase(ch);
- if (ch >= 'A' && ch <= 'Z') return (char)(ch + 'a' - 'A');
- return ch;
- }
-
- /**
- * Converts the character argument to uppercase.
- * @param ch the character to be converted.
- * @param unicodeAware If true, use java.lang.Character#toUpperCase;
- * otherwise, only US-ASCII charactes can be converted.
- * @return the uppercase equivalent of the character, if any;
- * otherwise, the character itself.
- */
- public static char toUpperCase(char ch, boolean unicodeAware) {
- if (unicodeAware) return Character.toUpperCase(ch);
- if (ch >= 'a' && ch <= 'z') return (char)(ch + 'A' - 'a');
- return ch;
- }
-
-}
diff --git a/libjava/classpath/gnu/regexp/RETokenAny.java b/libjava/classpath/gnu/regexp/RETokenAny.java
deleted file mode 100644
index a37d956..0000000
--- a/libjava/classpath/gnu/regexp/RETokenAny.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/* gnu/regexp/RETokenAny.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-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;
- }
-
- int getMaximumLength() {
- return 1;
- }
-
- REMatch matchThis(CharIndexed input, REMatch mymatch) {
- char ch = input.charAt(mymatch.index);
- boolean retval = matchOneChar(ch);
- if (retval) {
- ++mymatch.index;
- return mymatch;
- }
- return null;
- }
-
- boolean matchOneChar(char ch) {
- if ((ch == CharIndexed.OUT_OF_BOUNDS)
- || (!newline && (ch == '\n'))
- || (matchNull && (ch == 0))) {
- return false;
- }
- return true;
- }
-
- boolean returnsFixedLengthMatches() { return true; }
-
- int findFixedLengthMatches(CharIndexed input, REMatch mymatch, int max) {
- int index = mymatch.index;
- int numRepeats = 0;
- while (true) {
- if (numRepeats >= max) break;
- char ch = input.charAt(index++);
- if (! matchOneChar(ch)) break;
- numRepeats++;
- }
- return numRepeats;
- }
-
- void dump(StringBuffer os) {
- os.append('.');
- }
-}
-
diff --git a/libjava/classpath/gnu/regexp/RETokenBackRef.java b/libjava/classpath/gnu/regexp/RETokenBackRef.java
deleted file mode 100644
index 25ef952..0000000
--- a/libjava/classpath/gnu/regexp/RETokenBackRef.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/* gnu/regexp/RETokenBackRef.java
- Copyright (C) 2006 Free Software Foundation, Inc.
-
-This file is part of GNU Classpath.
-
-GNU Classpath is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2, or (at your option)
-any later version.
-
-GNU Classpath is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with GNU Classpath; see the file COPYING. If not, write to the
-Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-02110-1301 USA.
-
-Linking this library statically or dynamically with other modules is
-making a combined work based on this library. Thus, the terms and
-conditions of the GNU General Public License cover the whole
-combination.
-
-As a special exception, the copyright holders of this library give you
-permission to link this library with independent modules to produce an
-executable, regardless of the license terms of these independent
-modules, and to copy and distribute the resulting executable under
-terms of your choice, provided that you also meet, for each linked
-independent module, the terms and conditions of the license of that
-module. An independent module is a module which is not derived from
-or based on this library. If you modify this library, you may extend
-this exception to your version of the library, but you are not
-obligated to do so. If you do not wish to do so, delete this
-exception statement from your version. */
-
-
-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?
-
- REMatch matchThis(CharIndexed input, REMatch mymatch) {
- if (num >= mymatch.start.length) return null;
- if (num >= mymatch.end.length) return null;
- int b,e;
- b = mymatch.start[num];
- e = mymatch.end[num];
- if ((b==-1)||(e==-1)) return null; // this shouldn't happen, but...
- if (b < 0) b += 1;
- if (e < 0) e += 1;
- for (int i=b; i