JavacardOS will not accept order any more, please contact our partner Feitian online Store:
https://ftsafe.en.alibaba.com/index.html
https://ftsafe.en.alibaba.com/index.html
Generate random number
Moderator: UNKNwYSHSA
Generate random number
Anybody in here? Can anybody tell me how to generate random number bounded between two number in Java Card?
- horse dream
- Posts: 76
- Joined: Thu May 21, 2015 11:48 pm
- Points :140
- Contact:
Re: Generate random number
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);
}
}
Who is online
Users browsing this forum: No registered users and 5 guests