You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@harmony.apache.org by Oliver Deakin <ol...@googlemail.com> on 2006/07/25 12:26:44 UTC

Re: svn commit: r425020 - in /incubator/harmony/enhanced/classlib/trunk: make/ modules/security/ modules/security/make/ modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/ modules/security/src/main/java/linux/ modules/securit...

Hi Mikhail,

This commit has broken the Windows build - the culprit is the #include 
"harmony.h" line
in getWindowsRandom.c. The fix for this is trivial [1].

harmony.h was removed as part of HARMONY-695, and should no longer exist 
in anyones
deploy/include directory. I think this failure was not spotted earlier 
because when
the global build carries out a clean, it calls all the modular clean 
targets, which explicitly
clean up the resources that they have put into the deploy/include dir. 
However, if harmony.h
is still laying around from pre-H695 days, then no module will 
explicitly delete it, and it
will remain there for future builds unless manually removed.
To make sure that any leftover artifacts like this are properly cleaned 
up, the build system
should really call all the modular clean targets, as usual, and then 
remove anything
left in the deploy directory that isnt a VM (ie everything except 
subdirectories of
deploy/jdk/jre/bin). Here is a patch [2] that will properly cleanup the 
include
directories, and should expose any further build failures of this type.

Regards,
Oliver

[1]
Index: modules/security/src/main/native/security/windows/getWindowsRandom.c
===================================================================
--- 
modules/security/src/main/native/security/windows/getWindowsRandom.c    
(revision 425342)
+++ 
modules/security/src/main/native/security/windows/getWindowsRandom.c    
(working copy)
@@ -25,7 +25,7 @@
 
 #include <sddl.h>
 
-#include "harmony.h"
+#include "vmi.h"
 #include "jni.h"
 
 JNIEXPORT jint JNICALL


[2]
Index: make/build-native.xml
===================================================================
--- make/build-native.xml    (revision 425342)
+++ make/build-native.xml    (working copy)
@@ -177,6 +177,11 @@
              target="clean.native.includes" />
         <ant dir="modules/luni" antfile="build.xml"
              target="clean.native.includes" />
+       
+        <!-- delete the deploy/include and deploy/jdk/include
+        directories -->
+        <delete dir="${hy.hdk}/include" />
+        <delete dir="${hy.hdk}/jdk/include" />
     </target>
 
     <!-- =================================


mloenko@apache.org wrote:
> Author: mloenko
> Date: Mon Jul 24 05:01:54 2006
> New Revision: 425020
>
> URL: http://svn.apache.org/viewvc?rev=425020&view=rev
> Log:
> crypto provider improvements from:
> HARMONY-837 (two new classes - provider and MessageDigest implementation)
> HARMONY-872 (SecureRandom implementation)
> HARMONY-902 (SecureRandom, the "RandomBitsSupplier" class for Windows platform)
> also adjusted the build
>
> Added:
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/CryptoProvider.java
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1PRNG_SecureRandomImpl.java
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/security/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/security/provider/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/security/provider/crypto/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/security/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/security/provider/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/security/provider/crypto/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/   (with props)
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/getWindowsRandom.c
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.def
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.rc
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/makefile
>     incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/security_copyright.c
> Modified:
>     incubator/harmony/enhanced/classlib/trunk/make/build-java.xml
>     incubator/harmony/enhanced/classlib/trunk/make/build-native.xml
>     incubator/harmony/enhanced/classlib/trunk/modules/security/build.xml
>     incubator/harmony/enhanced/classlib/trunk/modules/security/make/hyproperties.xml
>
> Modified: incubator/harmony/enhanced/classlib/trunk/make/build-java.xml
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/make/build-java.xml?rev=425020&r1=425019&r2=425020&view=diff
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/make/build-java.xml (original)
> +++ incubator/harmony/enhanced/classlib/trunk/make/build-java.xml Mon Jul 24 05:01:54 2006
> @@ -119,6 +119,7 @@
>              <src path="modules/regex/src/main/java" />
>              <src path="modules/${hy.rmi.module}/src/main/java" />
>              <src path="modules/security-kernel/src/main/java" />
> +            <src path="modules/security/src/main/java/${hy.os}" />
>              <src path="modules/security/src/main/java/common" />
>              <src path="modules/sql/src/main/java" />
>              <src path="modules/swing/src/main/java/${hy.os}" />
>
> Modified: incubator/harmony/enhanced/classlib/trunk/make/build-native.xml
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/make/build-native.xml?rev=425020&r1=425019&r2=425020&view=diff
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/make/build-native.xml (original)
> +++ incubator/harmony/enhanced/classlib/trunk/make/build-native.xml Mon Jul 24 05:01:54 2006
> @@ -76,6 +76,7 @@
>          <ant dir="modules/nio" antfile="build.xml" target="build.native" />    	
>          <ant dir="modules/misc" antfile="build.xml" target="build.native" />    	
>          <ant dir="modules/awt" antfile="build.xml" target="build.native" />    	
> +        <ant dir="modules/security" antfile="build.xml" target="build.native" />    	
>      </target>
>  
>  
> @@ -94,6 +95,7 @@
>      	<ant dir="modules/nio" antfile="build.xml" target="clean.native" />
>      	<ant dir="modules/misc" antfile="build.xml" target="clean.native" />
>      	<ant dir="modules/awt" antfile="build.xml" target="clean.native" />
> +    	<ant dir="modules/security" antfile="build.xml" target="clean.native" />
>      	<delete dir="${native.lib.target}" />
>      </target>
>  
>
> Modified: incubator/harmony/enhanced/classlib/trunk/modules/security/build.xml
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/build.xml?rev=425020&r1=425019&r2=425020&view=diff
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/build.xml (original)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/build.xml Mon Jul 24 05:01:54 2006
> @@ -38,10 +38,43 @@
>  
>      <property file="../../make/depends.properties" />
>  
> +    <property name="hy.security.src.main.java.platform"
> +              value="${hy.security.src.main.java}/../${hy.os}" />
> +
> +    <property name="hy.security.src.test.java.platform"
> +              value="${hy.security.src.test.java}/../${hy.os}" />
> +
>      <target name="build" depends="compile.java, build.jar" />
>  
>      <target name="test" depends="build, compile.tests, run.tests" />
>  
> +
> +	<!-- Build native code -->
> +    <target name="build.native" if="${hy.security.src.main.native}/security/${hy.os}" >
> +		<exec failonerror="true" 
> +              executable="${make.command}" 
> +              dir="${hy.security.src.main.native}/security/${hy.os}">
> +            <env key="HY_HDK" value="${hy.hdk}" />
> +        </exec>
> +
> +		<!-- Copy the built shared libs over to the jre/bin dir -->
> +		<copy todir="${hy.jdk}/jre/bin" overwrite="yes">
> +			<fileset dir="${hy.security.src.main.native}/security">
> +                <patternset includes="*${shlib.suffix}*" />
> +            </fileset>
> +        </copy>
> +    </target>
> +	
> +	<!-- Clean natives -->
> +    <target name="clean.native" if="${hy.security.src.main.native}/security/${hy.os}" >
> +		<exec failonerror="true" 
> +              executable="${make.command}" 
> +              dir="${hy.security.src.main.native}/security/${hy.os}">
> +            <env key="HY_HDK" value="${hy.hdk}" />
> +		    <arg line="clean" />
> +        </exec>
> +    </target>
> +
>      <target name="clean">
>          <delete failonerror="false">
>              <fileset refid="classes" />
> @@ -55,11 +88,15 @@
>          <mkdir dir="${hy.build}" />
>  
>          <javac sourcepath=""
> -               srcdir="${hy.security.src.main.java}"
>                 destdir="${hy.build}"
>                 source="${hy.javac.source}"
>                 target="${hy.javac.target}"
>                 debug="${hy.javac.debug}">
> +
> +            <src>
> +                <pathelement location="${hy.security.src.main.java}"/>
> +                <pathelement location="${hy.security.src.main.java.platform}" />
> +            </src>
>  
>              <bootclasspath>
>                  <fileset dir="${hy.jdk}/jre/lib/boot">
>
> Modified: incubator/harmony/enhanced/classlib/trunk/modules/security/make/hyproperties.xml
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/make/hyproperties.xml?rev=425020&r1=425019&r2=425020&view=diff
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/make/hyproperties.xml (original)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/make/hyproperties.xml Mon Jul 24 05:01:54 2006
> @@ -20,6 +20,7 @@
>        <src>
>           <main>
>               <java location="src/main/java/common" />
> +             <native location="src/main/native" />
>      	     <resources location="src/main/resources" />
>           </main>
>           <test location="src/test">
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/CryptoProvider.java
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/CryptoProvider.java?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/CryptoProvider.java (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/CryptoProvider.java Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,64 @@
> +/*
> + *  Copyright 2006 The Apache Software Software Foundation or its licensors, as applicable.
> + *
> + *  Licensed under the Apache License, Version 2.0 (the "License");
> + *  you may not use this file except in compliance with the License.
> + *  You may obtain a copy of the License at
> + *
> + *     http://www.apache.org/licenses/LICENSE-2.0
> + *
> + *  Unless required by applicable law or agreed to in writing, software
> + *  distributed under the License is distributed on an "AS IS" BASIS,
> + *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> + *  See the License for the specific language governing permissions and
> + *  limitations under the License.
> + */
> +
> +
> +package org.apache.harmony.security.provider.crypto;
> +
> +
> +import java.security.Provider;
> +import java.security.AccessController;
> +
> +
> +/**
> + * Implementation of Provider for MessageDigest
> + * using a Secure Hash Algorithm, SHA-1;
> + * see SECURE HASH STANDARD, FIPS PUB 180-2
> + * (http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf) <BR>
> + * <BR>
> + * The implementation supports "SHA-1" algorithms described in
> + * JavaTM Cryptography Architecture, API Specification & Reference
> + */
> +
> +
> +public final class CryptoProvider extends Provider {
> +
> +
> +    /**
> +     * Creates a Provider and puts parameters
> +     */
> +    public CryptoProvider() {
> +
> +        super("Crypto", 1.0, "HARMONY CryptoProvider");
> +
> +    //  names of classes implementing services
> +    final String MD_NAME = 
> +                 "org.apache.harmony.security.provider.crypto.SHA1_MessageDigestImpl";
> +
> +        AccessController.doPrivileged( 
> +            new java.security.PrivilegedAction() {
> +                public Object run() {
> +
> +                    put("MessageDigest.SHA-1", MD_NAME);
> +                    put("MessageDigest.SHA-1 ImplementedIn", "Software");
> +                    put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
> +                    put("Alg.Alias.MessageDigest.SHA",  "SHA-1");
> +
> +                    return null;
> +                }
> +            }
> +        );
> +    }
> +}
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1PRNG_SecureRandomImpl.java
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1PRNG_SecureRandomImpl.java?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1PRNG_SecureRandomImpl.java (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1PRNG_SecureRandomImpl.java Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,416 @@
> +/*
> + *  Copyright 2006 The Apache Software Software Foundation or its licensors, as applicable.
> + *
> + *  Licensed under the Apache License, Version 2.0 (the "License");
> + *  you may not use this file except in compliance with the License.
> + *  You may obtain a copy of the License at
> + *
> + *     http://www.apache.org/licenses/LICENSE-2.0
> + *
> + *  Unless required by applicable law or agreed to in writing, software
> + *  distributed under the License is distributed on an "AS IS" BASIS,
> + *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> + *  See the License for the specific language governing permissions and
> + *  limitations under the License.
> + */
> +
> +/*
> + * TODO to add writeObject(ObjectOutputStream) and readObject(ObjectInputStream) for optimal serialization
> + */
> +
> +
> +package org.apache.harmony.security.provider.crypto;
> +
> +import java.security.InvalidParameterException;
> +import java.security.ProviderException;
> +import java.security.SecureRandomSpi;
> +
> +import org.apache.harmony.security.provider.crypto.RandomBitsSupplier;
> +import org.apache.harmony.security.provider.crypto.SHA1Impl;
> +
> +import java.io.Serializable;
> +import java.io.ObjectInputStream;
> +import java.io.ObjectOutputStream;
> +import java.io.IOException;
> +
> +
> +/**
> + * This class extends the SecureRandomSpi class implementing all its abstract methods. <BR>
> + * <BR>
> + * To generate pseudo-random bits, the implementation uses technique described in
> + * the "Random Number Generator (RNG) algoritms" section, Appendix A,
> + * JavaTM Cryptography Architecure, API Specification&Reference <BR>
> + * <BR>
> + * The class implements the Serializable interface.
> + */
> +
> +
> +public class SHA1PRNG_SecureRandomImpl extends SecureRandomSpi 
> +                                       implements Serializable, SHA1_Data {
> +
> +
> +    private static final long serialVersionUID = 283736797212159675L;
> +
> +
> +    // constants to use in expressions operating on bytes in int and long variables:
> +    // END_FLAGS - final bytes in words to append to message; 
> +    //             see "ch.5.1 Padding the Message, FIPS 180-2"
> +    // RIGHT1    - shifts to right for left half of long
> +    // RIGHT2    - shifts to right for right half of long
> +    // LEFT      - shifts to left for bytes
> +    // MASK      - mask to select counter's bytes after shift to right
> +
> +    private static final int[] END_FLAGS = { 0x80000000, 0x800000, 0x8000, 0x80 };
> +
> +    private static final int[] RIGHT1 = { 0, 40, 48, 56 };
> +    private static final int[] RIGHT2 = { 0,  8, 16, 24 };
> +    private static final int[] LEFT   = { 0, 24, 16,  8 };
> +
> +    private static final int[] MASK   = { 0xFFFFFFFF, 0x00FFFFFF, 0x0000FFFF, 0x000000FF };
> +
> +
> +    // HASHBYTES_TO_USE defines # of bytes returned by "computeHash(byte[])"
> +    // to use to form byte array returning by the "nextBytes(byte[])" method
> +    // Note, that this implementation uses more bytes than it is defined
> +    // in the above specification.
> +    private static final int HASHBYTES_TO_USE = 20;
> +
> +    // value of 16 defined in the "SECURE HASH STANDARD", FIPS PUB 180-2
> +    private static final int FRAME_LENGTH = 16;
> +
> +    // miscellanous constans defined in this implementation:
> +    // COUNTER_BASE - initial value to set to "counter" before computing "nextBytes(..)";
> +    //                note, that the exact value is not defined in STANDARD
> +    // HASHCOPY_OFFSET   - offset for copy of current hash in "copies" array
> +    // EXTRAFRAME_OFFSET - offset for extra frame in "copies" array;
> +    //                     as the extra frame follows the current hash frame, 
> +    //                     EXTRAFRAME_OFFSET is equal to length of current hash frame
> +    // FRAME_OFFSET      - offset for frame in "copies" array
> +    // MAX_BYTES - maximum # of seed bytes processing which doesn't require extra frame
> +    //             see (1) comments on usage of "seed" array below and
> +    //             (2) comments in "engineNextBytes(byte[])" method
> +    //
> +    // UNDEFINED  - three states of engine; initially its state is "UNDEFINED"
> +    // SET_SEED     call to "engineSetSeed"  sets up "SET_SEED" state,
> +    // NEXT_BYTES   call to "engineNextByte" sets up "NEXT_BYTES" state
> +
> +    private static final int COUNTER_BASE = 0;
> +
> +    private static final int   HASHCOPY_OFFSET = 0;
> +    private static final int EXTRAFRAME_OFFSET = 5;
> +    private static final int      FRAME_OFFSET = 21;
> +
> +    private static final int MAX_BYTES = 48;
> +
> +    private static final int UNDEFINED  = 0;
> +    private static final int SET_SEED   = 1;
> +    private static final int NEXT_BYTES = 2;
> +
> +
> +    private static SHA1PRNG_SecureRandomImpl myRandom;
> +
> +    // Structure of "seed" array: 
> +    // -  0-79 - words for computing hash
> +    // - 80    - unused 
> +    // - 81    - # of seed bytes in current seed frame
> +    // - 82-86 - 5 words, current seed hash
> +    private transient int seed[];
> +
> +    // total length of seed bytes, including all processed
> +    private transient long seedLength;
> +
> +    // Structure of "copies" array
> +    // -  0-4  - 5 words, copy of current seed hash
> +    // -  5-20 - extra 16 words frame; 
> +    //           is used if final padding exceeds 512-bit length 
> +    // - 21-36 - 16 word frame to store a copy of remaining bytes
> +    private transient int copies[];
> +
> +    // ready "next" bytes; needed because words are returned
> +    private transient byte nextBytes[];
> +
> +    // index of used bytes in "nextBytes" array
> +    private transient int nextBIndex;
> +
> +    // variable required according to "SECURE HASH STANDARD"
> +    private transient long counter;
> +
> +    // contains int value corresponding to engine's current state 
> +    private transient int state;
> +
> +    // The "seed" array is used to compute both "current seed hash" and "next bytes".
> +    //
> +    // As the "SHA1" algorithm computes a hash of entire seed by spletting it into
> +    // a number of the 512-bit length frames (512 bits = 64 bytes = 16 words),
> +    // "current seed hash" is a hash (5 words, 20 bytes) for all previous full frames;
> +    // remaining bytes are stored in the 0-15 word frame of the "seed" array.
> +    //
> +    // As for calculating "next bytes",
> +    // both remaining bytes and "current seed hash" are used,
> +    // to preserve the latter for following "setSeed(..)" commands,
> +    // the following technique is used:
> +    // - upon getting "nextBytes(byte[])" invoked, single or first in row,
> +    //   which requires computing new hash, that is, 
> +    //   there is no more bytes remaining from previous "next bytes" computation,
> +    //   remaining bytes are copied into the 21-36 word frame of the "copies" array;
> +    // - upon getting "setSeed(byte[])" invoked, single or first in row,
> +    //   remaining bytes are copied back. 
> +
> +
> +    /**
> +     *  Creates object and sets implementation variables to their initial values
> +     */ 
> +    public SHA1PRNG_SecureRandomImpl() {
> +
> +        seed = new int[HASH_OFFSET + EXTRAFRAME_OFFSET];
> +        seed[HASH_OFFSET   ] = H0;
> +        seed[HASH_OFFSET +1] = H1;
> +        seed[HASH_OFFSET +2] = H2;
> +        seed[HASH_OFFSET +3] = H3;
> +        seed[HASH_OFFSET +4] = H4;
> +
> +        seedLength = 0;
> +        copies     = new int[2*FRAME_LENGTH + EXTRAFRAME_OFFSET];
> +        nextBytes  = new byte[DIGEST_LENGTH];
> +        nextBIndex = HASHBYTES_TO_USE;
> +        counter    = COUNTER_BASE;
> +        state      = UNDEFINED; 
> +    }
> +
> +    /*
> +     * The method invokes the SHA1Impl's "updateHash(..)" method
> +     * to update current seed frame and
> +     * to compute new intermediate hash value if the frame is full.
> +     * 
> +     * After that it computes a length of whole seed.
> +     */
> +    private void updateSeed(byte[] bytes) {
> +
> +        // on call:   "seed" contains current bytes and current hash;
> +        // on return: "seed" contains new current bytes and possibly new current hash
> +        //            if after adding, seed bytes overfill its buffer
> +        SHA1Impl.updateHash(seed, bytes, 0, bytes.length -1);
> +
> +        seedLength += bytes.length;
> +    }
> +
> +
> +    /**
> +     * Changes current seed by supplementing a seed argument to the current seed,
> +     * if this already set;
> +     * the argument is used as first seed othewise. <BR>
> +     *
> +     * The method overrides "engineSetSeed(byte[])" in class SecureRandomSpi.
> +     *
> +     * @param
> +     *       seed - byte array
> +     * @throws
> +     *       NullPointerException - if null is passed to the "seed" argument
> +     */
> +    protected void engineSetSeed(byte[] seed) {
> +
> +        if ( seed == null ) {
> +            throw new NullPointerException("null is passed to the 'seed' argument");
> +        }
> +
> +        if ( state == NEXT_BYTES ) {       // first setSeed after NextBytes; restoring hash
> +            System.arraycopy(copies, HASHCOPY_OFFSET, this.seed, HASH_OFFSET, 
> +                             EXTRAFRAME_OFFSET);
> +        }
> +        state = SET_SEED;
> +
> +        if ( seed.length != 0 ) {
> +            updateSeed(seed);
> +        }
> +    }
> +
> +
> +    /**
> +     * Returns a required number of random bytes. <BR>
> +     *
> +     * The method overrides "engineGenerateSeed (int)" in class SecureRandomSpi. <BR>
> +     *
> +     * @param
> +     *       numBytes - number of bytes to return; should be >= 0.
> +     * @return
> +     *       byte array containing bits in order from left to right
> +     * @throws
> +     *       InvalidParameterException - if numBytes < 0
> +     */
> +    protected byte[] engineGenerateSeed(int numBytes) {
> +
> +        byte[] myBytes;        // byte[] for bytes returned by "nextBytes()"
> +
> +        if ( numBytes < 0 ) {
> +            throw new NegativeArraySizeException("numBytes=" + numBytes);
> +        }
> +        if ( numBytes == 0 ) {
> +            return new byte[0];
> +        }
> +
> +        if ( myRandom == null ) {
> +            myRandom = new SHA1PRNG_SecureRandomImpl();
> +            myRandom.engineSetSeed(RandomBitsSupplier.getRandomBits(DIGEST_LENGTH));
> +        }
> +
> +        myBytes = new byte[numBytes];
> +        myRandom.engineNextBytes(myBytes);
> +
> +        return myBytes;
> +    }
> +
> +
> +    /**
> +     * Writes random bytes into an array suppied.
> +     * Bits in a byte are from left to right. <BR>
> +     *
> +     * To generate random bytes, the "expansion of source bits" method is used,
> +     * that is,
> +     * the current seed with a 64-bit counter appended is used to compute new bits.
> +     * The counter is incremented by 1 for each 20-byte output. <BR>
> +     *
> +     * The method overrides engineNextBytes in class SecureRandomSpi.
> +     *
> +     * @param
> +     *       bytes - byte array to be filled in with bytes
> +     * @throws
> +     *       NullPointerException - if null is passed to the "bytes" argument
> +     */
> +    protected void engineNextBytes(byte[] bytes) {
> +
> +        int i, n;
> +
> +        long bits;               // number of bits required by Secure Hash Standard
> +        int nextByteToReturn;    // index of ready bytes in "bytes" array
> +        int  lastWord;           // index of last word in frame containing bytes
> +        final int extrabytes = 7;// # of bytes to add in order to computer # of 8 byte words
> +
> +        if ( bytes == null ) {
> +            throw new NullPointerException("null is passed to the 'bytes' argument");
> +        }
> +
> +        lastWord = seed[BYTES_OFFSET] == 0 ? 0 : (seed[BYTES_OFFSET] + extrabytes)>>3 -1 ;
> +
> +        if (state == UNDEFINED) {
> +
> +            // no seed supplied by user, hence it is generated thus randomizing internal state
> +            updateSeed(RandomBitsSupplier.getRandomBits(DIGEST_LENGTH));
> +            nextBIndex = HASHBYTES_TO_USE;
> +
> +        } else if (state == SET_SEED) {
> +
> +            System.arraycopy(seed, HASH_OFFSET, copies, HASHCOPY_OFFSET, EXTRAFRAME_OFFSET);
> +
> +            // possible cases for 64-byte frame:
> +            //
> +            // seed bytes < 48      - remaining bytes are enough for all, 8 counter bytes, 
> +            //                        0x80, and 8 seedLength bytes; no extra frame required
> +            // 48 < seed bytes < 56 - remaining 9 bytes are for 0x80 and 8 counter bytes
> +            //                        extra frame contains only seedLength value at the end
> +            // seed bytes > 55      - extra frame contains both counter's bytes
> +            //                        at the beginning and seedLength value at the end;
> +            //                        note, that beginning extra bytes are not more than 8,
> +            //                        that is, only 2 extra words may be used
> +
> +            // no need to set to "0" 3 words after "lastWord" and  
> +            // more than two words behind frame 
> +            for ( i = lastWord +3; i < FRAME_LENGTH +2 ; i++ ) { 
> +                seed[i] = 0;                                    
> +            }
> +
> +            bits = seedLength<<3 + 64;    // transforming # of bytes into # of bits
> +
> +            // putting # of bits into two last words (14,15) of 16 word frame in 
> +            // seed or copies array depending on total length after padding
> +            if ( seed[BYTES_OFFSET] < MAX_BYTES ) {
> +                seed[14] = (int)( bits >>>32 );
> +                seed[15] = (int)( bits & 0xFFFFFFFF );
> +            } else {
> +                copies[EXTRAFRAME_OFFSET + 14] = (int)( bits >>>32 );
> +                copies[EXTRAFRAME_OFFSET + 15] = (int)( bits & 0xFFFFFFFF );
> +            }
> +
> +            nextBIndex = HASHBYTES_TO_USE;    // skipping remaining random bits
> +        }
> +        state = NEXT_BYTES;
> +
> +        if ( bytes.length == 0 ) {
> +            return;
> +        }
> +
> +        nextByteToReturn = 0;
> +
> +        // possibly not all of HASHBYTES_TO_USE bytes were used previous time 
> +        n = (HASHBYTES_TO_USE - nextBIndex) < (bytes.length - nextByteToReturn) ?
> +             HASHBYTES_TO_USE - nextBIndex :
> +             bytes.length - nextByteToReturn ;
> +        if ( n > 0 ) {
> +            System.arraycopy(nextBytes, nextBIndex, bytes, nextByteToReturn, n);
> +            nextBIndex += n;
> +            nextByteToReturn += n;
> +        }
> +
> +        if ( nextByteToReturn >= bytes.length ) {
> +            return;                                // return because "bytes[]" are filled in
> +        }
> +
> +        n = seed[BYTES_OFFSET] & 0x03 ;
> +        for ( ; ; ) {
> +            if ( n == 0 ) {
> +
> +                seed[lastWord   ] = (int)( counter >>>32 );
> +                seed[lastWord +1] = (int)( counter & 0xFFFFFFFF );
> +                seed[lastWord +2] = END_FLAGS[0];
> +
> +            } else {
> +
> +                seed[lastWord   ] |= (int)( ( counter >>> RIGHT1[n] ) & MASK[n] );
> +                seed[lastWord +1]  = (int)( ( counter >>> RIGHT2[n] ) & 0xFFFFFFFF );
> +                seed[lastWord +2]  = (int)( ( counter <<  LEFT  [n] ) | END_FLAGS[n] ) ;
> +            }
> +            if (seed[BYTES_OFFSET] > MAX_BYTES) {
> +                copies[EXTRAFRAME_OFFSET]   = seed[FRAME_LENGTH];
> +                copies[EXTRAFRAME_OFFSET+1] = seed[FRAME_LENGTH+1];
> +            }
> +
> +            SHA1Impl.computeHash(seed);
> +
> +            if ( seed[BYTES_OFFSET] > MAX_BYTES ) {
> +
> +                System.arraycopy(seed, 0, copies, FRAME_OFFSET, FRAME_LENGTH);
> +                System.arraycopy(copies, EXTRAFRAME_OFFSET, seed, 0, FRAME_LENGTH);
> +
> +                SHA1Impl.computeHash(seed);
> +                System.arraycopy(copies, FRAME_OFFSET, seed, 0, FRAME_LENGTH);
> +            }
> +            counter++;
> +
> +            int j = 0;
> +            for ( i = 0; i < EXTRAFRAME_OFFSET; i++ ) {
> +                int k = seed[HASH_OFFSET +i];
> +                nextBytes[j  ] = (byte)( k >>>24 );  // getting first  byte from left
> +                nextBytes[j+1] = (byte)( k >>>16 );  // getting second byte from left
> +                nextBytes[j+2] = (byte)( k >>> 8 );  // getting third  byte from left
> +                nextBytes[j+3] = (byte)( k       );  // getting fourth byte from left
> +                j += 4;
> +            }
> +
> +            nextBIndex = 0;
> +            j = HASHBYTES_TO_USE < ( bytes.length -  nextByteToReturn ) ?
> +                HASHBYTES_TO_USE  :
> +                bytes.length - nextByteToReturn ;
> +
> +            if (j > 0) {
> +                System.arraycopy(nextBytes, 0, bytes, nextByteToReturn, j);
> +                nextByteToReturn += j;
> +                nextBIndex += j;
> +            }
> +
> +            if ( nextByteToReturn >= bytes.length ) {
> +                break;
> +            }
> +        }
> +    }
> +
> +
> +}
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/common/org/apache/harmony/security/provider/crypto/SHA1_MessageDigestImpl.java Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,326 @@
> +/*
> + *  Copyright 2006 The Apache Software Software Foundation or its licensors, as applicable.
> + *
> + *  Licensed under the Apache License, Version 2.0 (the "License");
> + *  you may not use this file except in compliance with the License.
> + *  You may obtain a copy of the License at
> + *
> + *     http://www.apache.org/licenses/LICENSE-2.0
> + *
> + *  Unless required by applicable law or agreed to in writing, software
> + *  distributed under the License is distributed on an "AS IS" BASIS,
> + *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> + *  See the License for the specific language governing permissions and
> + *  limitations under the License.
> + */
> +
> +
> +package org.apache.harmony.security.provider.crypto;
> +
> +
> +import java.security.MessageDigestSpi;
> +import java.security.DigestException;
> +
> +import java.nio.ByteBuffer;
> +import java.nio.BufferUnderflowException;
> +
> +import java.util.Arrays;
> +
> +import org.apache.harmony.security.provider.crypto.SHA1_Data;
> +import org.apache.harmony.security.provider.crypto.SHA1Impl;
> +
> +
> +/**
> + * This class extends the MessageDigestSpi class implementing all its abstract methods;
> + * it overrides the "Object clone()" and "int engineGetDigestLength()" methods. <BR>
> + * The class implements the Cloneable interface.
> + */
> +
> +
> +public class SHA1_MessageDigestImpl extends MessageDigestSpi 
> +                                    implements Cloneable, SHA1_Data {
> +
> +
> +    private  int buffer[];       // buffer has the following structure:
> +                                 // -  0-16 - frame for accumulating a message
> +                                 // - 17-79 - for SHA1Impl methods
> +                                 // - 80    - unused
> +                                 // - 81    - to store length of the message
> +                                 // - 82-86 - frame for current message digest
> +
> +    private byte oneByte[];      // one byte buffer needed to use in engineUpdate(byte)
> +                                 // having buffer as private field is just optimization
> +
> +    private int messageLength;   // total length of bytes supplied by user
> +
> +
> +    /**
> +     *  The constructor creates needed buffers and sets the engine at initial state
> +     */ 
> +    public SHA1_MessageDigestImpl() {
> +
> +        // BYTES_OFFSET +6 is minimal length required by methods in SHA1Impl
> +        buffer  = new int[BYTES_OFFSET +6];
> +
> +        oneByte = new byte[1];
> +
> +        engineReset();
> +    }
> +
> +
> +    /**
> +     * The method performs final actions and invokes the "computeHash(int[])" method.
> +     * In case if there is no enough words in current frame
> +     * after processing its data, extra frame is prepared and 
> +     * the "computeHash(int[])" method is invoked second time. <BR>
> +     *
> +     * After processing, the method resets engine's state
> +     *
> +     * @param
> +     *       digest - byte array
> +     * @param
> +     *       offset - offset in digest
> +     */
> +    private void processDigest(byte[] digest, int offset) {
> +
> +        int i, j;         // implementation variables
> +        int lastWord;     //
> +
> +        long nBits = messageLength <<3 ;  // length has to be calculated before padding
> +
> +        engineUpdate( (byte) 0x80 );      // beginning byte in padding
> +
> +        i = 0;                     // i contains number of beginning word for following loop
> +
> +        lastWord = (buffer[BYTES_OFFSET] + 3)>>2 ;  // computing of # of full words by shifting
> +                                                    // # of bytes
> +
> +        // possible cases:
> +        //
> +        // - buffer[BYTES_OFFSET] == 0 - buffer frame is empty, 
> +        //                         padding byte was 64th in previous frame
> +        //                         current frame should contain only message's length
> +        //
> +        // - lastWord < 14 - two last, these are 14 & 15, words in 16 word frame are free;
> +        //                   no extra frame needed
> +        // - lastWord = 14 - only one last, namely 15-th, word in frame doesn't contain bytes;
> +        //                   extra frame is needed
> +        // - lastWord > 14 - last word in frame is not full; 
> +        //                   extra frame is needed
> +
> +        if ( buffer[BYTES_OFFSET] != 0 ) {
> +
> +            if ( lastWord < 15 ) {
> +                i = lastWord;
> +            } else {
> +                if ( lastWord == 15 ) {
> +                    buffer[15] = 0;       // last word in frame is set to "0"
> +                }
> +                SHA1Impl.computeHash(buffer);
> +                i = 0;
> +            }
> +        }
> +        Arrays.fill(buffer, i, 14, 0);
> +
> +        buffer[14] = (int)( nBits >>>32 );
> +        buffer[15] = (int)( nBits & 0xFFFFFFFF );
> +        SHA1Impl.computeHash(buffer);
> +
> +        // converting 5-word frame into 20 bytes
> +        j = offset;
> +        for ( i = HASH_OFFSET; i < HASH_OFFSET +5; i++ ) {
> +            int k = buffer[i];
> +            digest[j  ] = (byte) ( k >>>24 );   // getting first  byte from left
> +            digest[j+1] = (byte) ( k >>>16 );   // getting second byte from left
> +            digest[j+2] = (byte) ( k >>> 8 );   // getting third  byte from left
> +            digest[j+3] = (byte) ( k       );   // getting fourth byte from left
> +            j += 4;
> +        }
> +
> +        engineReset();
> +    }
> +
> +    //  methods specified in java.security.MessageDigestSpi
> +
> +    /**
> +     * Returns a "deep" copy of this SHA1MDImpl object. <BR>
> +     *
> +     * The method overrides "clone()" in class Object. <BR>
> +     *
> +     * @return
> +     *       a clone of this object
> +     */
> +    public Object clone() throws CloneNotSupportedException {
> +
> +        SHA1_MessageDigestImpl cloneObj = (SHA1_MessageDigestImpl) super.clone();
> +
> +        cloneObj.buffer  = ( int[])buffer.clone();
> +        cloneObj.oneByte = (byte[])oneByte.clone();
> +
> +        return cloneObj;
> +    }
> +
> +
> +    /**
> +     * Computes a message digest value. <BR>
> +     *
> +     * The method resets the engine. <BR>
> +     *
> +     * The method overrides "engineDigest()" in class MessageDigestSpi. <BR>
> +     *
> +     * @return
> +     *       byte array containing message digest value
> +     */
> +    protected byte[] engineDigest() {
> +
> +        byte[] hash = new byte[DIGEST_LENGTH];
> +
> +        processDigest(hash, 0);
> +        return hash;
> +    }
> +
> +
> +    /**
> +     * Computes message digest value.
> +     * Upon return, the value is stored in "buf" buffer beginning "offset" byte. <BR>
> +     *
> +     * The method resets the engine. <BR>
> +     *
> +     * The method overrides "engineDigest(byte[],int,int) in class MessageDigestSpi. 
> +     *
> +     * @param
> +     *       buf    byte array to store a message digest returned      
> +     * @param            
> +     *       offset a position in the array for first byte of the message digest   
> +     * @param
> +     *       len    number of bytes within buffer allotted for the message digest; 
> +     *                as this implementation doesn't provide partial digests,        
> +     *                len should be >= 20, DigestException is thrown otherwise       
> +     * @return
> +     *       the length of the message digest stored in the "buf" buffer;            
> +     *       in this implementation the length=20
> +     *
> +     * @throws IllegalArgumentException       
> +     *               if null is passed to the "buf" argument <BR>
> +     *               if offset + len > buf.length  <BR>
> +     *               if offset > buf.length or len > buf.length
> +     *
> +     * @throws DigestException          
> +     *               if len < 20 
> +     *
> +     * @throws  ArrayIndexOutOfBoundsException 
> +     *               if offset < 0
> +     */
> +    protected int engineDigest(byte[] buf, int offset, int len) throws DigestException { 
> +
> +        if ( buf == null ) {
> +            throw new IllegalArgumentException("null is passed to 'buf' parameter"); 
> +        }
> +        if ( offset > buf.length || len > buf.length || (len + offset) > buf.length ) {
> +            throw new IllegalArgumentException(
> +               "buf.lendth doesn't fit supplied offset and len");
> +        }
> +        if ( len < DIGEST_LENGTH ) {
> +            throw new DigestException(" len < digest's length (which is 20 bytes) ");
> +        }
> +        if ( offset < 0 ) {
> +            throw new ArrayIndexOutOfBoundsException("negative offset: " + offset);
> +        }
> +
> +        processDigest(buf, offset);
> +
> +        return DIGEST_LENGTH;
> +    }
> +
> +
> +    /**
> +     * Returns a message digest length. <BR>
> +     *
> +     * The method overrides "engineGetDigestLength()" in class MessageDigestSpi. <BR>
> +     *
> +     * @return
> +     *        total length of current message digest as an int value
> +     */
> +    protected int engineGetDigestLength() { 
> +        return DIGEST_LENGTH; 
> +    }
> + 
> +
> +    /**
> +     * Resets the engine. <BR>
> +     *
> +     * The method overrides "engineReset()" in class MessageDigestSpi. <BR>
> +     */
> +    protected void engineReset() {
> +
> +        messageLength = 0;
> +
> +        buffer[BYTES_OFFSET] = 0;
> +        buffer[HASH_OFFSET   ] = H0;
> +        buffer[HASH_OFFSET +1] = H1;
> +        buffer[HASH_OFFSET +2] = H2;
> +        buffer[HASH_OFFSET +3] = H3;
> +        buffer[HASH_OFFSET +4] = H4;
> +    }
> +
> +
> +    /**
> +     * Supplements a byte to current message. <BR>
> +     *
> +     * The method overrides "engineUpdate(byte)" in class MessageDigestSpi. <BR>
> +     *
> +     * @param
> +     *       input byte to add to current message
> +     */
> +    protected void engineUpdate(byte input) {
> +
> +        oneByte[0] = input;
> +        SHA1Impl.updateHash( buffer, oneByte, 0, 0 );
> +        messageLength++;
> +    }
> +
> +
> +    /**
> +     * Updates current message. <BR>
> +     *
> +     * The method overrides "engineUpdate(byte[],intint)" in class MessageDigestSpi. <BR>
> +     *
> +     * The method silently returns if "len" <= 0.
> +     *
> +     * @param
> +     *       input  a byte array
> +     * @param
> +     *       offset a number of first byte in the "input" array to use for updating
> +     * @param
> +     *       len    a number of bytes to use
> +     *
> +     * @throws NullPointerException     
> +     *                if null is passed to the "buf" argument
> +     *
> +     * @throws IllegalArgumentException 
> +     *                if offset > buf.length or len > buf.length or 
> +     *                (len + offset) > buf.length
> +     * @throws ArrayIndexOutOfBoundsException
> +     *                offset < 0
> +     */
> +    protected void engineUpdate(byte[] input, int offset, int len) {
> +
> +        if ( input == null ) {
> +            throw new IllegalArgumentException("no byte[] passed to 'input' parameter"); 
> +        }
> +        if ( len <= 0 ) {
> +            return;
> +        }
> +        if ( offset < 0 ) {
> +            throw new ArrayIndexOutOfBoundsException("offset < 0 : " + offset);
> +        }
> +        if ( offset > input.length || len > input.length || (len + offset) > input.length ) {
> +            throw new IllegalArgumentException(
> +               "input.lendth doesn't fit supplied offset and len");
> +        }
> +
> +        SHA1Impl.updateHash(buffer, input, offset, offset + len -1 );
> +        messageLength += len;
> +    }
> +
> +}
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/linux/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,169 @@
> +/*
> + *  Copyright 2006 The Apache Software Software Foundation or its licensors, as applicable.
> + *
> + *  Licensed under the Apache License, Version 2.0 (the "License");
> + *  you may not use this file except in compliance with the License.
> + *  You may obtain a copy of the License at
> + *
> + *     http://www.apache.org/licenses/LICENSE-2.0
> + *
> + *  Unless required by applicable law or agreed to in writing, software
> + *  distributed under the License is distributed on an "AS IS" BASIS,
> + *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> + *  See the License for the specific language governing permissions and
> + *  limitations under the License.
> + */
> +
> +
> +package org.apache.harmony.security.provider.crypto;
> +
> +
> +import java.io.File;
> +import java.io.FileInputStream;
> +import java.io.BufferedInputStream;
> +import java.io.IOException;
> +import java.io.FileNotFoundException;
> +
> +import java.security.ProviderException;
> +import java.security.AccessController;
> +import java.security.PrivilegedActionException;
> +
> +
> +/**
> + *  The static class providing access on Linux paltform
> + *  to system means for generating true random bits. <BR>
> + *
> + *  The source for true random bits is one of Linux's devices "/dev/urandom/" or
> + *  "/dev/random" depends on which one is avalable; if both the first is used. <BR>
> + *
> + *  If no device available the service is not avilable,
> + *  that is, provider shouldn't register the algorithm. <BR>
> + */
> +
> +
> +public class RandomBitsSupplier implements SHA1_Data {
> +
> +
> +    /**
> +     *  BufferedInputStream to read from device
> +     */
> +    private static BufferedInputStream bis = null;
> +
> +    /**
> +     * File to connect to device
> +     */
> +    private static File randomFile = null;
> +
> +    /**
> +     * value of field is "true" only if a device is available
> +     */
> +    private static boolean serviceAvailable;
> +
> +
> +    static {
> +        AccessController.doPrivileged(
> +            new java.security.PrivilegedAction() {
> +                public Object run() {
> +
> +                    for ( int i = 0 ; i < DEVICE_NAMES.length ; i++ ) {
> +                        File file = new File(DEVICE_NAMES[i]);
> +
> +                        try {
> +                            if ( file.canRead() ) {
> +                                bis = new BufferedInputStream(
> +                                          new FileInputStream(file));
> +                                randomFile = file;
> +                                return null;
> +                            }
> +                        } catch (FileNotFoundException e) {
> +                        }
> +                    }
> +                    return null;
> +                }
> +            }
> +        );
> +        serviceAvailable = (bis != null);
> +    }
> +
> +
> +    /**
> +     * The method is called by provider to determine if a device is available.
> +     */
> +    static boolean isServiceAvailable() {
> +        return serviceAvailable;
> +    }
> +
> +
> +    /**
> +     * On the Linux platform with "random" devices available,
> +     * the method reads random bytes from the device.  <BR>
> +     *
> +     * In case of any runtime failure ProviderException gets thrown.
> +     */
> +    private static synchronized byte[] getLinuxRandomBits(int numBytes) {
> +
> +        byte[] bytes = new byte[numBytes];
> +
> +        int total = 0;
> +        int bytesRead;
> +        int offset = 0;
> +        try {
> +            for ( ; ; ) {
> +
> +                bytesRead = bis.read(bytes, offset, numBytes-total);
> +
> +
> +                // the below case should not occur because /dev/random or /dev/urandom is a special file
> +                // hence, if it is happened there is some internal problem
> +                //
> +                if ( bytesRead == -1 ) {
> +                    throw new ProviderException(
> +                        "ATTENTION: 'bytesRead == -1' in getLinuxRandomBits()" );
> +                }
> +
> +                total  += bytesRead;
> +                offset += bytesRead;
> +
> +                if ( total >= numBytes ) {
> +                    break;
> +                }          
> +            }
> +        } catch (IOException e) {
> +
> +            // actually there should be no IOException because device is a special file;
> +            // hence, there is either some internal problem or, for instance,
> +            // device was removed in runtime, or something else
> +            //
> +            throw new ProviderException(
> +                "ATTENTION: IOException in RandomBitsSupplier.getLinuxRandomBits()\n", e );
> +        }
> +        return bytes; 
> +    }
> +
> +
> +    /**
> +     * The method returns byte array of requested length provided service is available.
> +     * ProviderException gets thrown otherwise.
> +     *
> +     * @param
> +     *       numBytes - length of bytes requested
> +     * @return
> +     *       byte array
> +     * @throws
> +     *       InvalidArgumentException - if numBytes <= 0
> +     */
> +    public static byte[] getRandomBits(int numBytes) {
> +
> +        if ( numBytes <= 0 ) {
> +            throw new IllegalArgumentException("numBytes <= 0  : " + numBytes);
> +        }
> +
> +        if ( !serviceAvailable ) {
> +            throw new ProviderException(
> +                "ATTENTION: service is not available : no random devices");
> +        }
> +
> +        return getLinuxRandomBits(numBytes);
> +    }
> +
> +}
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/java/windows/org/apache/harmony/security/provider/crypto/RandomBitsSupplier.java Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,104 @@
> +/*
> + *  Copyright 2006 The Apache Software Software Foundation or its licensors, as applicable.
> + *
> + *  Licensed under the Apache License, Version 2.0 (the "License");
> + *  you may not use this file except in compliance with the License.
> + *  You may obtain a copy of the License at
> + *
> + *     http://www.apache.org/licenses/LICENSE-2.0
> + *
> + *  Unless required by applicable law or agreed to in writing, software
> + *  distributed under the License is distributed on an "AS IS" BASIS,
> + *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> + *  See the License for the specific language governing permissions and
> + *  limitations under the License.
> + */
> +
> +
> +package org.apache.harmony.security.provider.crypto;
> +
> +import java.security.ProviderException;
> +import java.security.AccessController;
> +
> +
> +/**
> + * The static class providing access on Windows paltform
> + * to system means for generating true random bits. <BR>
> + *
> + * It uses a native method to get the random bits from CryptGenRandom.
> + * If the required library is not installed 
> + * the provider shouldn't register the algorithm.
> + */
> +
> +public class RandomBitsSupplier implements SHA1_Data {
> +
> +    /**
> +     * specification for native library
> +     */
> +    private static native boolean getWindowsRandom(byte[] bytes, int numBytes);
> +
> +    /**
> +     * static field is "true" only if native library is linked
> +     */
> +    private static boolean serviceAvailable;
> +
> +
> +    static {
> +        try {
> +            AccessController.doPrivileged(
> +                new java.security.PrivilegedAction() {
> +                    public Object run() throws UnsatisfiedLinkError {
> +                        System.loadLibrary(LIBRARY_NAME); 
> +                        return null;
> +                    }
> +                }
> +            );
> +        } catch (UnsatisfiedLinkError e) {
> +            serviceAvailable = false;
> +        }
> +        serviceAvailable = true;
> +    }
> +
> +
> +    /**
> +     * The method is called by provider to determine if a device is available.
> +     */
> +    static boolean isServiceAvailable() {
> +        return serviceAvailable;
> +    }
> +
> +
> +    /**
> +     * The method returns byte array containing random bits.
> +     *
> +     * @param
> +     *       numBytes - length of bytes requested
> +     * @return
> +     *       byte array
> +     * @throws
> +     *       InvalidArgumentException - if numBytes <= 0         <BR>
> +     *       ProviderException - if some problem related to native library is discovered <BR>
> +     */
> +    public static synchronized byte[] getRandomBits(int numBytes) {
> +
> +        if ( numBytes <= 0 ) {
> +            throw new IllegalArgumentException("numBytes <= 0  : " + numBytes);
> +        }
> +
> +        if ( !serviceAvailable ) {
> +            throw new ProviderException(
> +                "ATTENTION: service is not available : native library is not linked" );
> +        }
> +
> +        byte[] myBytes = new byte[numBytes];
> +
> +        if ( !getWindowsRandom(myBytes, numBytes) ) {
> +
> +            // it is unexpected result
> +            throw new ProviderException(
> +                "ATTENTION: getWindowsRandom(myBytes, numBytes) returned false" );
> +        }
> +
> +        return myBytes;
> +    }
> +}
>
> Propchange: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/
> ------------------------------------------------------------------------------
> --- svn:ignore (added)
> +++ svn:ignore Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,3 @@
> +
> +hysecurity.RES
> +vc70.pdb
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/getWindowsRandom.c
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/getWindowsRandom.c?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/getWindowsRandom.c (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/getWindowsRandom.c Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,64 @@
> +/*
> + *  Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
> + *
> + *  Licensed under the Apache License, Version 2.0 (the "License");
> + *  you may not use this file except in compliance with the License.
> + *  You may obtain a copy of the License at
> + *
> + *     http://www.apache.org/licenses/LICENSE-2.0
> + *
> + *  Unless required by applicable law or agreed to in writing, software
> + *  distributed under the License is distributed on an "AS IS" BASIS,
> + *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> + *  See the License for the specific language governing permissions and
> + *  limitations under the License.
> + */
> +
> +#undef _WIN32_WINNT
> +#define _WIN32_WINNT 0x0500
> +
> +#include <stdio.h>
> +
> +#include <windows.h>
> +#include <wincrypt.h>
> +#include <winerror.h>
> +
> +#include <sddl.h>
> +
> +#include "harmony.h"
> +#include "jni.h"
> +
> +JNIEXPORT jint JNICALL
> +Java_org_apache_harmony_security_provider_crypto_RandomBitsSupplier_getWindowsRandom(JNIEnv *env, jclass obj, jbyteArray bytes, jint numBytes)
> +{
> +    HCRYPTPROV hcrypt_provider;
> +
> +    byte * random_bits;
> +    int true  = 1;
> +    int false = 0;
> +
> +    int b;
> +
> +    b = CryptAcquireContext( &hcrypt_provider, NULL, NULL, PROV_DSS, CRYPT_VERIFYCONTEXT );
> +
> +     if ( !b ) {
> +        return false;
> +    }
> +
> +	random_bits  = malloc(numBytes);
> +
> +    b = CryptGenRandom( hcrypt_provider, numBytes, random_bits );
> +
> +      if ( !b ){
> +		free(random_bits);
> +        return false;
> +    }
> +
> +    b = CryptReleaseContext(hcrypt_provider, 0);
> +
> +    (*env)->SetByteArrayRegion(env, bytes, 0, numBytes, (signed char*)random_bits);
> +    free(random_bits);
> +
> +    return true;
> +}
> +
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.def
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.def?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.def (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.def Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,8 @@
> +LIBRARY	HYSECURITY
> +
> +SECTIONS
> +	.data	READ WRITE
> +	.text	EXECUTE READ
> +
> +EXPORTS
> +	Java_org_apache_harmony_security_provider_crypto_RandomBitsSupplier_getWindowsRandom
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.rc
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.rc?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.rc (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/hysecurity.rc Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,47 @@
> +;
> +; Copyright 2006 The Apache Software Foundation or its licensors, as applicable
> +; 
> +; Licensed under the Apache License, Version 2.0 (the "License");
> +; you may not use this file except in compliance with the License.
> +; You may obtain a copy of the License at
> +; 
> +;     http://www.apache.org/licenses/LICENSE-2.0
> +; 
> +; Unless required by applicable law or agreed to in writing, software
> +; distributed under the License is distributed on an "AS IS" BASIS,
> +; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> +; See the License for the specific language governing permissions and
> +; limitations under the License.
> +;
> +
> +#include <windows.h>
> +#include <winver.h>
> +
> +VS_VERSION_INFO VERSIONINFO
> + FILEVERSION 0,1,0,0
> + PRODUCTVERSION 0,1,0,0
> + FILEFLAGSMASK 0x3fL
> + FILEFLAGS 0x0L
> + FILEOS VOS_NT_WINDOWS32
> + FILETYPE VFT_DLL
> + FILESUBTYPE 0x0L
> +BEGIN
> +	BLOCK "StringFileInfo"
> +	BEGIN
> +		BLOCK "040904b0"
> +		BEGIN
> +			VALUE "CompanyName", "The Apache Software Foundation.\0"
> +			VALUE "FileDescription", "Security component native code\0"
> +			VALUE "FileVersion", "0.1\0"
> +			VALUE "InternalName", "security\0"
> +			VALUE "LegalCopyright", "(c) Copyright 2005, 2006 The Apache Software Foundation or its licensors, as applicable.\0"
> +			VALUE "OriginalFilename", "hysecurity.dll\0"
> +			VALUE "ProductName", "Apache Harmony\0"
> +			VALUE "ProductVersion", "0.1\0"
> +		END
> +	END
> +	BLOCK "VarFileInfo"
> +	BEGIN
> +		VALUE "Translation", 0x0409, 1200
> +	END
> +END
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/makefile
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/makefile?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/makefile (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/makefile Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,43 @@
> +# Copyright 2006 The Apache Software Foundation or its licensors, as applicable
> +# 
> +# Licensed under the Apache License, Version 2.0 (the "License");
> +# you may not use this file except in compliance with the License.
> +# You may obtain a copy of the License at
> +# 
> +#     http://www.apache.org/licenses/LICENSE-2.0
> +# 
> +# Unless required by applicable law or agreed to in writing, software
> +# distributed under the License is distributed on an "AS IS" BASIS,
> +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> +# See the License for the specific language governing permissions and
> +# limitations under the License.
> +
> +#
> +# Makefile for module 'security'
> +#
> +
> +!include <$(HY_HDK)\build\make\defines.mak>
> +
> +LIBBASE=hysecurity
> +
> +DLLNAME=$(DLLPATH)$(LIBBASE).dll
> +LIBNAME=$(LIBPATH)$(LIBBASE).lib
> +
> +HYLDFLAGS = $(HYLDFLAGS) -def:$(LIBBASE).def
> +HYCFLAGS = $(HYCFLAGS) /I$(SHAREDSUB) /I$(SHARED)common /I..\zip \
> +	   /I$(SHARED)fdlibm
> +
> +BUILDFILES = security_copyright.obj getWindowsRandom.obj
> +
> +VIRTFILES = $(LIBBASE).res
> +
> +SYSLIBFILES = ws2_32.lib Iphlpapi.lib
> +
> +MDLLIBFILES = $(LIBPATH)hycommon.lib $(LIBPATH)hypool.lib
> +
> +DLLBASE=0x13900000
> +
> +COMMENT=/comment:"Security component native code. (c) Copyright 2006 The Apache Software Foundation or its licensors, as applicable."
> +
> +!include <$(HY_HDK)\build\make\rules.mak>
> +
>
> Added: incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/security_copyright.c
> URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/security_copyright.c?rev=425020&view=auto
> ==============================================================================
> --- incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/security_copyright.c (added)
> +++ incubator/harmony/enhanced/classlib/trunk/modules/security/src/main/native/security/windows/security_copyright.c Mon Jul 24 05:01:54 2006
> @@ -0,0 +1,19 @@
> +/* Copyright 2006 The Apache Software Foundation or its licensors, as applicable
> + * 
> + * Licensed under the Apache License, Version 2.0 (the "License");
> + * you may not use this file except in compliance with the License.
> + * You may obtain a copy of the License at
> + * 
> + *     http://www.apache.org/licenses/LICENSE-2.0
> + * 
> + * Unless required by applicable law or agreed to in writing, software
> + * distributed under the License is distributed on an "AS IS" BASIS,
> + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> + * See the License for the specific language governing permissions and
> + * limitations under the License.
> + */
> +
> +/* A copyright string included in each DLL and executable */
> +
> +const char hyCopyright[] =
> +  "(c) Copyright 2006 The Apache Software Foundation or its licensors, as applicable.";
>
>
>
>   

-- 
Oliver Deakin
IBM United Kingdom Limited


---------------------------------------------------------------------
Terms of use : http://incubator.apache.org/harmony/mailing.html
To unsubscribe, e-mail: harmony-dev-unsubscribe@incubator.apache.org
For additional commands, e-mail: harmony-dev-help@incubator.apache.org