diff options
| author | Raif S. Naffah <raif@swiftdsl.com.au> | 2006-06-24 00:09:26 +0000 |
|---|---|---|
| committer | Raif S. Naffah <raif@swiftdsl.com.au> | 2006-06-24 00:09:26 +0000 |
| commit | c6a7fb5cb0459d9cfdb13834868c4b3c87fa7b7e (patch) | |
| tree | 25d8bec8afc47cbf7f95d62517939fbbf1383a87 /gnu/java/security | |
| parent | 6c181a1fd8daf166b48fa352fb3d8963d182c3d5 (diff) | |
| download | classpath-c6a7fb5cb0459d9cfdb13834868c4b3c87fa7b7e.tar.gz | |
2006-06-24 Raif S. Naffah <raif@swiftdsl.com.au>
* gnu/java/security/util/Util.java: Source formatting.
* gnu/java/security/util/SimpleList.java: Likewise.
* gnu/java/security/util/Sequence.java: Likewise.
* gnu/java/security/util/PRNG.java: Likewise.
* gnu/java/security/util/ExpirableObject.java: Likewise.
* gnu/java/security/util/Base64.java: Likewise.
* gnu/java/security/sig/SignatureFactory.java: Likewise.
* gnu/java/security/sig/ISignatureCodec.java: Likewise.
* gnu/java/security/sig/ISignature.java: Likewise.
* gnu/java/security/sig/BaseSignature.java: Likewise.
* gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java: Likewise.
* gnu/java/security/sig/rsa/RSAPSSSignature.java: Likewise.
* gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java: Likewise.
* gnu/java/security/sig/rsa/RSA.java: Likewise.
* gnu/java/security/sig/rsa/EMSA_PSS.java: Likewise.
* gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java: Likewise.
* gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java: Likewise.
* gnu/java/security/sig/dss/DSSSignatureRawCodec.java: Likewise.
* gnu/java/security/sig/dss/DSSSignature.java: Likewise.
* gnu/java/security/provider/X509CertificateFactory.java: Likewise.
* gnu/java/security/provider/PKIXCertPathValidatorImpl.java: Likewise.
* gnu/java/security/provider/Gnu.java: Likewise.
* gnu/java/security/prng/RandomEventListener.java: Likewise.
* gnu/java/security/prng/RandomEvent.java: Likewise.
* gnu/java/security/prng/PRNGFactory.java: Likewise.
* gnu/java/security/prng/MDGenerator.java: Likewise.
* gnu/java/security/prng/LimitReachedException.java: Likewise.
* gnu/java/security/prng/IRandom.java: Likewise.
* gnu/java/security/prng/EntropySource.java: Likewise.
* gnu/java/security/prng/BasePRNG.java: Likewise.
Diffstat (limited to 'gnu/java/security')
30 files changed, 1224 insertions, 1887 deletions
diff --git a/gnu/java/security/prng/BasePRNG.java b/gnu/java/security/prng/BasePRNG.java index fe815d700..3b7c8cf07 100644 --- a/gnu/java/security/prng/BasePRNG.java +++ b/gnu/java/security/prng/BasePRNG.java @@ -41,14 +41,11 @@ package gnu.java.security.prng; import java.util.Map; /** - * <p>An abstract class to facilitate implementing PRNG algorithms.</p> + * An abstract class to facilitate implementing PRNG algorithms. */ -public abstract class BasePRNG implements IRandom +public abstract class BasePRNG + implements IRandom { - - // Constants and variables - // ------------------------------------------------------------------------- - /** The canonical name prefix of the PRNG algorithm. */ protected String name; @@ -61,12 +58,9 @@ public abstract class BasePRNG implements IRandom /** The index into buffer of where the next byte will come from. */ protected int ndx; - // Constructor(s) - // ------------------------------------------------------------------------- - /** - * <p>Trivial constructor for use by concrete subclasses.</p> - * + * Trivial constructor for use by concrete subclasses. + * * @param name the canonical name of this instance. */ protected BasePRNG(String name) @@ -78,14 +72,6 @@ public abstract class BasePRNG implements IRandom buffer = new byte[0]; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // IRandom interface implementation ---------------------------------------- - public String name() { return name; @@ -101,10 +87,9 @@ public abstract class BasePRNG implements IRandom public byte nextByte() throws IllegalStateException, LimitReachedException { - if (!initialised) - { - throw new IllegalStateException(); - } + if (! initialised) + throw new IllegalStateException(); + return nextByteInternal(); } @@ -117,7 +102,7 @@ public abstract class BasePRNG implements IRandom public void nextBytes(byte[] out, int offset, int length) throws IllegalStateException, LimitReachedException { - if (!initialised) + if (! initialised) throw new IllegalStateException("not initialized"); if (length == 0) @@ -127,7 +112,6 @@ public abstract class BasePRNG implements IRandom throw new ArrayIndexOutOfBoundsException("offset=" + offset + " length=" + length + " limit=" + out.length); - if (ndx >= buffer.length) { fillBlock(); @@ -163,9 +147,6 @@ public abstract class BasePRNG implements IRandom throw new UnsupportedOperationException("random state is non-modifiable"); } - // Instance methods - // ------------------------------------------------------------------------- - public boolean isInitialised() { return initialised; @@ -182,8 +163,6 @@ public abstract class BasePRNG implements IRandom return buffer[ndx++]; } - // abstract methods to implement by subclasses ----------------------------- - public Object clone() throws CloneNotSupportedException { BasePRNG result = (BasePRNG) super.clone(); diff --git a/gnu/java/security/prng/EntropySource.java b/gnu/java/security/prng/EntropySource.java index 260c668f8..95f68f048 100644 --- a/gnu/java/security/prng/EntropySource.java +++ b/gnu/java/security/prng/EntropySource.java @@ -43,7 +43,6 @@ package gnu.java.security.prng; */ public interface EntropySource { - /** * Returns the estimated quality of this source. This value should be * between 0 and 100 (the running quality is computed as a percentage, diff --git a/gnu/java/security/prng/IRandom.java b/gnu/java/security/prng/IRandom.java index 2c89e7ad5..66ad6d224 100644 --- a/gnu/java/security/prng/IRandom.java +++ b/gnu/java/security/prng/IRandom.java @@ -41,140 +41,134 @@ package gnu.java.security.prng; import java.util.Map; /** - * <p>The basic visible methods of any pseudo-random number generator.</p> - * - * <p>The [HAC] defines a PRNG (as implemented in this library) as follows:</p> - * + * The basic visible methods of any pseudo-random number generator. + * <p> + * The [HAC] defines a PRNG (as implemented in this library) as follows: * <ul> - * <li>"5.6 Definition: A pseudorandom bit generator (PRBG) is said to pass - * the <em>next-bit test</em> if there is no polynomial-time algorithm which, - * on input of the first <code>L</code> bits of an output sequence <code>S</code>, - * can predict the <code>(L+1)</code>st bit of <code>S</code> with a - * probability significantly grater than <code>1/2</code>."</li> - * - * <li>"5.8 Definition: A PRBG that passes the <em>next-bit test</em> - * (possibly under some plausible but unproved mathematical assumption such - * as the intractability of factoring integers) is called a - * <em>cryptographically secure pseudorandom bit generator</em> (CSPRBG)."</li> + * <li>"5.6 Definition: A pseudorandom bit generator (PRBG) is said to pass the + * <em>next-bit test</em> if there is no polynomial-time algorithm which, on + * input of the first <code>L</code> bits of an output sequence <code>S</code>, + * can predict the <code>(L+1)</code><sup>st</sup> bit of <code>S</code> with a + * probability significantly greater than <code>1/2</code>."</li> + * <li>"5.8 Definition: A PRBG that passes the <em>next-bit test</em> + * (possibly under some plausible but unproved mathematical assumption such as + * the intractability of factoring integers) is called a <em>cryptographically + * secure pseudorandom bit generator</em> (CSPRBG)."</li> * </ul> - * - * <p><b>IMPLEMENTATION NOTE</b>: Although all the concrete classes in this + * <p> + * <b>IMPLEMENTATION NOTE</b>: 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, <b>DOES NOT</b> 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 <b>same block size</b> but without any - * knowledge of neither key material nor key size.</p> - * - * <p>References:</p> - * + * the same cipher that operates with the <b>same block size</b> but without + * any knowledge of neither key material nor key size. + * <p> + * References: * <ol> - * <li><a href="http://www.cacr.math.uwaterloo.ca/hac">[HAC]</a>: Handbook of - * Applied Cryptography.<br> - * CRC Press, Inc. ISBN 0-8493-8523-7, 1997<br> - * Menezes, A., van Oorschot, P. and S. Vanstone.</li> + * <li><a href="http://www.cacr.math.uwaterloo.ca/hac">[HAC]</a>: Handbook of + * Applied Cryptography.<br> + * CRC Press, Inc. ISBN 0-8493-8523-7, 1997<br> + * Menezes, A., van Oorschot, P. and S. Vanstone.</li> * </ol> */ -public interface IRandom extends Cloneable +public interface IRandom + extends Cloneable { - - // Constants - // ------------------------------------------------------------------------- - - // Methods - // ------------------------------------------------------------------------- - /** - * <p>Returns the canonical name of this instance.</p> - * - * @return the canonical name of this instance. */ + * Returns the canonical name of this instance. + * + * @return the canonical name of this instance. + */ String name(); /** - * <p>Initialises the pseudo-random number generator scheme with the - * appropriate attributes.</p> - * + * Initialises the pseudo-random number generator scheme with the appropriate + * attributes. + * * @param attributes a set of name-value pairs that describe the desired - * future instance behaviour. + * future instance behaviour. * @exception IllegalArgumentException if at least one of the defined name/ - * value pairs contains invalid data. + * value pairs contains invalid data. */ void init(Map attributes); /** - * <p>Returns the next 8 bits of random data generated from this instance.</p> - * + * Returns the next 8 bits of random data generated from this instance. + * * @return the next 8 bits of random data generated from this instance. * @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. */ byte nextByte() throws IllegalStateException, LimitReachedException; /** - * <p>Fills the designated byte array, starting from byte at index - * <code>offset</code>, for a maximum of <code>length</code> bytes with the - * output of this generator instance. - * + * Fills the designated byte array, starting from byte at index + * <code>offset</code>, for a maximum of <code>length</code> bytes with + * the output of this generator instance. + * * @param out the placeholder to contain the generated random bytes. * @param offset the starting index in <i>out</i> to consider. This method - * does nothing if this parameter is not within <code>0</code> and - * <code>out.length</code>. - * @param length the maximum number of required random bytes. This method - * does nothing if this parameter is less than <code>1</code>. + * does nothing if this parameter is not within <code>0</code> and + * <code>out.length</code>. + * @param length the maximum number of required random bytes. This method does + * nothing if this parameter is less than <code>1</code>. * @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; /** - * <p>Supplement, or possibly replace, the random state of this PRNG with - * a random byte.</p> - * - * <p>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}.</p> - * + * Supplement, or possibly replace, the random state of this PRNG with a + * random byte. + * <p> + * 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); /** - * <p>Supplement, or possibly replace, the random state of this PRNG with - * a sequence of new random bytes.</p> - * - * <p>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}.</p> - * + * Supplement, or possibly replace, the random state of this PRNG with a + * sequence of new random bytes. + * <p> + * 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); /** - * <p>Supplement, or possibly replace, the random state of this PRNG with - * a sequence of new random bytes.</p> - * - * <p>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}.</p> - * + * Supplement, or possibly replace, the random state of this PRNG with a + * sequence of new random bytes. + * <p> + * 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 <i>offset</i>, <i>length</i>, - * or <i>offset</i>+<i>length</i> is out of bounds. + * @exception IndexOutOfBoundsException If <i>offset</i>, <i>length</i>, or + * <i>offset</i>+<i>length</i> is out of bounds. */ void addRandomBytes(byte[] in, int offset, int length); /** - * <p>Returns a clone copy of this instance.</p> - * + * Returns a clone copy of this instance. + * * @return a clone copy of this instance. */ Object clone() throws CloneNotSupportedException; -}
\ No newline at end of file +} diff --git a/gnu/java/security/prng/LimitReachedException.java b/gnu/java/security/prng/LimitReachedException.java index 2fd8bfa7f..8d5b30baf 100644 --- a/gnu/java/security/prng/LimitReachedException.java +++ b/gnu/java/security/prng/LimitReachedException.java @@ -42,15 +42,9 @@ package gnu.java.security.prng; * A checked exception that indicates that a pseudo random number generated has * reached its theoretical limit in generating random bytes. */ -public class LimitReachedException extends Exception +public class LimitReachedException + extends Exception { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - public LimitReachedException() { super(); @@ -60,10 +54,4 @@ public class LimitReachedException extends Exception { super(msg); } - - // Class methods - // ------------------------------------------------------------------------- - - // Instant methods - // ------------------------------------------------------------------------- -}
\ No newline at end of file +} diff --git a/gnu/java/security/prng/MDGenerator.java b/gnu/java/security/prng/MDGenerator.java index 073c559ae..574a2f9d6 100644 --- a/gnu/java/security/prng/MDGenerator.java +++ b/gnu/java/security/prng/MDGenerator.java @@ -45,19 +45,17 @@ import gnu.java.security.hash.IMessageDigest; import java.util.Map; /** - * <p>A simple pseudo-random number generator that relies on a hash algorithm, - * that (a) starts its operation by hashing a <code>seed</code>, 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 <code>seed</code>, 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 - * <code>seed</code> is given, an empty octet sequence is used.</p> + * <code>seed</code> 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/gnu/java/security/prng/PRNGFactory.java b/gnu/java/security/prng/PRNGFactory.java index 1699d9e7e..ae15d053b 100644 --- a/gnu/java/security/prng/PRNGFactory.java +++ b/gnu/java/security/prng/PRNGFactory.java @@ -45,56 +45,43 @@ import java.util.HashSet; import java.util.Set; /** - * <p>A Factory to instantiate pseudo random number generators.</p> + * 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 <i>Singleton</i> pattern. */ protected PRNGFactory() { } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns an instance of a padding algorithm given its name.</p> - * + * 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 final IRandom getInstance(String prng) { if (prng == null) - { - return null; - } + return null; prng = prng.trim(); IRandom result = null; if (prng.equalsIgnoreCase(MD_PRNG)) - { - result = new MDGenerator(); - } + result = new MDGenerator(); return result; } /** - * <p>Returns a {@link Set} of names of padding algorithms supported by this - * <i>Factory</i>.</p> - * + * Returns a {@link Set} of names of padding algorithms supported by this + * <i>Factory</i>. + * * @return a {@link Set} of pseudo-random number generator algorithm names - * (Strings). + * (Strings). */ public static final Set getNames() { @@ -102,7 +89,4 @@ public class PRNGFactory implements Registry hs.add(MD_PRNG); return Collections.unmodifiableSet(hs); } - - // Instance methods - // ------------------------------------------------------------------------- } diff --git a/gnu/java/security/prng/RandomEvent.java b/gnu/java/security/prng/RandomEvent.java index c07062125..fc4607a8a 100644 --- a/gnu/java/security/prng/RandomEvent.java +++ b/gnu/java/security/prng/RandomEvent.java @@ -41,12 +41,11 @@ package gnu.java.security.prng; import java.util.EventObject; /** - * An interface for entropy accumulators that will be notified of random - * events. + * A type for entropy accumulators that will be notified of random events. */ -public class RandomEvent extends EventObject +public class RandomEvent + extends EventObject { - private final byte sourceNumber; private final byte poolNumber; @@ -61,7 +60,7 @@ public class RandomEvent extends EventObject this.poolNumber = poolNumber; if (data.length == 0 || data.length > 32) throw new IllegalArgumentException( - "random events take between 1 and 32 bytes of data"); + "random events take between 1 and 32 bytes of data"); this.data = (byte[]) data.clone(); } @@ -79,4 +78,4 @@ public class RandomEvent extends EventObject { return data; } -}
\ No newline at end of file +} diff --git a/gnu/java/security/prng/RandomEventListener.java b/gnu/java/security/prng/RandomEventListener.java index 1dc14619f..beb9087f4 100644 --- a/gnu/java/security/prng/RandomEventListener.java +++ b/gnu/java/security/prng/RandomEventListener.java @@ -41,10 +41,10 @@ package gnu.java.security.prng; import java.util.EventListener; /** - * An interface for entropy accumulators that will be notified of random - * events. + * An interface for entropy accumulators that will be notified of random events. */ -public interface RandomEventListener extends EventListener +public interface RandomEventListener + extends EventListener { void addRandomEvent(RandomEvent event); -}
\ No newline at end of file +} diff --git a/gnu/java/security/provider/Gnu.java b/gnu/java/security/provider/Gnu.java index 6ea96c1e4..62bb0a29e 100644 --- a/gnu/java/security/provider/Gnu.java +++ b/gnu/java/security/provider/Gnu.java @@ -42,12 +42,16 @@ import java.security.AccessController; import java.security.PrivilegedAction; import java.security.Provider; -public final class Gnu extends Provider +public final class Gnu + extends Provider { public Gnu() { - super("GNU", 1.0, "GNU provider v1.0 implementing SHA-1, MD5, DSA, RSA, X.509 Certificates and CRLs, PKIX certificate path validators, Collection cert stores, Diffie-Hellman key agreement and key pair generator"); - + super("GNU", 1.0, + "GNU provider v1.0 implementing SHA-1, MD5, DSA, RSA, X.509 " + + "Certificates and CRLs, PKIX certificate path validators, " + + "Collection cert stores, Diffie-Hellman key agreement and " + + "key pair generator"); AccessController.doPrivileged (new PrivilegedAction() { public Object run() @@ -163,29 +167,41 @@ public final class Gnu extends Provider put("Alg.Alias.KeyFactory.PKCS#8", "Encoded"); put("Alg.Alias.KeyFactory.PKCS8", "Encoded"); - put("MessageDigest.HAVAL", gnu.java.security.jce.hash.HavalSpi.class.getName()); + put("MessageDigest.HAVAL", + gnu.java.security.jce.hash.HavalSpi.class.getName()); put("MessageDigest.HAVAL ImplementedIn", "Software"); - put("MessageDigest.MD2", gnu.java.security.jce.hash.MD2Spi.class.getName()); + put("MessageDigest.MD2", + gnu.java.security.jce.hash.MD2Spi.class.getName()); put("MessageDigest.MD2 ImplementedIn", "Software"); - put("MessageDigest.MD4", gnu.java.security.jce.hash.MD4Spi.class.getName()); + put("MessageDigest.MD4", + gnu.java.security.jce.hash.MD4Spi.class.getName()); put("MessageDigest.MD4 ImplementedIn", "Software"); - put("MessageDigest.MD5", gnu.java.security.jce.hash.MD5Spi.class.getName()); + put("MessageDigest.MD5", + gnu.java.security.jce.hash.MD5Spi.class.getName()); put("MessageDigest.MD5 ImplementedIn", "Software"); - put("MessageDigest.RIPEMD128", gnu.java.security.jce.hash.RipeMD128Spi.class.getName()); + put("MessageDigest.RIPEMD128", + gnu.java.security.jce.hash.RipeMD128Spi.class.getName()); put("MessageDigest.RIPEMD128 ImplementedIn", "Software"); - put("MessageDigest.RIPEMD160", gnu.java.security.jce.hash.RipeMD160Spi.class.getName()); + put("MessageDigest.RIPEMD160", + gnu.java.security.jce.hash.RipeMD160Spi.class.getName()); put("MessageDigest.RIPEMD160 ImplementedIn", "Software"); - put("MessageDigest.SHA-160", gnu.java.security.jce.hash.Sha160Spi.class.getName()); + put("MessageDigest.SHA-160", + gnu.java.security.jce.hash.Sha160Spi.class.getName()); put("MessageDigest.SHA-160 ImplementedIn", "Software"); - put("MessageDigest.SHA-256", gnu.java.security.jce.hash.Sha256Spi.class.getName()); + put("MessageDigest.SHA-256", + gnu.java.security.jce.hash.Sha256Spi.class.getName()); put("MessageDigest.SHA-256 ImplementedIn", "Software"); - put("MessageDigest.SHA-384", gnu.java.security.jce.hash.Sha384Spi.class.getName()); + put("MessageDigest.SHA-384", + gnu.java.security.jce.hash.Sha384Spi.class.getName()); put("MessageDigest.SHA-384 ImplementedIn", "Software"); - put("MessageDigest.SHA-512", gnu.java.security.jce.hash.Sha512Spi.class.getName()); + put("MessageDigest.SHA-512", + gnu.java.security.jce.hash.Sha512Spi.class.getName()); put("MessageDigest.SHA-512 ImplementedIn", "Software"); - put("MessageDigest.TIGER", gnu.java.security.jce.hash.TigerSpi.class.getName()); + put("MessageDigest.TIGER", + gnu.java.security.jce.hash.TigerSpi.class.getName()); put("MessageDigest.TIGER ImplementedIn", "Software"); - put("MessageDigest.WHIRLPOOL", gnu.java.security.jce.hash.WhirlpoolSpi.class.getName()); + put("MessageDigest.WHIRLPOOL", + gnu.java.security.jce.hash.WhirlpoolSpi.class.getName()); put("MessageDigest.WHIRLPOOL ImplementedIn", "Software"); put("Alg.Alias.MessageDigest.SHS", "SHA-160"); @@ -224,29 +240,41 @@ public final class Gnu extends Provider put("SecureRandom.SHA1PRNG", gnu.java.security.jce.prng.Sha160RandomSpi.class.getName()); - put("SecureRandom.MD2PRNG", gnu.java.security.jce.prng.MD2RandomSpi.class.getName()); + put("SecureRandom.MD2PRNG", + gnu.java.security.jce.prng.MD2RandomSpi.class.getName()); put("SecureRandom.MD2PRNG ImplementedIn", "Software"); - put("SecureRandom.MD4PRNG", gnu.java.security.jce.prng.MD4RandomSpi.class.getName()); + put("SecureRandom.MD4PRNG", + gnu.java.security.jce.prng.MD4RandomSpi.class.getName()); put("SecureRandom.MD4PRNG ImplementedIn", "Software"); - put("SecureRandom.MD5PRNG", gnu.java.security.jce.prng.MD5RandomSpi.class.getName()); + put("SecureRandom.MD5PRNG", + gnu.java.security.jce.prng.MD5RandomSpi.class.getName()); put("SecureRandom.MD5PRNG ImplementedIn", "Software"); - put("SecureRandom.RIPEMD128PRNG", gnu.java.security.jce.prng.RipeMD128RandomSpi.class.getName()); + put("SecureRandom.RIPEMD128PRNG", + gnu.java.security.jce.prng.RipeMD128RandomSpi.class.getName()); put("SecureRandom.RIPEMD128PRNG ImplementedIn", "Software"); - put("SecureRandom.RIPEMD160PRNG", gnu.java.security.jce.prng.RipeMD160RandomSpi.class.getName()); + put("SecureRandom.RIPEMD160PRNG", + gnu.java.security.jce.prng.RipeMD160RandomSpi.class.getName()); put("SecureRandom.RIPEMD160PRNG ImplementedIn", "Software"); - put("SecureRandom.SHA-160PRNG", gnu.java.security.jce.prng.Sha160RandomSpi.class.getName()); + put("SecureRandom.SHA-160PRNG", + gnu.java.security.jce.prng.Sha160RandomSpi.class.getName()); put("SecureRandom.SHA-160PRNG ImplementedIn", "Software"); - put("SecureRandom.SHA-256PRNG", gnu.java.security.jce.prng.Sha256RandomSpi.class.getName()); + put("SecureRandom.SHA-256PRNG", + gnu.java.security.jce.prng.Sha256RandomSpi.class.getName()); put("SecureRandom.SHA-256PRNG ImplementedIn", "Software"); - put("SecureRandom.SHA-384PRNG", gnu.java.security.jce.prng.Sha384RandomSpi.class.getName()); + put("SecureRandom.SHA-384PRNG", + gnu.java.security.jce.prng.Sha384RandomSpi.class.getName()); put("SecureRandom.SHA-384PRNG ImplementedIn", "Software"); - put("SecureRandom.SHA-512PRNG", gnu.java.security.jce.prng.Sha512RandomSpi.class.getName()); + put("SecureRandom.SHA-512PRNG", + gnu.java.security.jce.prng.Sha512RandomSpi.class.getName()); put("SecureRandom.SHA-512PRNG ImplementedIn", "Software"); - put("SecureRandom.TIGERPRNG", gnu.java.security.jce.prng.TigerRandomSpi.class.getName()); + put("SecureRandom.TIGERPRNG", + gnu.java.security.jce.prng.TigerRandomSpi.class.getName()); put("SecureRandom.TIGERPRNG ImplementedIn", "Software"); - put("SecureRandom.HAVALPRNG", gnu.java.security.jce.prng.HavalRandomSpi.class.getName()); + put("SecureRandom.HAVALPRNG", + gnu.java.security.jce.prng.HavalRandomSpi.class.getName()); put("SecureRandom.HAVALPRNG ImplementedIn", "Software"); - put("SecureRandom.WHIRLPOOLPRNG", gnu.java.security.jce.prng.WhirlpoolRandomSpi.class.getName()); + put("SecureRandom.WHIRLPOOLPRNG", + gnu.java.security.jce.prng.WhirlpoolRandomSpi.class.getName()); put("SecureRandom.WHIRLPOOLPRNG ImplementedIn", "Software"); put("Alg.Alias.SecureRandom.SHA-1PRNG", "SHA-160PRNG"); diff --git a/gnu/java/security/provider/PKIXCertPathValidatorImpl.java b/gnu/java/security/provider/PKIXCertPathValidatorImpl.java index 3680f2fae..430b51b13 100644 --- a/gnu/java/security/provider/PKIXCertPathValidatorImpl.java +++ b/gnu/java/security/provider/PKIXCertPathValidatorImpl.java @@ -85,51 +85,45 @@ import java.util.Set; import java.util.logging.Logger; /** - * An implementation of the Public Key Infrastructure's X.509 - * certificate path validation algorithm. - * - * <p>See <a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280: - * Internet X.509 Public Key Infrastructure Certificate and - * Certificate Revocation List (CRL) Profile</a>. - * + * An implementation of the Public Key Infrastructure's X.509 certificate path + * validation algorithm. + * <p> + * See <a href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280: Internet X.509 + * Public Key Infrastructure Certificate and Certificate Revocation List (CRL) + * Profile</a>. + * * @author Casey Marshall (rsdio@metastatic.org) */ -public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi +public class PKIXCertPathValidatorImpl + extends CertPathValidatorSpi { private static final Logger log = Logger.getLogger(PKIXCertPathValidatorImpl.class.getName()); - public static final String ANY_POLICY = "2.5.29.32.0"; - // Constructor. - // ------------------------------------------------------------------------- + public static final String ANY_POLICY = "2.5.29.32.0"; 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); @@ -152,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(); @@ -170,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 { @@ -180,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) { @@ -204,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) @@ -228,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. @@ -274,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 @@ -289,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; @@ -330,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; @@ -350,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 @@ -364,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 @@ -381,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()); @@ -396,34 +381,29 @@ 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. - * - * <p>The CRL is accepted iff:</p> - * + * Check if a given CRL is acceptable for checking the revocation status of + * certificates in the path being checked. + * <p> + * The CRL is accepted iff: * <ol> * <li>The <i>nextUpdate</i> field (if present) is in the future.</li> * <li>The CRL does not contain any unsupported critical extensions.</li> * <li>The CRL is signed by one of the certificates in the path, or,</li> - * <li>The CRL is signed by the given public key and was issued by the - * public key's subject, or,</li> - * <li>The CRL is signed by a certificate in the given cert stores, and - * that cert is signed by one of the certificates in the path.</li> + * <li>The CRL is signed by the given public key and was issued by the public + * key's subject, or,</li> + * <li>The CRL is signed by a certificate in the given cert stores, and that + * cert is signed by one of the certificates in the path.</li> * </ol> - * + * * @param crl The CRL being checked. * @param path The path this CRL is being checked against. * @param now The value to use as 'now'. @@ -431,9 +411,9 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi * @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) @@ -442,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 @@ -466,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); @@ -481,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 @@ -492,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 @@ -534,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()); } } @@ -550,13 +530,13 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi * Perform a basic sanity check on the CA certificate at <code>index</code>. */ 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; @@ -577,23 +557,27 @@ 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 (Configuration.DEBUG) log.fine("updatePolicyTree depth == " + depth); @@ -624,7 +608,7 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi } } } - while (!stack.isEmpty()); + while (! stack.isEmpty()); Extension e = null; CertificatePolicies policies = null; @@ -647,18 +631,18 @@ public class PKIXCertPathValidatorImpl extends CertPathValidatorSpi log.fine("nodes are == " + nodes); log.fine("cert policies are == " + cp); } - for (Iterator it = nodes.iterator(); it.hasNext(); ) + for (Iterator it = nodes.iterator(); it.hasNext();) { PolicyNodeImpl parent = (PolicyNodeImpl) it.next(); if (Configuration.DEBUG) log.fine("adding policies to " + parent); - for (Iterator it2 = cp.iterator(); it2.hasNext(); ) + for (Iterator it2 = cp.iterator(); it2.hasNext();) { OID policy = (OID) it2.next(); if (Configuration.DEBUG) log.fine("trying to add policy == " + policy); - if (policy.toString().equals(ANY_POLICY) && - params.isAnyPolicyInhibited()) + if (policy.toString().equals(ANY_POLICY) + && params.isAnyPolicyInhibited()) continue; PolicyNodeImpl child = new PolicyNodeImpl(); child.setValidPolicy(policy.toString()); @@ -673,28 +657,28 @@ 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 (Configuration.DEBUG) log.fine("checkExplicitPolicy depth=" + depth); - for (Iterator it = explicitPolicies.iterator(); it.hasNext(); ) + for (Iterator it = explicitPolicies.iterator(); it.hasNext();) { int[] i = (int[]) it.next(); int caDepth = i[0]; diff --git a/gnu/java/security/provider/X509CertificateFactory.java b/gnu/java/security/provider/X509CertificateFactory.java index 1a415eabb..7d61779f9 100644 --- a/gnu/java/security/provider/X509CertificateFactory.java +++ b/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/gnu/java/security/sig/BaseSignature.java b/gnu/java/security/sig/BaseSignature.java index dd964d481..9c76cacba 100644 --- a/gnu/java/security/sig/BaseSignature.java +++ b/gnu/java/security/sig/BaseSignature.java @@ -49,15 +49,11 @@ import java.util.Map; import java.util.Random; /** - * <p>A base abstract class to facilitate implementations of concrete - * Signatures.</p> + * A base abstract class to facilitate implementations of concrete Signatures. */ -public abstract class BaseSignature implements ISignature +public abstract class BaseSignature + implements ISignature { - - // Constants and variables - // ------------------------------------------------------------------------- - /** The canonical name of this signature scheme. */ protected String schemeName; @@ -79,9 +75,6 @@ public abstract class BaseSignature implements ISignature /** Our default source of randomness. */ private PRNG prng = null; - // Constructor(s) - // ------------------------------------------------------------------------- - /** * Trivial constructor. * @@ -101,14 +94,6 @@ public abstract class BaseSignature implements ISignature this.md = md; } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // gnu.crypto.sig.ISignature interface implementation ---------------------- - public String name() { return schemeName + "-" + md.name(); @@ -117,51 +102,41 @@ public abstract class BaseSignature implements ISignature public void setupVerify(Map attributes) throws IllegalArgumentException { setup(attributes); - // do we have a public key? PublicKey key = (PublicKey) attributes.get(VERIFIER_KEY); if (key != null) - { - setupForVerification(key); - } + setupForVerification(key); } public void setupSign(Map attributes) throws IllegalArgumentException { setup(attributes); - // do we have a private key? PrivateKey key = (PrivateKey) attributes.get(SIGNER_KEY); if (key != null) - { - setupForSigning(key); - } + setupForSigning(key); } public void update(byte b) { if (md == null) - { - throw new IllegalStateException(); - } + throw new IllegalStateException(); + md.update(b); } public void update(byte[] b, int off, int len) { if (md == null) - { - throw new IllegalStateException(); - } + throw new IllegalStateException(); + md.update(b, off, len); } public Object sign() { if (md == null || privateKey == null) - { - throw new IllegalStateException(); - } + throw new IllegalStateException(); return generateSignature(); } @@ -169,15 +144,11 @@ public abstract class BaseSignature implements ISignature public boolean verify(Object sig) { if (md == null || publicKey == null) - { - throw new IllegalStateException(); - } + throw new IllegalStateException(); return verifySignature(sig); } - // abstract methods to be implemented by concrete subclasses --------------- - public abstract Object clone(); protected abstract void setupForVerification(PublicKey key) @@ -191,8 +162,6 @@ public abstract class BaseSignature implements ISignature protected abstract boolean verifySignature(Object signature) throws IllegalStateException; - // Other instance methods -------------------------------------------------- - /** Initialises the internal fields of this instance. */ protected void init() { @@ -204,33 +173,27 @@ public abstract class BaseSignature implements ISignature } /** - * <p>Fills the designated byte array with random data.</p> - * + * Fills the designated byte array with random data. + * * @param buffer the byte array to fill with random data. */ protected void nextRandomBytes(byte[] buffer) { if (rnd != null) - { - rnd.nextBytes(buffer); - } + rnd.nextBytes(buffer); else if (irnd != null) - { - try - { - irnd.nextBytes(buffer, 0, buffer.length); - } - catch (IllegalStateException x) - { - throw new RuntimeException("nextRandomBytes(): " - + String.valueOf(x)); - } - catch (LimitReachedException x) - { - throw new RuntimeException("nextRandomBytes(): " - + String.valueOf(x)); - } - } + try + { + irnd.nextBytes(buffer, 0, buffer.length); + } + catch (IllegalStateException x) + { + throw new RuntimeException("nextRandomBytes(): " + x); + } + catch (LimitReachedException x) + { + throw new RuntimeException("nextRandomBytes(): " + x); + } else getDefaultPRNG().nextBytes(buffer); } @@ -238,17 +201,12 @@ public abstract class BaseSignature implements ISignature private void setup(Map attributes) { init(); - // do we have a Random or SecureRandom, or should we use our own? Object obj = attributes.get(SOURCE_OF_RANDOMNESS); if (obj instanceof Random) - { - rnd = (Random) obj; - } + rnd = (Random) obj; else if (obj instanceof IRandom) - { - irnd = (IRandom) obj; - } + irnd = (IRandom) obj; } private PRNG getDefaultPRNG() diff --git a/gnu/java/security/sig/ISignature.java b/gnu/java/security/sig/ISignature.java index 9ad853a29..ff25f29d9 100644 --- a/gnu/java/security/sig/ISignature.java +++ b/gnu/java/security/sig/ISignature.java @@ -41,28 +41,24 @@ package gnu.java.security.sig; import java.util.Map; /** - * <p>The visible methods of every signature-with-appendix scheme.</p> - * - * <p>The Handbook of Applied Cryptography (HAC), by A. Menezes & al. states: + * The visible methods of every signature-with-appendix scheme. + * <p> + * 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 <i>digital signature schemes with - * appendix</i>. ... They rely on cryptographic hash functions rather than - * customised redundancy functions, and are less prone to existential forgery - * attacks."</p> - * - * <p>References:</p> + * verification algorithm are called <i>digital signature schemes with appendix</i>. + * ... They rely on cryptographic hash functions rather than customised + * redundancy functions, and are less prone to existential forgery attacks." + * <p> + * References: * <ol> - * <li><a href="http://www.cacr.math.uwaterloo.ca/hac/">Handbook of Applied - * Cryptography</a>, Alfred J. Menezes, Paul C. van Oorschot and Scott A. - * Vanstone. Section 11.2.2 Digital signature schemes with appendix.</li> + * <li><a href="http://www.cacr.math.uwaterloo.ca/hac/">Handbook of Applied + * Cryptography</a>, Alfred J. Menezes, Paul C. van Oorschot and Scott A. + * Vanstone. Section 11.2.2 Digital signature schemes with appendix.</li> * </ol> */ -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.java.security.prng.IRandom} instance to - * use. The default is to use a classloader singleton from + * {@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 - // ------------------------------------------------------------------------- - /** - * <p>Returns the canonical name of this signature scheme.</p> - * + * Returns the canonical name of this signature scheme. + * * @return the canonical name of this instance. */ String name(); /** - * <p>Initialises this instance for signature verification.</p> - * + * Initialises this instance for signature verification. + * * @param attributes the attributes to use for setting up this instance. * @throws IllegalArgumentException if the designated public key is not - * appropriate for this signature scheme. + * appropriate for this signature scheme. * @see #SOURCE_OF_RANDOMNESS * @see #VERIFIER_KEY */ void setupVerify(Map attributes) throws IllegalArgumentException; /** - * <p>Initialises this instance for signature generation.</p> - * + * Initialises this instance for signature generation. + * * @param attributes the attributes to use for setting up this instance. * @throws IllegalArgumentException if the designated private key is not - * appropriate for this signature scheme. + * appropriate for this signature scheme. * @see #SOURCE_OF_RANDOMNESS * @see #SIGNER_KEY */ void setupSign(Map attributes) throws IllegalArgumentException; /** - * <p>Digests one byte of a message for signing or verification purposes.</p> - * + * Digests one byte of a message for signing or verification purposes. + * * @param b the message byte to digest. - * @throws IllegalStateException if this instance was not setup for - * signature generation/verification. + * @throws IllegalStateException if this instance was not setup for signature + * generation/verification. */ void update(byte b) throws IllegalStateException; /** - * <p>Digests a sequence of bytes from a message for signing or verification - * purposes.</p> - * + * Digests a sequence of bytes from a message for signing or verification + * purposes. + * * @param buffer the byte sequence to consider. * @param offset the byte poisition in <code>buffer</code> of the first byte - * to consider. - * @param length the number of bytes in <code>buffer</code> starting from the - * byte at index <code>offset</code> to digest. - * @throws IllegalStateException if this instance was not setup for - * signature generation/verification. + * to consider. + * @param length the number of bytes in <code>buffer</code> starting from + * the byte at index <code>offset</code> to digest. + * @throws IllegalStateException if this instance was not setup for signature + * generation/verification. */ void update(byte[] buffer, int offset, int length) throws IllegalStateException; /** - * <p>Terminates a signature generation phase by digesting and processing the - * context of the underlying message digest algorithm instance.</p> - * + * Terminates a signature generation phase by digesting and processing the + * context of the underlying message digest algorithm instance. + * * @return a {@link Object} representing the native output of the signature - * scheme implementation. - * @throws IllegalStateException if this instance was not setup for - * signature generation. + * scheme implementation. + * @throws IllegalStateException if this instance was not setup for signature + * generation. */ Object sign() throws IllegalStateException; /** - * <p>Terminates a signature verification phase by digesting and processing - * the context of the underlying message digest algorithm instance.</p> - * + * Terminates a signature verification phase by digesting and processing the + * context of the underlying message digest algorithm instance. + * * @param signature a native signature object previously generated by an - * invocation of the <code>sign()</code> method. + * invocation of the <code>sign()</code> method. * @return <code>true</code> 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; /** - * <p>Returns a clone copy of this instance.</p> - * + * Returns a clone copy of this instance. + * * @return a clone copy of this instance. */ Object clone(); diff --git a/gnu/java/security/sig/ISignatureCodec.java b/gnu/java/security/sig/ISignatureCodec.java index b6ab0ba9b..aaae6ccb0 100644 --- a/gnu/java/security/sig/ISignatureCodec.java +++ b/gnu/java/security/sig/ISignatureCodec.java @@ -41,23 +41,16 @@ package gnu.java.security.sig; import gnu.java.security.Registry; /** - * <p>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.</p> + * creating their internal Java representation from external sources. */ public interface ISignatureCodec { - - // Constants - // ------------------------------------------------------------------------- - /** Constant identifying the <i>Raw</i> encoding format. */ int RAW_FORMAT = Registry.RAW_ENCODING_ID; - // Method(s) - // ------------------------------------------------------------------------- - int getFormatID(); byte[] encodeSignature(Object signature); diff --git a/gnu/java/security/sig/SignatureFactory.java b/gnu/java/security/sig/SignatureFactory.java index d5bd728ad..28b68925b 100644 --- a/gnu/java/security/sig/SignatureFactory.java +++ b/gnu/java/security/sig/SignatureFactory.java @@ -53,38 +53,28 @@ public class SignatureFactory { private static Set names; - // Constructor(s) - // ------------------------------------------------------------------------- - /** Trivial constructor to enforce Singleton pattern. */ private SignatureFactory() { super(); } - // Class methods - // ------------------------------------------------------------------------- - /** * Returns an instance of a signature-with-appendix scheme given its name. - * + * * @param ssa the case-insensitive signature-with-appendix scheme name. * @return an instance of the scheme, or <code>null</code> 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 <i>Factory</i>. - * + * Returns a {@link Set} of signature-with-appendix scheme names supported by + * this <i>Factory</i>. + * * @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/gnu/java/security/sig/dss/DSSSignature.java b/gnu/java/security/sig/dss/DSSSignature.java index 370a93854..1ef1bea1a 100644 --- a/gnu/java/security/sig/dss/DSSSignature.java +++ b/gnu/java/security/sig/dss/DSSSignature.java @@ -55,72 +55,65 @@ import java.util.Map; import java.util.Random; /** - * <p>The DSS (Digital Signature Standard) algorithm makes use of the following - * parameters:</p> - * + * The DSS (Digital Signature Standard) algorithm makes use of the following + * parameters: * <ol> - * <li>p: A prime modulus, where <code>2<sup>L-1</sup> < p < 2<sup>L</sup> - * </code> for <code>512 <= L <= 1024</code> and <code>L</code> a - * multiple of <code>64</code>.</li> - * <li>q: A prime divisor of <code>p - 1</code>, where <code>2<sup>159</sup> + * <li>p: A prime modulus, where + * <code>2<sup>L-1</sup> < p < 2<sup>L</sup> </code> for <code>512 <= L + * <= 1024</code> and <code>L</code> a multiple of <code>64</code>.</li> + * <li>q: A prime divisor of <code>p - 1</code>, where <code>2<sup>159</sup> * < q < 2<sup>160</sup></code>.</li> - * <li>g: Where <code>g = h<sup>(p-1)</sup>/q mod p</code>, where - * <code>h</code> is any integer with <code>1 < h < p - 1</code> such - * that <code>h<sup> (p-1)</sup>/q mod p > 1</code> (<code>g</code> has order - * <code>q mod p</code>).</li> - * <li>x: A randomly or pseudorandomly generated integer with <code>0 < x + * <li>g: Where <code>g = h<sup>(p-1)</sup>/q mod p</code>, where + * <code>h</code> is any integer with <code>1 < h < p - 1</code> such + * that <code>h<sup> (p-1)</sup>/q mod p > 1</code> (<code>g</code> has order + * <code>q mod p</code>).</li> + * <li>x: A randomly or pseudorandomly generated integer with <code>0 < x * < q</code>.</li> - * <li>y: <code>y = g<sup>x</sup> mod p</code>.</li> - * <li>k: A randomly or pseudorandomly generated integer with <code>0 < k + * <li>y: <code>y = g<sup>x</sup> mod p</code>.</li> + * <li>k: A randomly or pseudorandomly generated integer with <code>0 < k * < q</code>.</li> * </ol> - * - * <p>The integers <code>p</code>, <code>q</code>, and <code>g</code> can be + * <p> + * The integers <code>p</code>, <code>q</code>, and <code>g</code> can be * public and can be common to a group of users. A user's private and public - * keys are <code>x</code> and <code>y</code>, respectively. They are normally - * fixed for a period of time. Parameters <code>x</code> and <code>k</code> are - * used for signature generation only, and must be kept secret. Parameter - * <code>k</code> must be regenerated for each signature.</p> - * - * <p>The signature of a message <code>M</code> is the pair of numbers <code>r</code> - * and <code>s</code> computed according to the equations below:</p> - * + * keys are <code>x</code> and <code>y</code>, respectively. They are + * normally fixed for a period of time. Parameters <code>x</code> and + * <code>k</code> are used for signature generation only, and must be kept + * secret. Parameter <code>k</code> must be regenerated for each signature. + * <p> + * The signature of a message <code>M</code> is the pair of numbers + * <code>r</code> and <code>s</code> computed according to the equations below: * <ul> - * <li><code>r = (g<sup>k</sup> mod p) mod q</code> and</li> - * <li><code>s = (k<sup>-1</sup>(SHA(M) + xr)) mod q</code>.</li> + * <li><code>r = (g<sup>k</sup> mod p) mod q</code> and</li> + * <li><code>s = (k<sup>-1</sup>(SHA(M) + xr)) mod q</code>.</li> * </ul> - * - * <p>In the above, <code>k<sup>-1</sup></code> is the multiplicative inverse of - * <code>k</code>, <code>mod q</code>; i.e., <code>(k<sup>-1</sup> k) mod q = 1 - * </code> and <code>0 < k-1 < q</code>. The value of <code>SHA(M)</code> - * is a 160-bit string output by the Secure Hash Algorithm specified in FIPS 180. - * For use in computing <code>s</code>, this string must be converted to an - * integer.</p> - * - * <p>As an option, one may wish to check if <code>r == 0</code> or <code>s == 0 - * </code>. If either <code>r == 0</code> or <code>s == 0</code>, a new value - * of <code>k</code> should be generated and the signature should be - * recalculated (it is extremely unlikely that <code>r == 0</code> or <code>s == - * 0</code> if signatures are generated properly).</p> - * - * <p>The signature is transmitted along with the message to the verifier.</p> - * - * <p>References:</p> + * <p> + * In the above, <code>k<sup>-1</sup></code> is the multiplicative inverse of + * <code>k</code>, <code>mod q</code>; i.e., <code>(k<sup>-1</sup> k) mod q = + * 1</code> and <code>0 < k-1 < q</code>. The value of <code>SHA(M)</code> + * is a 160-bit string output by the Secure Hash Algorithm specified in FIPS + * 180. For use in computing <code>s</code>, this string must be converted to + * an integer. + * <p> + * As an option, one may wish to check if <code>r == 0</code> or <code>s == 0 + * </code>. + * If either <code>r == 0</code> or <code>s == 0</code>, a new value of + * <code>k</code> should be generated and the signature should be recalculated + * (it is extremely unlikely that <code>r == 0</code> or <code>s == 0</code> if + * signatures are generated properly). + * <p> + * The signature is transmitted along with the message to the verifier. + * <p> + * References: * <ol> - * <li><a href="http://www.itl.nist.gov/fipspubs/fip186.htm">Digital - * Signature Standard (DSS)</a>, Federal Information Processing Standards - * Publication 186. National Institute of Standards and Technology.</li> + * <li><a href="http://www.itl.nist.gov/fipspubs/fip186.htm">Digital Signature + * Standard (DSS)</a>, Federal Information Processing Standards Publication + * 186. National Institute of Standards and Technology.</li> * </ol> */ -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.<p> - * + * Returns the output of a signature generation phase. + * * @return an object encapsulating the DSS signature pair <code>r</code> and - * <code>s</code>. + * <code>s</code>. */ 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}.<p> - * + * Returns the output of a previously generated signature object as a pair of + * {@link java.math.BigInteger}. + * * @return the DSS signature pair <code>r</code> and <code>s</code>. */ 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/gnu/java/security/sig/dss/DSSSignatureRawCodec.java b/gnu/java/security/sig/dss/DSSSignatureRawCodec.java index b0590a573..903d7aad6 100644 --- a/gnu/java/security/sig/dss/DSSSignatureRawCodec.java +++ b/gnu/java/security/sig/dss/DSSSignatureRawCodec.java @@ -45,61 +45,46 @@ import java.io.ByteArrayOutputStream; import java.math.BigInteger; /** - * <p>An object that implements the {@link ISignatureCodec} operations for the - * <i>Raw</i> format to use with DSS signatures.</p> + * An object that implements the {@link ISignatureCodec} operations for the + * <i>Raw</i> format to use with DSS signatures. */ -public class DSSSignatureRawCodec implements ISignatureCodec +public class DSSSignatureRawCodec + implements ISignatureCodec { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - - // implicit 0-arguments constructor - - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // gnu.crypto.sig.ISignatureCodec interface implementation ----------------- - public int getFormatID() { return RAW_FORMAT; } /** - * <p>Returns the encoded form of the designated DSS (Digital Signature - * Standard) signature object according to the <i>Raw</i> format supported by - * this library.</p> - * - * <p>The <i>Raw</i> format for a DSA signature, in this implementation, is a - * byte sequence consisting of the following:</p> - * + * Returns the encoded form of the designated DSS (Digital Signature Standard) + * signature object according to the <i>Raw</i> format supported by this + * library. + * <p> + * The <i>Raw</i> format for a DSA signature, in this implementation, is a + * byte sequence consisting of the following: * <ol> - * <li>4-byte magic consisting of the value of the literal - * {@link Registry#MAGIC_RAW_DSS_SIGNATURE},</li> - * <li>1-byte version consisting of the constant: 0x01,</li> - * <li>4-byte count of following bytes representing the DSS parameter - * <code>r</code> in internet order,</li> - * <li>n-bytes representation of a {@link BigInteger} obtained by invoking - * the <code>toByteArray()</code> method on the DSS parameter <code>r</code>,</li> - * <li>4-byte count of following bytes representing the DSS parameter - * <code>s</code>,</li> - * <li>n-bytes representation of a {@link BigInteger} obtained by invoking - * the <code>toByteArray()</code> method on the DSS parameter <code>s</code>.</li> + * <li>4-byte magic consisting of the value of the literal + * {@link Registry#MAGIC_RAW_DSS_SIGNATURE},</li> + * <li>1-byte version consisting of the constant: 0x01,</li> + * <li>4-byte count of following bytes representing the DSS parameter + * <code>r</code> in internet order,</li> + * <li>n-bytes representation of a {@link BigInteger} obtained by invoking + * the <code>toByteArray()</code> method on the DSS parameter <code>r</code>, + * </li> + * <li>4-byte count of following bytes representing the DSS parameter + * <code>s</code>,</li> + * <li>n-bytes representation of a {@link BigInteger} obtained by invoking + * the <code>toByteArray()</code> method on the DSS parameter <code>s</code>. + * </li> * </ol> - * + * * @param signature the signature to encode, consisting of the two DSS - * parameters <code>r</code> and <code>s</code> as a {@link java.math.BigInteger} - * array. + * parameters <code>r</code> and <code>s</code> as a + * {@link BigInteger} array. * @return the <i>Raw</i> 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/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java b/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java index efe580d51..39de01f02 100644 --- a/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java +++ b/gnu/java/security/sig/rsa/EME_PKCS1_V1_5.java @@ -47,25 +47,21 @@ import java.security.interfaces.RSAKey; import java.util.Random; /** - * <p>An implementation of the EME-PKCS1-V1.5 encoding and decoding methods.</p> - * - * <p>EME-PKCS1-V1.5 is parameterised by the entity <code>k</code> which is the - * byte count of an RSA public shared modulus.</p> - * - * <p>References:</p> + * An implementation of the EME-PKCS1-V1.5 encoding and decoding methods. + * <p> + * EME-PKCS1-V1.5 is parameterised by the entity <code>k</code> which is the + * byte count of an RSA public shared modulus. + * <p> + * References: * <ol> - * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography - * Standards (PKCS) #1:</a><br> - * RSA Cryptography Specifications Version 2.1.<br> - * Jakob Jonsson and Burt Kaliski.</li> + * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography + * Standards (PKCS) #1:</a><br> + * RSA Cryptography Specifications Version 2.1.<br> + * Jakob Jonsson and Burt Kaliski.</li> * </ol> */ 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 - // ------------------------------------------------------------------------- - /** - * <p>Generates an octet string <code>PS</code> of length <code>k - mLen - - * 3</code> consisting of pseudo-randomly generated nonzero octets. The - * length of <code>PS</code> will be at least eight octets.</p> - * - * <p>The method then concatenates <code>PS</code>, the message <code>M</code>, + * Generates an octet string <code>PS</code> of length <code>k - mLen - + * 3</code> consisting of pseudo-randomly generated nonzero octets. The length + * of <code>PS</code> will be at least eight octets. + * <p> + * The method then concatenates <code>PS</code>, the message <code>M</code>, * and other padding to form an encoded message <code>EM</code> of length - * <code>k</code> octets as:</p> - * + * <code>k</code> octets as: * <pre> - * EM = 0x00 || 0x02 || PS || 0x00 || M. + * EM = 0x00 || 0x02 || PS || 0x00 || M. * </pre> - * - * <p>This method uses a default PRNG to obtain the padding bytes.</p> - * + * <p> + * This method uses a default PRNG to obtain the padding bytes. + * * @param M the message to encode. * @return the encoded message <code>EM</code>. */ 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); } /** - * <p>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.</p> - * + * {@link IRandom}) is given as a parameter. + * * @param M the message to encode. * @param irnd the {@link IRandom} instance to use as a source of randomness. * @return the encoded message <code>EM</code>. @@ -183,14 +167,13 @@ public class EME_PKCS1_V1_5 { throw new RuntimeException("encode(): " + String.valueOf(x)); } - return assembleEM(PS, M); } /** - * <p>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 <code>EM</code>. @@ -213,33 +196,31 @@ public class EME_PKCS1_V1_5 } break; } - return assembleEM(PS, M); } /** - * <p>Separate the encoded message <code>EM</code> into an octet string + * Separate the encoded message <code>EM</code> into an octet string * <code>PS</code> consisting of nonzero octets and a message <code>M</code> - * as:</p> - * + * as: * <pre> - * EM = 0x00 || 0x02 || PS || 0x00 || M. + * EM = 0x00 || 0x02 || PS || 0x00 || M. * </pre> - * - * <p>If the first octet of <code>EM</code> does not have hexadecimal value - * <code>0x00</code>, if the second octet of <code>EM</code> does not have - * hexadecimal value <code>0x02</code>, if there is no octet with hexadecimal - * value <code>0x00</code> to separate <code>PS</code> from <code>M</code>, - * or if the length of <code>PS</code> is less than <code>8</code> octets, - * output "decryption error" and stop.</p> - + * <p> + * If the first octet of <code>EM</code> does not have hexadecimal value + * <code>0x00</code>, if the second octet of <code>EM</code> does not + * have hexadecimal value <code>0x02</code>, if there is no octet with + * hexadecimal value <code>0x00</code> to separate <code>PS</code> from + * <code>M</code>, or if the length of <code>PS</code> is less than + * <code>8</code> octets, output "decryption error" and stop. + * * @param EM the designated encoded message. * @return the decoded message <code>M</code> framed in the designated - * <code>EM</code> value. + * <code>EM</code> value. * @throws IllegalArgumentException if the length of the designated entity - * <code>EM</code> is different than <code>k</code> (the length in bytes of - * the public shared modulus), or if any of the conditions described above - * is detected. + * <code>EM</code> is different than <code>k</code> (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/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java b/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java index d155fc88f..a0c4de17f 100644 --- a/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java +++ b/gnu/java/security/sig/rsa/EMSA_PKCS1_V1_5.java @@ -45,12 +45,12 @@ import gnu.java.security.hash.IMessageDigest; import java.io.ByteArrayOutputStream; /** - * <p>An implementation of the EMSA-PKCS1-V1.5 encoding scheme.</p> - * - * <p>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.</p> - * - * <p>References:</p> + * An implementation of the EMSA-PKCS1-V1.5 encoding scheme. + * <p> + * 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. + * <p> + * References: * <ol> * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography * Standards (PKCS) #1:</a><br> @@ -58,12 +58,9 @@ import java.io.ByteArrayOutputStream; * Jakob Jonsson and Burt Kaliski.</li> * </ol> */ -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) - // ------------------------------------------------------------------------- - /** - * <p>Trivial private constructor to enforce use through Factory method.</p> + * Trivial private constructor to enforce use through Factory method. * * @param hash the message digest instance to use with this scheme instance. */ @@ -162,41 +135,24 @@ public class EMSA_PKCS1_V1_5 implements Cloneable hLen = hash.hashSize(); final String name = hash.name(); if (name.equals(Registry.MD2_HASH)) - { - prefix = MD2_PREFIX; - } + prefix = MD2_PREFIX; else if (name.equals(Registry.MD5_HASH)) - { - prefix = MD5_PREFIX; - } + prefix = MD5_PREFIX; else if (name.equals(Registry.SHA160_HASH)) - { - prefix = SHA160_PREFIX; - } + prefix = SHA160_PREFIX; else if (name.equals(Registry.SHA256_HASH)) - { - prefix = SHA256_PREFIX; - } + prefix = SHA256_PREFIX; else if (name.equals(Registry.SHA384_HASH)) - { - prefix = SHA384_PREFIX; - } + prefix = SHA384_PREFIX; else if (name.equals(Registry.SHA512_HASH)) - { - prefix = SHA512_PREFIX; - } + prefix = SHA512_PREFIX; else - { - throw new UnsupportedOperationException(); // should not happen - } + throw new UnsupportedOperationException(); // should not happen } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns an instance of this object given a designated name of a hash - * function.</p> + * Returns an instance of this object given a designated name of a hash + * function. * * @param mdName the canonical name of a hash function. * @return an instance of this object configured for use with the designated @@ -208,32 +164,26 @@ public class EMSA_PKCS1_V1_5 implements Cloneable { final IMessageDigest hash = HashFactory.getInstance(mdName); final String name = hash.name(); - if (!(name.equals(Registry.MD2_HASH) || name.equals(Registry.MD5_HASH) + if (! (name.equals(Registry.MD2_HASH) + || name.equals(Registry.MD5_HASH) || name.equals(Registry.SHA160_HASH) || name.equals(Registry.SHA256_HASH) - || name.equals(Registry.SHA384_HASH) || name.equals(Registry.SHA512_HASH))) - { - throw new UnsupportedOperationException("hash with no OID: " + name); - } + || name.equals(Registry.SHA384_HASH) + || name.equals(Registry.SHA512_HASH))) + throw new UnsupportedOperationException("hash with no OID: " + name); + return new EMSA_PKCS1_V1_5(hash); } - // Instance methods - // ------------------------------------------------------------------------- - - // Cloneable interface implementation -------------------------------------- - public Object clone() { return getInstance(hash.name()); } - // own methods ------------------------------------------------------------- - /** - * <p>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).</p> + * described in RFC-3447 (see class documentation). * * @param mHash the byte sequence resulting from applying the message digest * algorithm Hash to the message <i>M</i>. @@ -270,17 +220,13 @@ public class EMSA_PKCS1_V1_5 implements Cloneable // 3. If emLen < tLen + 11, output "intended encoded message length too // short" and stop. if (emLen < tLen + 11) - { - throw new IllegalArgumentException("emLen too short"); - } + throw new IllegalArgumentException("emLen too short"); // 4. Generate an octet string PS consisting of emLen - tLen - 3 octets // with hexadecimal value 0xff. The length of PS will be at least 8 // octets. final byte[] PS = new byte[emLen - tLen - 3]; for (int i = 0; i < PS.length; i++) - { - PS[i] = (byte) 0xFF; - } + PS[i] = (byte) 0xFF; // 5. Concatenate PS, the DER encoding T, and other padding to form the // encoded message EM as: EM = 0x00 || 0x01 || PS || 0x00 || T. baos.reset(); diff --git a/gnu/java/security/sig/rsa/EMSA_PSS.java b/gnu/java/security/sig/rsa/EMSA_PSS.java index 0b93abab7..5dd7e28eb 100644 --- a/gnu/java/security/sig/rsa/EMSA_PSS.java +++ b/gnu/java/security/sig/rsa/EMSA_PSS.java @@ -47,43 +47,43 @@ import java.util.Arrays; import java.util.logging.Logger; /** - * <p>An implementation of the EMSA-PSS encoding/decoding scheme.</p> - * - * <p>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.</p> - * - * <p>EMSA-PSS is parameterized by the choice of hash function Hash and mask + * An implementation of the EMSA-PSS encoding/decoding scheme. + * <p> + * 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. + * <p> + * 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.</p> - * - * <p>References:</p> + * 1363-2000 recommends SHA-1 and RIPEMD-160. + * <p> + * References: * <ol> - * <li><a href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip"> - * RSA-PSS Signature Scheme with Appendix, part B.</a><br> - * Primitive specification and supporting documentation.<br> - * Jakob Jonsson and Burt Kaliski.</li> + * <li><a + * href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip"> + * RSA-PSS Signature Scheme with Appendix, part B.</a><br> + * Primitive specification and supporting documentation.<br> + * Jakob Jonsson and Burt Kaliski.</li> * </ol> */ -public class EMSA_PSS implements Cloneable +public class EMSA_PSS + implements Cloneable { private static final Logger log = Logger.getLogger(EMSA_PSS.class.getName()); + /** The underlying hash function to use with this instance. */ private IMessageDigest hash; /** The output size of the hash function in octets. */ private int hLen; - // Constructor(s) - // ------------------------------------------------------------------------- - /** - * <p>Trivial private constructor to enforce use through Factory method.</p> - * + * Trivial private constructor to enforce use through Factory method. + * * @param hash the message digest instance to use with this scheme instance. */ private EMSA_PSS(IMessageDigest hash) @@ -94,16 +94,13 @@ public class EMSA_PSS implements Cloneable hLen = hash.hashSize(); } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns an instance of this object given a designated name of a hash - * function.</p> - * + * Returns an instance of this object given a designated name of a hash + * function. + * * @param mdName the canonical name of a hash function. * @return an instance of this object configured for use with the designated - * options. + * options. */ public static EMSA_PSS getInstance(String mdName) { @@ -111,51 +108,38 @@ public class EMSA_PSS implements Cloneable return new EMSA_PSS(hash); } - // Instance methods - // ------------------------------------------------------------------------- - - // Cloneable interface implementation -------------------------------------- - public Object clone() { return getInstance(hash.name()); } - // own methods ------------------------------------------------------------- - /** - * <p>The encoding operation EMSA-PSS-Encode computes the hash of a message + * The encoding operation EMSA-PSS-Encode computes the hash of a message * <code>M</code> using a hash function and maps the result to an encoded * message <code>EM</code> of a specified length using a mask generation - * function.</p> - * + * function. + * * @param mHash the byte sequence resulting from applying the message digest - * algorithm Hash to the message <i>M</i>. + * algorithm Hash to the message <i>M</i>. * @param emBits the maximal bit length of the integer OS2IP(EM), at least - * <code>8.hLen + 8.sLen + 9</code>. + * <code>8.hLen + 8.sLen + 9</code>. * @param salt the salt to use when encoding the output. * @return the encoded message <code>EM</code>, an octet string of length - * <code>emLen = CEILING(emBits / 8)</code>. + * <code>emLen = CEILING(emBits / 8)</code>. * @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. @@ -169,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(); @@ -191,9 +174,7 @@ public class EMSA_PSS implements Cloneable } // 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)); @@ -208,14 +189,14 @@ public class EMSA_PSS implements Cloneable } /** - * <p>The decoding operation EMSA-PSS-Decode recovers the message hash from - * an encoded message <code>EM</code> and compares it to the hash of - * <code>M</code>.</p> - * + * The decoding operation EMSA-PSS-Decode recovers the message hash from an + * encoded message <code>EM</code> and compares it to the hash of + * <code>M</code>. + * * @param mHash the byte sequence resulting from applying the message digest - * algorithm Hash to the message <i>M</i>. + * algorithm Hash to the message <i>M</i>. * @param EM the <i>encoded message</i>, an octet string of length - * <code>emLen = CEILING(emBits/8). + * <code>emLen = CEILING(emBits/8). * @param emBits the maximal bit length of the integer OS2IP(EM), at least * <code>8.hLen + 8.sLen + 9</code>. * @param sLen the length, in octets, of the expected salt. @@ -234,13 +215,10 @@ public class EMSA_PSS implements Cloneable 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) { @@ -252,12 +230,13 @@ public class EMSA_PSS implements Cloneable if (emBits < (8 * hLen + 8 * sLen + 9)) { if (Configuration.DEBUG) - log.fine("emBits < (8hLen + 8sLen + 9); sLen: " + String.valueOf(sLen)); + 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 (Configuration.DEBUG) @@ -265,9 +244,9 @@ public class EMSA_PSS implements Cloneable 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 (Configuration.DEBUG) @@ -283,9 +262,7 @@ 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 (Configuration.DEBUG) @@ -294,11 +271,10 @@ public class EMSA_PSS implements Cloneable 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) @@ -319,16 +295,15 @@ public class EMSA_PSS implements Cloneable 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(); @@ -337,34 +312,30 @@ public class EMSA_PSS implements Cloneable return Arrays.equals(H, H0); } - // helper methods ---------------------------------------------------------- - /** - * <p>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.</p> - * + * 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. + * * @param Z a seed. * @param l the desired output length in octets. * @return the mask. * @exception IllegalArgumentException if the desired output length is too - * long. + * long. */ private byte[] MGF(byte[] Z, int l) { // 1. If l > (2**32).hLen, output 'mask too long' and stop. if (l < 1 || (l & 0xFFFFFFFFL) > ((hLen & 0xFFFFFFFFL) << 32L)) - { - throw new IllegalArgumentException("mask too long"); - } + throw new IllegalArgumentException("mask too long"); // 2. Let T be the empty octet string. byte[] result = new byte[l]; // 3. For i = 0 to CEILING(l/hLen) ? 1, do @@ -379,14 +350,14 @@ public class EMSA_PSS implements Cloneable int length; for (int i = 0; i < limit; i++) { - // 3.1 Convert i to an octet string C of length 4 with the primitive - // I2OSP: C = I2OSP(i, 4). - // 3.2 Concatenate the hash of the seed Z and C to the octet string T: - // T = T || Hash(Z || C) + // 3.1 Convert i to an octet string C of length 4 with the primitive + // I2OSP: C = I2OSP(i, 4). + // 3.2 Concatenate the hash of the seed Z and C to the octet string T: + // T = T || Hash(Z || C) hashZC = (IMessageDigest) hashZ.clone(); - hashZC.update((byte) (i >>> 24)); - hashZC.update((byte) (i >>> 16)); - hashZC.update((byte) (i >>> 8)); + hashZC.update((byte)(i >>> 24)); + hashZC.update((byte)(i >>> 16)); + hashZC.update((byte)(i >>> 8)); hashZC.update((byte) i); t = hashZC.digest(); length = l - sofar; diff --git a/gnu/java/security/sig/rsa/RSA.java b/gnu/java/security/sig/rsa/RSA.java index 7d1707e19..cdd9eaa5b 100644 --- a/gnu/java/security/sig/rsa/RSA.java +++ b/gnu/java/security/sig/rsa/RSA.java @@ -49,31 +49,26 @@ import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; /** - * <p>Utility methods related to the RSA algorithm.</p> - * - * <p>References:</p> + * Utility methods related to the RSA algorithm. + * <p> + * References: * <ol> - * <li><a href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip"> - * RSA-PSS Signature Scheme with Appendix, part B.</a><br> - * Primitive specification and supporting documentation.<br> - * Jakob Jonsson and Burt Kaliski.</li> - * - * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography - * Standards (PKCS) #1:</a><br> - * RSA Cryptography Specifications Version 2.1.<br> - * Jakob Jonsson and Burt Kaliski.</li> - * - * <li><a href="http://crypto.stanford.edu/~dabo/abstracts/ssl-timing.html"> - * Remote timing attacks are practical</a><br> - * D. Boneh and D. Brumley.</li> + * <li><a + * href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip"> + * RSA-PSS Signature Scheme with Appendix, part B.</a><br> + * Primitive specification and supporting documentation.<br> + * Jakob Jonsson and Burt Kaliski.</li> + * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography + * Standards (PKCS) #1:</a><br> + * RSA Cryptography Specifications Version 2.1.<br> + * Jakob Jonsson and Burt Kaliski.</li> + * <li><a href="http://crypto.stanford.edu/~dabo/abstracts/ssl-timing.html"> + * Remote timing attacks are practical</a><br> + * D. Boneh and D. Brumley.</li> * </ol> */ 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 -------------------------------------- - /** - * <p>An implementation of the <b>RSASP</b> method: Assuming that the - * designated RSA private key is a valid one, this method computes a - * <i>signature representative</i> for a designated <i>message - * representative</i> signed by the holder of the designated RSA private - * key.<p> - * + * An implementation of the <b>RSASP</b> method: Assuming that the designated + * RSA private key is a valid one, this method computes a <i>signature + * representative</i> for a designated <i>message representative</i> signed + * by the holder of the designated RSA private key. + * * @param K the RSA private key. * @param m the <i>message representative</i>: an integer between - * <code>0</code> and <code>n - 1</code>, where <code>n</code> is the RSA - * <i>modulus</i>. + * <code>0</code> and <code>n - 1</code>, where <code>n</code> + * is the RSA <i>modulus</i>. * @return the <i>signature representative</i>, an integer between - * <code>0</code> and <code>n - 1</code>, where <code>n</code> is the RSA - * <i>modulus</i>. + * <code>0</code> and <code>n - 1</code>, where <code>n</code> + * is the RSA <i>modulus</i>. * @throws ClassCastException if <code>K</code> is not an RSA one. * @throws IllegalArgumentException if <code>m</code> (the <i>message - * representative</i>) is out of range. + * representative</i>) 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"); } } /** - * <p>An implementation of the <b>RSAVP</b> method: Assuming that the - * designated RSA public key is a valid one, this method computes a - * <i>message representative</i> for the designated <i>signature - * representative</i> generated by an RSA private key, for a message - * intended for the holder of the designated RSA public key.</p> - * + * An implementation of the <b>RSAVP</b> method: Assuming that the designated + * RSA public key is a valid one, this method computes a <i>message + * representative</i> for the designated <i>signature representative</i> + * generated by an RSA private key, for a message intended for the holder of + * the designated RSA public key. + * * @param K the RSA public key. * @param s the <i>signature representative</i>, an integer between - * <code>0</code> and <code>n - 1</code>, where <code>n</code> is the RSA - * <i>modulus</i>. + * <code>0</code> and <code>n - 1</code>, where <code>n</code> + * is the RSA <i>modulus</i>. * @return a <i>message representative</i>: an integer between <code>0</code> - * and <code>n - 1</code>, where <code>n</code> is the RSA <i>modulus</i>. + * and <code>n - 1</code>, where <code>n</code> is the RSA + * <i>modulus</i>. * @throws ClassCastException if <code>K</code> is not an RSA one. * @throws IllegalArgumentException if <code>s</code> (the <i>signature - * representative</i>) is out of range. + * representative</i>) 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 --------------------------------------- - /** - * <p>An implementation of the <code>RSAEP</code> algorithm.</p> - * + * An implementation of the <code>RSAEP</code> algorithm. + * * @param K the recipient's RSA public key. * @param m the message representative as an MPI. * @return the resulting MPI --an MPI between <code>0</code> and - * <code>n - 1</code> (<code>n</code> being the public shared modulus)-- that - * will eventually be padded with an appropriate framing/padding scheme. + * <code>n - 1</code> (<code>n</code> being the public shared + * modulus)-- that will eventually be padded with an appropriate + * framing/padding scheme. * @throws ClassCastException if <code>K</code> is not an RSA one. * @throws IllegalArgumentException if <code>m</code>, the message - * representative is not between <code>0</code> and <code>n - 1</code> - * (<code>n</code> being the public shared modulus). + * representative is not between <code>0</code> and + * <code>n - 1</code> (<code>n</code> 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"); } } /** - * <p>An implementation of the <code>RSADP</code> algorithm.</p> - * + * An implementation of the <code>RSADP</code> algorithm. + * * @param K the recipient's RSA private key. * @param c the ciphertext representative as an MPI. * @return the message representative, an MPI between <code>0</code> and - * <code>n - 1</code> (<code>n</code> being the shared public modulus). + * <code>n - 1</code> (<code>n</code> being the shared public + * modulus). * @throws ClassCastException if <code>K</code> is not an RSA one. * @throws IllegalArgumentException if <code>c</code>, the ciphertext - * representative is not between <code>0</code> and <code>n - 1</code> - * (<code>n</code> being the shared public modulus). + * representative is not between <code>0</code> and + * <code>n - 1</code> (<code>n</code> 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 ------------------------------------------------------ - /** - * <p>Converts a <i>multi-precision integer</i> (MPI) <code>s</code> into an - * octet sequence of length <code>k</code>.</p> - * + * Converts a <i>multi-precision integer</i> (MPI) <code>s</code> into an + * octet sequence of length <code>k</code>. + * * @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 <code>s</code> is greater than <code>k</code>. + * bytes of <code>s</code> is greater than <code>k</code>. */ 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; } /** - * <p>Returns a random MPI with a random bit-length of the form <code>8b</code>, - * where <code>b</code> is in the range <code>[32..64]</code>.</p> - * + * Returns a random MPI with a random bit-length of the form <code>8b</code>, + * where <code>b</code> is in the range <code>[32..64]</code>. + * * @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/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java b/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java index e64d30b69..76460c0ca 100644 --- a/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java +++ b/gnu/java/security/sig/rsa/RSAPKCS1V1_5Signature.java @@ -51,35 +51,29 @@ import java.security.interfaces.RSAPublicKey; import java.util.Arrays; /** - * <p>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.</p> - * - * <p>References:</p> + * method. + * <p> + * References: * <ol> - * <li><a href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip"> - * RSA-PSS Signature Scheme with Appendix, part B.</a><br> - * Primitive specification and supporting documentation.<br> - * Jakob Jonsson and Burt Kaliski.</li> - * - * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography - * Standards (PKCS) #1:</a><br> - * RSA Cryptography Specifications Version 2.1.<br> - * Jakob Jonsson and Burt Kaliski.</li> + * <li><a + * href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip"> + * RSA-PSS Signature Scheme with Appendix, part B.</a><br> + * Primitive specification and supporting documentation.<br> + * Jakob Jonsson and Burt Kaliski.</li> + * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography + * Standards (PKCS) #1:</a><br> + * RSA Cryptography Specifications Version 2.1.<br> + * Jakob Jonsson and Burt Kaliski.</li> * </ol> */ -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 } /** - * <p>Constructs an instance of this object using the designated message - * digest algorithm as its underlying hash function.</p> - * + * Constructs an instance of this object using the designated message digest + * algorithm as its underlying hash function. + * * @param mdName the canonical name of the underlying hash function. */ public RSAPKCS1V1_5Signature(final String mdName) @@ -117,14 +111,6 @@ public class RSAPKCS1V1_5Signature extends BaseSignature this.pkcs1 = (EMSA_PKCS1_V1_5) that.pkcs1.clone(); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // Implementation of abstract methods in superclass ------------------------ - public Object clone() { return new RSAPKCS1V1_5Signature(this); @@ -133,49 +119,46 @@ public class RSAPKCS1V1_5Signature extends BaseSignature protected void setupForVerification(final PublicKey k) throws IllegalArgumentException { - if (!(k instanceof RSAPublicKey)) - { - throw new IllegalArgumentException(); - } + if (! (k instanceof RSAPublicKey)) + throw new IllegalArgumentException(); + publicKey = k; } protected void setupForSigning(final PrivateKey k) throws IllegalArgumentException { - if (!(k instanceof RSAPrivateKey)) - { - throw new IllegalArgumentException(); - } + if (! (k instanceof RSAPrivateKey)) + throw new IllegalArgumentException(); + privateKey = k; } protected Object generateSignature() throws IllegalStateException { // 1. EMSA-PKCS1-v1_5 encoding: Apply the EMSA-PKCS1-v1_5 encoding - // operation (Section 9.2) to the message M to produce an encoded - // message EM of length k octets: + // operation (Section 9.2) to the message M to produce an encoded + // message EM of length k octets: // - // EM = EMSA-PKCS1-V1_5-ENCODE (M, k). + // EM = EMSA-PKCS1-V1_5-ENCODE (M, k). // - // If the encoding operation outputs "message too long," output - // "message too long" and stop. If the encoding operation outputs - // "intended encoded message length too short," output "RSA modulus - // too short" and stop. + // If the encoding operation outputs "message too long," output + // "message too long" and stop. If the encoding operation outputs + // "intended encoded message length too short," output "RSA modulus + // too short" and stop. final int modBits = ((RSAPrivateKey) privateKey).getModulus().bitLength(); final int k = (modBits + 7) / 8; final byte[] EM = pkcs1.encode(md.digest(), k); - // 2. RSA signature: - // a. Convert the encoded message EM to an integer message epresentative - // m (see Section 4.2): m = OS2IP (EM). + // a. Convert the encoded message EM to an integer message epresentative + // m (see Section 4.2): m = OS2IP (EM). final BigInteger m = new BigInteger(1, EM); - // b. Apply the RSASP1 signature primitive (Section 5.2.1) to the RSA - // private key K and the message representative m to produce an - // integer signature representative s: s = RSASP1 (K, m). + // b. Apply the RSASP1 signature primitive (Section 5.2.1) to the RSA + // private key K and the message representative m to produce an + // integer signature representative s: s = RSASP1 (K, m). final BigInteger s = RSA.sign(privateKey, m); - // c. Convert the signature representative s to a signature S of length - // k octets (see Section 4.1): S = I2OSP (s, k). + // c. Convert the signature representative s to a signature S of length + // k octets (see Section 4.1): S = I2OSP (s, k). // 3. Output the signature S. return RSA.I2OSP(s, k); } @@ -184,28 +167,24 @@ public class RSAPKCS1V1_5Signature extends BaseSignature throws IllegalStateException { if (publicKey == null) - { - throw new IllegalStateException(); - } + throw new IllegalStateException(); final byte[] S = (byte[]) sig; // 1. Length checking: If the length of the signature S is not k octets, - // output "invalid signature" and stop. + // output "invalid signature" and stop. final int modBits = ((RSAPublicKey) publicKey).getModulus().bitLength(); final int k = (modBits + 7) / 8; if (S.length != k) - { - return false; - } + return false; // 2. RSA verification: - // a. Convert the signature S to an integer signature representative - // s (see Section 4.2): s = OS2IP (S). + // a. Convert the signature S to an integer signature representative + // s (see Section 4.2): s = OS2IP (S). final BigInteger s = new BigInteger(1, S); - // b. Apply the RSAVP1 verification primitive (Section 5.2.2) to the - // RSA public key (n, e) and the signature representative s to - // produce an integer message representative m: - // m = RSAVP1 ((n, e), s). - // If RSAVP1 outputs "signature representative out of range," - // output "invalid signature" and stop. + // b. Apply the RSAVP1 verification primitive (Section 5.2.2) to the + // RSA public key (n, e) and the signature representative s to + // produce an integer message representative m: + // m = RSAVP1 ((n, e), s). + // If RSAVP1 outputs "signature representative out of range," + // output "invalid signature" and stop. final BigInteger m; try { @@ -215,10 +194,10 @@ public class RSAPKCS1V1_5Signature extends BaseSignature { return false; } - // c. Convert the message representative m to an encoded message EM - // of length k octets (see Section 4.1): EM = I2OSP (m, k). - // If I2OSP outputs "integer too large," output "invalid signature" - // and stop. + // c. Convert the message representative m to an encoded message EM + // of length k octets (see Section 4.1): EM = I2OSP (m, k). + // If I2OSP outputs "integer too large," output "invalid signature" + // and stop. final byte[] EM; try { @@ -229,17 +208,17 @@ public class RSAPKCS1V1_5Signature extends BaseSignature return false; } // 3. EMSA-PKCS1-v1_5 encoding: Apply the EMSA-PKCS1-v1_5 encoding - // operation (Section 9.2) to the message M to produce a second - // encoded message EM' of length k octets: - // EM' = EMSA-PKCS1-V1_5-ENCODE (M, k). - // If the encoding operation outputs "message too long," output - // "message too long" and stop. If the encoding operation outputs - // "intended encoded message length too short," output "RSA modulus - // too short" and stop. + // operation (Section 9.2) to the message M to produce a second + // encoded message EM' of length k octets: + // EM' = EMSA-PKCS1-V1_5-ENCODE (M, k). + // If the encoding operation outputs "message too long," output + // "message too long" and stop. If the encoding operation outputs + // "intended encoded message length too short," output "RSA modulus + // too short" and stop. final byte[] EMp = pkcs1.encode(md.digest(), k); // 4. Compare the encoded message EM and the second encoded message EM'. - // If they are the same, output "valid signature"; otherwise, output - // "invalid signature." + // If they are the same, output "valid signature"; otherwise, output + // "invalid signature." return Arrays.equals(EM, EMp); } } diff --git a/gnu/java/security/sig/rsa/RSAPSSSignature.java b/gnu/java/security/sig/rsa/RSAPSSSignature.java index 3e9cad452..053d653a1 100644 --- a/gnu/java/security/sig/rsa/RSAPSSSignature.java +++ b/gnu/java/security/sig/rsa/RSAPSSSignature.java @@ -53,37 +53,36 @@ import java.security.interfaces.RSAPublicKey; import java.util.logging.Logger; /** - * <p>The RSA-PSS signature scheme is a public-key encryption scheme combining - * the RSA algorithm with the Probabilistic Signature Scheme (PSS) encoding - * method.</p> - * - * <p>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. + * <p> + * 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.</p> - * - * <p>References:</pr> + * P1363a) to facilitate implementation and integration into existing protocols. + * <p> + * References: * <ol> - * <li><a href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip"> - * RSA-PSS Signature Scheme with Appendix, part B.</a><br> - * Primitive specification and supporting documentation.<br> - * Jakob Jonsson and Burt Kaliski.</li> + * <li><a + * href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip"> + * RSA-PSS Signature Scheme with Appendix, part B.</a><br> + * Primitive specification and supporting documentation.<br> + * Jakob Jonsson and Burt Kaliski.</li> * </ol> */ -public class RSAPSSSignature extends BaseSignature +public class RSAPSSSignature + extends BaseSignature { private static final Logger log = Logger.getLogger(RSAPSSSignature.class.getName()); + /** The underlying EMSA-PSS instance for this object. */ private EMSA_PSS pss; /** 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 <i>salt</i>. @@ -94,10 +93,9 @@ public class RSAPSSSignature extends BaseSignature } /** - * <p>Constructs an instance of this object using the designated message - * digest algorithm as its underlying hash function, and having 0-octet - * <i>salt</i>.</p> - * + * Constructs an instance of this object using the designated message digest + * algorithm as its underlying hash function, and having 0-octet <i>salt</i>. + * * @param mdName the canonical name of the underlying hash function. */ public RSAPSSSignature(String mdName) @@ -106,12 +104,12 @@ public class RSAPSSSignature extends BaseSignature } /** - * <p>Constructs an instance of this object using the designated message - * digest algorithm as its underlying hash function.</p> - * + * Constructs an instance of this object using the designated message digest + * algorithm as its underlying hash function. + * * @param mdName the canonical name of the underlying hash function. * @param sLen the desired length in octets of the salt to use for encoding / - * decoding signatures. + * decoding signatures. */ public RSAPSSSignature(String mdName, int sLen) { @@ -137,14 +135,6 @@ public class RSAPSSSignature extends BaseSignature this.pss = (EMSA_PSS) that.pss.clone(); } - // Class methods - // ------------------------------------------------------------------------- - - // Instance methods - // ------------------------------------------------------------------------- - - // Implementation of abstract methods in superclass ------------------------ - public Object clone() { return new RSAPSSSignature(this); @@ -153,32 +143,30 @@ public class RSAPSSSignature extends BaseSignature protected void setupForVerification(PublicKey k) throws IllegalArgumentException { - if (!(k instanceof RSAPublicKey)) - { - throw new IllegalArgumentException(); - } + if (! (k instanceof RSAPublicKey)) + throw new IllegalArgumentException(); + publicKey = (RSAPublicKey) k; } protected void setupForSigning(PrivateKey k) throws IllegalArgumentException { - if (!(k instanceof RSAPrivateKey)) - { - throw new IllegalArgumentException(); - } + if (! (k instanceof RSAPrivateKey)) + throw new IllegalArgumentException(); + privateKey = (RSAPrivateKey) k; } protected Object generateSignature() throws IllegalStateException { // 1. Apply the EMSA-PSS encoding operation to the message M to produce an - // encoded message EM of length CEILING((modBits ? 1)/8) octets such - // that the bit length of the integer OS2IP(EM) is at most modBits ? 1: - // EM = EMSA-PSS-Encode(M,modBits ? 1). - // Note that the octet length of EM will be one less than k if - // modBits ? 1 is divisible by 8. If the encoding operation outputs - // 'message too long' or 'encoding error,' then output 'message too - // long' or 'encoding error' and stop. + // encoded message EM of length CEILING((modBits ? 1)/8) octets such + // that the bit length of the integer OS2IP(EM) is at most modBits ? 1: + // EM = EMSA-PSS-Encode(M,modBits ? 1). + // Note that the octet length of EM will be one less than k if + // modBits ? 1 is divisible by 8. If the encoding operation outputs + // 'message too long' or 'encoding error,' then output 'message too + // long' or 'encoding error' and stop. int modBits = ((RSAPrivateKey) privateKey).getModulus().bitLength(); byte[] salt = new byte[sLen]; this.nextRandomBytes(salt); @@ -186,44 +174,40 @@ public class RSAPSSSignature extends BaseSignature if (Configuration.DEBUG) log.fine("EM (sign): " + Util.toString(EM)); // 2. Convert the encoded message EM to an integer message representative - // m (see Section 1.2.2): m = OS2IP(EM). + // m (see Section 1.2.2): m = OS2IP(EM). BigInteger m = new BigInteger(1, EM); // 3. Apply the RSASP signature primitive to the public key K and the - // message representative m to produce an integer signature - // representative s: s = RSASP(K,m). + // message representative m to produce an integer signature + // representative s: s = RSASP(K,m). BigInteger s = RSA.sign(privateKey, m); // 4. Convert the signature representative s to a signature S of length k - // octets (see Section 1.2.1): S = I2OSP(s, k). + // octets (see Section 1.2.1): S = I2OSP(s, k). // 5. Output the signature S. int k = (modBits + 7) / 8; - // return encodeSignature(s, k); + // return encodeSignature(s, k); return RSA.I2OSP(s, k); } protected boolean verifySignature(Object sig) throws IllegalStateException { if (publicKey == null) - { - throw new IllegalStateException(); - } - // byte[] S = decodeSignature(sig); + throw new IllegalStateException(); + // byte[] S = decodeSignature(sig); byte[] S = (byte[]) sig; // 1. If the length of the signature S is not k octets, output 'signature - // invalid' and stop. + // invalid' and stop. int modBits = ((RSAPublicKey) publicKey).getModulus().bitLength(); int k = (modBits + 7) / 8; if (S.length != k) - { - return false; - } + return false; // 2. Convert the signature S to an integer signature representative s: - // s = OS2IP(S). + // s = OS2IP(S). BigInteger s = new BigInteger(1, S); // 3. Apply the RSAVP verification primitive to the public key (n, e) and - // the signature representative s to produce an integer message - // representative m: m = RSAVP((n, e), s). - // If RSAVP outputs 'signature representative out of range,' then - // output 'signature invalid' and stop. + // the signature representative s to produce an integer message + // representative m: m = RSAVP((n, e), s). + // If RSAVP outputs 'signature representative out of range,' then + // output 'signature invalid' and stop. BigInteger m = null; try { @@ -234,20 +218,18 @@ public class RSAPSSSignature extends BaseSignature return false; } // 4. Convert the message representative m to an encoded message EM of - // length emLen = CEILING((modBits - 1)/8) octets, where modBits is - // equal to the bit length of the modulus: EM = I2OSP(m, emLen). - // Note that emLen will be one less than k if modBits - 1 is divisible - // by 8. If I2OSP outputs 'integer too large,' then output 'signature - // invalid' and stop. + // length emLen = CEILING((modBits - 1)/8) octets, where modBits is + // equal to the bit length of the modulus: EM = I2OSP(m, emLen). + // Note that emLen will be one less than k if modBits - 1 is divisible + // by 8. If I2OSP outputs 'integer too large,' then output 'signature + // invalid' and stop. int emBits = modBits - 1; int emLen = (emBits + 7) / 8; byte[] EM = m.toByteArray(); if (Configuration.DEBUG) log.fine("EM (verify): " + Util.toString(EM)); if (EM.length > emLen) - { - return false; - } + return false; else if (EM.length < emLen) { byte[] newEM = new byte[emLen]; @@ -255,9 +237,9 @@ public class RSAPSSSignature extends BaseSignature EM = newEM; } // 5. Apply the EMSA-PSS decoding operation to the message M and the - // encoded message EM: Result = EMSA-PSS-Decode(M, EM, emBits). If - // Result = 'consistent,' output 'signature verified.' Otherwise, - // output 'signature invalid.' + // encoded message EM: Result = EMSA-PSS-Decode(M, EM, emBits). If + // Result = 'consistent,' output 'signature verified.' Otherwise, + // output 'signature invalid.' byte[] mHash = md.digest(); boolean result = false; try @@ -270,55 +252,4 @@ public class RSAPSSSignature extends BaseSignature } return result; } - - // Other instance methods -------------------------------------------------- - - /** - * Converts the <i>signature representative</i> <code>s</code> to a signature - * <code>S</code> of length <code>k</code> octets; i.e. - * <code>S = I2OSP(s, k)</code>, where <code>k = CEILING(modBits/8)</code>. - * - * @param s the <i>signature representative</i>. - * @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 <code>s</code> is greater than <code>k</code>, implying that - * <code>s</code> is not less than the RSA <i>modulus</i>. - */ - // 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.<p> - * - * @return the octet sequence <code>S</code>. - */ - // private byte[] decodeSignature(Object signature) { - // return (byte[]) signature; - // } } diff --git a/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java b/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java index 1ae295e36..b5e059c20 100644 --- a/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java +++ b/gnu/java/security/sig/rsa/RSAPSSSignatureRawCodec.java @@ -44,53 +44,41 @@ import gnu.java.security.sig.ISignatureCodec; import java.io.ByteArrayOutputStream; /** - * <p>An object that implements the {@link ISignatureCodec} - * operations for the <i>Raw</i> format to use with RSA-PSS signatures.</p> + * An object that implements the {@link ISignatureCodec} operations for the + * <i>Raw</i> format to use with RSA-PSS signatures. */ -public class RSAPSSSignatureRawCodec implements ISignatureCodec +public class RSAPSSSignatureRawCodec + implements ISignatureCodec { - - // Constants and variables - // ------------------------------------------------------------------------- - - // Constructor(s) - // ------------------------------------------------------------------------- - // implicit 0-arguments constructor - // Class methods - // ------------------------------------------------------------------------- - - // gnu.crypto.keys.IKeyPairCodec interface implementation - // ------------------------------------------------------------------------- - public int getFormatID() { return RAW_FORMAT; } /** - * <p>Returns the encoded form of the designated RSA-PSS signature object - * according to the <i>Raw</i> format supported by this library.</p> - * - * <p>The <i>Raw</i> format for an RSA-PSS signature, in this implementation, - * is a byte sequence consisting of the following:</p> - * + * Returns the encoded form of the designated RSA-PSS signature object + * according to the <i>Raw</i> format supported by this library. + * <p> + * The <i>Raw</i> format for an RSA-PSS signature, in this implementation, is + * a byte sequence consisting of the following: * <ol> - * <li>4-byte magic consisting of the value of the literal - * {@link Registry#MAGIC_RAW_RSA_PSS_SIGNATURE},<li> - * <li>1-byte version consisting of the constant: 0x01,</li> - * <li>4-byte count of following bytes representing the RSA-PSS signature - * bytes in internet order,</li> - * <li>the RSA-PSS signature bytes in internet order.</li> + * <li>4-byte magic consisting of the value of the literal + * {@link Registry#MAGIC_RAW_RSA_PSS_SIGNATURE}, + * <li> + * <li>1-byte version consisting of the constant: 0x01,</li> + * <li>4-byte count of following bytes representing the RSA-PSS signature + * bytes in internet order,</li> + * <li>the RSA-PSS signature bytes in internet order.</li> * </ol> - * + * * @param signature the signature to encode, consisting of the output of the - * <code>sign()</code> method of a {@link RSAPSSSignature} instance --a byte - * array. + * <code>sign()</code> method of a {@link RSAPSSSignature} instance + * --a byte array. * @return the <i>Raw</i> 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/gnu/java/security/util/Base64.java b/gnu/java/security/util/Base64.java index 6c4657b7c..38a1c7e1e 100644 --- a/gnu/java/security/util/Base64.java +++ b/gnu/java/security/util/Base64.java @@ -50,6 +50,7 @@ import java.util.logging.Logger; public class Base64 { 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; @@ -64,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 * <code>encode(source, 0, source.length)</code>. - * + * * @param src the data to convert. */ public static final String encode(final byte[] src) @@ -146,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. @@ -159,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; @@ -175,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); } @@ -238,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; } /** - * <p>Encodes up to three bytes of the array <code>src</code> and writes - * the resulting four Base64 bytes to <code>dest</code>. The source and + * Encodes up to three bytes of the array <code>src</code> and writes the + * resulting four Base64 bytes to <code>dest</code>. The source and * destination arrays can be manipulated anywhere along their length by - * specifying <code>sOffset</code> and <code>dOffset</code>.</p> - * - * <p>This method does not check to make sure the arrays are large enough to + * specifying <code>sOffset</code> and <code>dOffset</code>. + * <p> + * This method does not check to make sure the arrays are large enough to * accomodate <code>sOffset + 3</code> for the <code>src</code> array or * <code>dOffset + 4</code> for the <code>dest</code> array. The actual * number of significant bytes in the input array is given by - * <code>numBytes</code>.</p> - * + * <code>numBytes</code>. + * * @param src the array to convert. * @param sOffset the index where conversion begins. * @param numBytes the number of significant bytes in your array. @@ -285,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; @@ -313,19 +286,18 @@ public class Base64 } /** - * <p>Decodes four bytes from array <code>src</code> and writes the - * resulting bytes (up to three of them) to <code>dest</code>.</p> - * - * <p>The source and destination arrays can be manipulated anywhere along - * their length by specifying <code>sOffset</code> and <code>dOffset</code>. - * </p> - * - * <p>This method does not check to make sure your arrays are large enough - * to accomodate <code>sOffset + 4</code> for the <code>src</code> array or + * Decodes four bytes from array <code>src</code> and writes the resulting + * bytes (up to three of them) to <code>dest</code>. + * <p> + * The source and destination arrays can be manipulated anywhere along their + * length by specifying <code>sOffset</code> and <code>dOffset</code>. + * <p> + * This method does not check to make sure your arrays are large enough to + * accomodate <code>sOffset + 4</code> for the <code>src</code> array or * <code>dOffset + 3</code> for the <code>dest</code> array. This method * returns the actual number of bytes that were converted from the Base64 - * encoding.</p> - * + * encoding. + * * @param src the array to convert. * @param sOffset the index where conversion begins. * @param dest the array to hold the conversion. @@ -335,32 +307,30 @@ public class Base64 private static final int decode4to3(final byte[] src, final int sOffset, final byte[] dest, final int dOffset) { - if (src[sOffset + 2] == EQUALS_SIGN) - { // Example: Dk== - final int outBuff = ((DECODABET[src[sOffset]] & 0xFF) << 18) - | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12); - dest[dOffset] = (byte) (outBuff >>> 16); + if (src[sOffset + 2] == EQUALS_SIGN) // Example: Dk== + { + final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18) + | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12); + dest[dOffset] = (byte)(outBuff >>> 16); return 1; } - - if (src[sOffset + 3] == EQUALS_SIGN) - { // Example: DkL= - final int outBuff = ((DECODABET[src[sOffset]] & 0xFF) << 18) - | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12) - | ((DECODABET[src[sOffset + 2]] & 0xFF) << 6); - dest[dOffset] = (byte) (outBuff >>> 16); - dest[dOffset + 1] = (byte) (outBuff >>> 8); + if (src[sOffset + 3] == EQUALS_SIGN) // Example: DkL= + { + final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18) + | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12) + | ((DECODABET[src[sOffset + 2]] & 0xFF) << 6); + dest[dOffset ] = (byte)(outBuff >>> 16); + dest[dOffset + 1] = (byte)(outBuff >>> 8); return 2; } - - try - { // Example: DkLE - final int outBuff = ((DECODABET[src[sOffset]] & 0xFF) << 18) - | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12) - | ((DECODABET[src[sOffset + 2]] & 0xFF) << 6) - | ((DECODABET[src[sOffset + 3]] & 0xFF)); - dest[dOffset] = (byte) (outBuff >> 16); - dest[dOffset + 1] = (byte) (outBuff >> 8); + try // Example: DkLE + { + final int outBuff = ((DECODABET[src[sOffset ]] & 0xFF) << 18) + | ((DECODABET[src[sOffset + 1]] & 0xFF) << 12) + | ((DECODABET[src[sOffset + 2]] & 0xFF) << 6) + | ((DECODABET[src[sOffset + 3]] & 0xFF)); + dest[dOffset ] = (byte)(outBuff >> 16); + dest[dOffset + 1] = (byte)(outBuff >> 8); dest[dOffset + 2] = (byte) outBuff; return 3; } diff --git a/gnu/java/security/util/ExpirableObject.java b/gnu/java/security/util/ExpirableObject.java index c14b75957..e0c4e6b59 100644 --- a/gnu/java/security/util/ExpirableObject.java +++ b/gnu/java/security/util/ExpirableObject.java @@ -46,26 +46,23 @@ import javax.security.auth.Destroyable; /** * The base class for objects with sensitive data that are automatically - * 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. - * - * <p>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 <code>destroy()</code>. - * - * <p>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. + * <p> + * 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 <code>destroy()</code>. + * <p> + * 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 <i>delay</i> is negative, or if - * <code>delay + System.currentTimeMillis()</code> is negative. + * <code>delay + System.currentTimeMillis()</code> 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/gnu/java/security/util/PRNG.java b/gnu/java/security/util/PRNG.java index 138cc6bcb..7bb27cbf4 100644 --- a/gnu/java/security/util/PRNG.java +++ b/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 <code>buffer</code> 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 <code>buffer</code> are * replaced with pseudo-random data, iff the <code>buffer</code> * size is not zero. diff --git a/gnu/java/security/util/Sequence.java b/gnu/java/security/util/Sequence.java index 1bdafa30e..5e3a64eaf 100644 --- a/gnu/java/security/util/Sequence.java +++ b/gnu/java/security/util/Sequence.java @@ -44,24 +44,18 @@ import java.util.LinkedList; /** * A monotonic sequence of integers in the finite field 2<sup>32</sup>. */ -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 <i>end</i>, with an increment - * of 1. If <i>end</i> 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 <i>end</i>, with an increment of + * 1. If <i>end</i> 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 <i>start</i> to <i>end</i>, with an - * increment of 1. If <i>end</i> is less than <i>start</i>, 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 <i>end</i> is less than <i>start</i>, 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 <i>span</i>. If <i>end</i> is less than <i>start</i>, 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. - * - * <p><i>span</i> can be negative, resulting in a decresing sequence. - * - * <p>If <i>span</i> is 0, then the sequence will contain {<i>start</i>, + * <p> + * <i>span</i> can be negative, resulting in a decresing sequence. + * <p> + * If <i>span</i> is 0, then the sequence will contain {<i>start</i>, * <i>end</i>} if <i>start</i> != <i>end</i>, or just the singleton * <i>start</i> if <i>start</i> == <i>end</i>. - * + * * @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[] { Integer.valueOf(start), Integer.valueOf(end) }; - } + sequence = new Integer[] { Integer.valueOf(start), + Integer.valueOf(end) }; else - { - sequence = new Integer[] { Integer.valueOf(start) }; - } + sequence = new Integer[] { Integer.valueOf(start) }; } else { LinkedList l = new LinkedList(); for (int i = start; i != end; i += span) - { - l.add(Integer.valueOf(i)); - } + 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/gnu/java/security/util/SimpleList.java b/gnu/java/security/util/SimpleList.java index 8636b4e14..74f3bafce 100644 --- a/gnu/java/security/util/SimpleList.java +++ b/gnu/java/security/util/SimpleList.java @@ -43,24 +43,18 @@ 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 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/gnu/java/security/util/Util.java b/gnu/java/security/util/Util.java index f39afb931..c7a6810fb 100644 --- a/gnu/java/security/util/Util.java +++ b/gnu/java/security/util/Util.java @@ -41,47 +41,37 @@ package gnu.java.security.util; import java.math.BigInteger; /** - * <p>A collection of utility methods used throughout this project.</p> + * A collection of utility methods used throughout this project. */ public class Util { - - // Constants and variables - // ------------------------------------------------------------------------- - // Hex charset private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray(); // Base-64 charset - private static final String BASE64_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./"; + private static final String BASE64_CHARS = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz./"; private static final char[] BASE64_CHARSET = BASE64_CHARS.toCharArray(); - // Constructor(s) - // ------------------------------------------------------------------------- - /** Trivial constructor to enforce Singleton pattern. */ private Util() { super(); } - // Class methods - // ------------------------------------------------------------------------- - /** - * <p>Returns a string of hexadecimal digits from a byte array. Each byte is - * converted to 2 hex symbols; zero(es) included.</p> - * - * <p>This method calls the method with same name and three arguments as:</p> - * + * Returns a string of hexadecimal digits from a byte array. Each byte is + * converted to 2 hex symbols; zero(es) included. + * <p> + * This method calls the method with same name and three arguments as: * <pre> - * toString(ba, 0, ba.length); + * toString(ba, 0, ba.length); * </pre> - * + * * @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 } /** - * <p>Returns a string of hexadecimal digits from a byte array, starting at - * <code>offset</code> and consisting of <code>length</code> bytes. Each byte - * is converted to 2 hex symbols; zero(es) included.</p> - * + * Returns a string of hexadecimal digits from a byte array, starting at + * <code>offset</code> and consisting of <code>length</code> 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); } /** - * <p>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.</p> - * - * <p>This method calls the method with same name and three arguments as:</p> - * + * 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. + * <p> + * This method calls the method with same name and three arguments as: * <pre> - * toReversedString(ba, 0, ba.length); + * toReversedString(ba, 0, ba.length); * </pre> - * + * * @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 } /** - * <p>Returns a string of hexadecimal digits from a byte array, starting at - * <code>offset</code> and consisting of <code>length</code> bytes. Each byte - * is converted to 2 hex symbols; zero(es) included.</p> - * - * <p>The byte array is treated as a large little-endian integer, and - * is returned as a large big-endian integer.</p> - * + * Returns a string of hexadecimal digits from a byte array, starting at + * <code>offset</code> and consisting of <code>length</code> bytes. Each + * byte is converted to 2 hex symbols; zero(es) included. + * <p> + * 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); } /** - * <p>Returns a byte array from a string of hexadecimal digits.</p> - * + * <p> + * Returns a byte array from a string of hexadecimal digits. + * </p> + * * @param s a string of hexadecimal ASCII characters * @return the decoded byte array from the input hexadecimal string. */ @@ -174,22 +164,20 @@ public class Util byte[] result = new byte[((limit + 1) / 2)]; int i = 0, j = 0; if ((limit % 2) == 1) - { - result[j++] = (byte) fromDigit(s.charAt(i++)); - } + result[j++] = (byte) fromDigit(s.charAt(i++)); while (i < limit) { - result[j] = (byte) (fromDigit(s.charAt(i++)) << 4); + result[j ] = (byte) (fromDigit(s.charAt(i++)) << 4); result[j++] |= (byte) fromDigit(s.charAt(i++)); } return result; } /** - * <p>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.</p> - * + * 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. + * * @param s a string of hexadecimal ASCII characters * @return the decoded byte array from the input hexadecimal string. */ @@ -199,45 +187,37 @@ public class Util byte[] result = new byte[((limit + 1) / 2)]; int i = 0; if ((limit % 2) == 1) - { - result[i++] = (byte) fromDigit(s.charAt(--limit)); - } + result[i++] = (byte) fromDigit(s.charAt(--limit)); while (limit > 0) { - result[i] = (byte) fromDigit(s.charAt(--limit)); + result[i ] = (byte) fromDigit(s.charAt(--limit)); result[i++] |= (byte) (fromDigit(s.charAt(--limit)) << 4); } return result; } /** - * <p>Returns a number from <code>0</code> to <code>15</code> corresponding - * to the designated hexadecimal digit.</p> - * + * Returns a number from <code>0</code> to <code>15</code> 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); } /** - * <p>Returns a string of 8 hexadecimal digits (most significant digit first) - * corresponding to the unsigned integer <code>n</code>.</p> - * + * Returns a string of 8 hexadecimal digits (most significant digit first) + * corresponding to the unsigned integer <code>n</code>. + * * @param n the unsigned integer to convert. * @return a hexadecimal string 8-character long. */ @@ -253,8 +233,8 @@ public class Util } /** - * <p>Returns a string of hexadecimal digits from an integer array. Each int - * is converted to 4 hex symbols.</p> + * Returns a string of hexadecimal digits from an integer array. Each int is + * converted to 4 hex symbols. */ public static String toString(int[] ia) { @@ -268,17 +248,17 @@ public class Util buf[j++] = HEX_DIGITS[(k >>> 20) & 0x0F]; buf[j++] = HEX_DIGITS[(k >>> 16) & 0x0F]; buf[j++] = HEX_DIGITS[(k >>> 12) & 0x0F]; - buf[j++] = HEX_DIGITS[(k >>> 8) & 0x0F]; - buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F]; - buf[j++] = HEX_DIGITS[k & 0x0F]; + buf[j++] = HEX_DIGITS[(k >>> 8) & 0x0F]; + buf[j++] = HEX_DIGITS[(k >>> 4) & 0x0F]; + buf[j++] = HEX_DIGITS[ k & 0x0F]; } return new String(buf); } /** - * <p>Returns a string of 16 hexadecimal digits (most significant digit first) - * corresponding to the unsigned long <code>n</code>.</p> - * + * Returns a string of 16 hexadecimal digits (most significant digit first) + * corresponding to the unsigned long <code>n</code>. + * * @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); } /** - * <p>Similar to the <code>toString()</code> method except that the Unicode + * Similar to the <code>toString()</code> 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.</p> - * + * eg. s-box values. + * * @throws ArrayIndexOutOfBoundsException if the length is odd. */ public static String toUnicodeString(byte[] ba) @@ -307,11 +287,11 @@ public class Util } /** - * <p>Similar to the <code>toString()</code> method except that the Unicode + * Similar to the <code>toString()</code> 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.</p> - * + * eg. s-box values. + * * @throws ArrayIndexOutOfBoundsException if the length is odd. */ public static final String toUnicodeString(byte[] ba, int offset, int length) @@ -324,31 +304,27 @@ public class Util while (i < length) { sb.append("\\u"); - k = ba[offset + i++]; sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]); - sb.append(HEX_DIGITS[k & 0x0F]); - + sb.append(HEX_DIGITS[ k & 0x0F]); k = ba[offset + i++]; sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]); - sb.append(HEX_DIGITS[k & 0x0F]); - + sb.append(HEX_DIGITS[ k & 0x0F]); if ((++j % 8) == 0) - { - sb.append("\"+").append('\n').append("\""); - } + sb.append("\"+").append('\n').append("\""); } sb.append("\"").append('\n'); return sb.toString(); } /** - * <p>Similar to the <code>toString()</code> method except that the Unicode + * Similar to the <code>toString()</code> 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.</p> - * - * @throws ArrayIndexOutOfBoundsException if the length is not a multiple of 4. + * strings; eg. s-box values. + * + * @throws ArrayIndexOutOfBoundsException if the length is not a multiple of + * 4. */ public static String toUnicodeString(int[] ia) { @@ -367,14 +343,11 @@ public class Util sb.append(HEX_DIGITS[(k >>> 16) & 0x0F]); sb.append("\\u"); sb.append(HEX_DIGITS[(k >>> 12) & 0x0F]); - sb.append(HEX_DIGITS[(k >>> 8) & 0x0F]); - sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]); - sb.append(HEX_DIGITS[k & 0x0F]); - + sb.append(HEX_DIGITS[(k >>> 8) & 0x0F]); + sb.append(HEX_DIGITS[(k >>> 4) & 0x0F]); + sb.append(HEX_DIGITS[ k & 0x0F]); if ((++j % 4) == 0) - { - sb.append("\"+").append('\n').append("\""); - } + sb.append("\"+").append('\n').append("\""); } sb.append("\"").append('\n'); return sb.toString(); @@ -388,20 +361,20 @@ public class Util for (int i = 0; i < limit; i++) { c = s.charAt(i >>> 1); - result[i] = (byte) (((i & 1) == 0) ? c >>> 8 : c); + result[i] = (byte)(((i & 1) == 0) ? c >>> 8 : c); } return result; } /** - * <p>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 <code>m</code> is prepended to the start of each - * line.</p> - * - * <p>If <code>offset</code> and <code>length</code> are omitted, the whole + * line. + * <p> + * If <code>offset</code> and <code>length</code> are omitted, the whole * array is used. If <code>m</code> is omitted, nothing is prepended to each - * line.</p> - * + * line. + * * @param data the byte array to be dumped. * @param offset the offset within <i>data</i> to start from. * @param length the number of bytes to dump. @@ -411,23 +384,17 @@ public class Util public static String dumpString(byte[] data, int offset, int length, String m) { if (data == null) - { - return m + "null\n"; - } + return m + "null\n"; StringBuffer sb = new StringBuffer(length * 3); if (length > 32) - { - sb.append(m).append("Hexadecimal dump of ").append(length).append( - " bytes...\n"); - } + sb.append(m).append("Hexadecimal dump of ") + .append(length).append(" bytes...\n"); // each line will list 32 bytes in 4 groups of 8 each int end = offset + length; String s; int l = Integer.toString(length).length(); if (l < 4) - { - l = 4; - } + l = 4; for (; offset < end; offset += 32) { if (length > 32) @@ -437,16 +404,10 @@ public class Util } int i = 0; for (; i < 32 && offset + i + 7 < end; i += 8) - { - sb.append(toString(data, offset + i, 8)).append(' '); - } + sb.append(toString(data, offset + i, 8)).append(' '); if (i < 32) - { - for (; i < 32 && offset + i < end; i++) - { - sb.append(byteToString(data[offset + i])); - } - } + for (; i < 32 && offset + i < end; i++) + sb.append(byteToString(data[offset + i])); sb.append('\n'); } return sb.toString(); @@ -468,9 +429,9 @@ public class Util } /** - * <p>Returns a string of 2 hexadecimal digits (most significant digit first) - * corresponding to the lowest 8 bits of <code>n</code>.</p> - * + * Returns a string of 2 hexadecimal digits (most significant digit first) + * corresponding to the lowest 8 bits of <code>n</code>. + * * @param n the byte value to convert. * @return a string of 2 hex characters representing the input. */ @@ -481,15 +442,15 @@ public class Util } /** - * <p>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).</p> - * - * <p>Used by SASL password file manipulation primitives.</p> - * + * '.' (dot) shall be used instead of "+' (plus). + * <p> + * 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"; } /** - * <p>The inverse function of the above.</p> - * - * <p>Converts a string representing the encoding of some bytes in Base-64 - * to their original form.</p> - * + * The inverse function of the above. + * <p> + * 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 <code>str</code>. - * @throws NumberFormatException if <code>str</code> is <code>null</code>, or - * <code>str</code> contains an illegal Base-64 character. + * @throws NumberFormatException if <code>str</code> is <code>null</code>, + * or <code>str</code> 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 ---------------------------------------------------- /** - * <p>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.</p> - * + * leading zeroes are found. + * * @param n the {@link BigInteger} to trim. * @return the byte array representation of the designated {@link BigInteger} - * with no leading 0-bytes. + * with no leading 0-bytes. */ public static final byte[] trim(BigInteger n) { byte[] in = n.toByteArray(); if (in.length == 0 || in[0] != 0) - { - return in; - } + return in; int len = in.length; int i = 1; while (in[i] == 0 && i < len) - { - ++i; - } + ++i; byte[] result = new byte[len - i]; System.arraycopy(in, i, result, 0, len - i); return result; } /** - * <p>Returns a hexadecimal dump of the trimmed bytes of a {@link BigInteger}. - * </p> - * + * Returns a hexadecimal dump of the trimmed bytes of a {@link BigInteger}. + * * @param x the {@link BigInteger} to display. * @return the string representation of the designated {@link BigInteger}. */ |
