Page 1 of 1

Generate random number

Posted: Fri Jun 05, 2015 3:08 am
by vermont
Anybody in here? Can anybody tell me how to generate random number bounded between two number in Java Card?

Re: Generate random number

Posted: Fri Jun 05, 2015 3:33 am
by horse dream
The following is a simple code that you can refer to. Hope to help you. BTW, if you have anyother questions ,feel free to post them here.

Code: Select all

package nl.owlstead.jcsecurerandom;

import javacard.framework.JCSystem;
import javacard.framework.Util;
import javacard.security.RandomData;

public final class JCSecureRandom {

    private static final short SHORT_SIZE_BYTES = 2;
    private static final short START = 0;

    private final RandomData rnd;
    private final byte[] buf;

    public JCSecureRandom(final RandomData rnd) {
        this.rnd = rnd;
        this.buf = JCSystem.makeTransientByteArray(SHORT_SIZE_BYTES,
                JCSystem.CLEAR_ON_DESELECT);
    }

    public short nextShort(final short n) {
        final short sn = (short) (n - 1);
        short bits, val;
        do {
            bits = next15();
            val = (short) (bits % n);
        } while ((short) (bits - val + sn) < 0);
        return val;
    }

    public byte nextByte(final byte n) {
        if ((n & -n) == n) {
            return (byte) ((n * next7()) >> 7);
        }

        final byte sn = (byte) (n - 1);
        byte bits, val;
        do {
            bits = next7();
            val = (byte) (bits % n);
        } while ((byte) (bits - val + sn) < 0);
        return val;
    }

    private short next15() {
        this.rnd.generateData(this.buf, START, SHORT_SIZE_BYTES);
        return (short) (Util.getShort(this.buf, START) & 0x7FFF);
    }

    private byte next7() {
        this.rnd.generateData(this.buf, START, SHORT_SIZE_BYTES);
        return (byte) (this.buf[START] & 0x7F);
    }
}