Our Online Store have the new products: RFID antenna board. Currently it can work with JC10M24R and JCOP4 card chips.
Compared with normal cards, the antenna board module has a smaller size and fixed holes, which is easy to integrate in the IOT(Internet Of Things) project.

Generate random number

Algorithm School

Moderator: UNKNwYSHSA

User avatar
vermont
Posts: 13
Joined: Tue May 26, 2015 10:18 pm
Points :6
Contact:

Generate random number

Post by vermont » Fri Jun 05, 2015 3:08 am

Anybody in here? Can anybody tell me how to generate random number bounded between two number in Java Card?

User avatar
horse dream
Posts: 76
Joined: Thu May 21, 2015 11:48 pm
Points :138
Contact:

Re: Generate random number

Post by horse dream » Fri Jun 05, 2015 3:33 am

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);
    }
}

Post Reply Previous topicNext topic

Who is online

Users browsing this forum: No registered users and 37 guests

JavaCard OS : Disclaimer