Skip to content

Commit bd20467

Browse files
author
zhourenjian@gmail.com
committed
Generate key use Math.random correctly or precisely random
1 parent 24cd307 commit bd20467

File tree

2 files changed

+5
-6
lines changed

2 files changed

+5
-6
lines changed

sources/net.sf.j2s.ajax/ajaxpipe/net/sf/j2s/ajax/CompoundPipeRunnable.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,12 @@
33
public class CompoundPipeRunnable extends SimplePipeRunnable {
44

55
private static String nextSessionKey() {
6-
String hexStr = "0123456789abcdef";
7-
String key = "";
6+
StringBuffer keyBuffer = new StringBuffer(4);
87
for (int i = 0; i < 4; i++) {
9-
int hex = (int) Math.round(15 * Math.random());
10-
key += "" + hexStr.charAt(hex);
8+
int hex = (int) Math.floor(Math.random() * 16);
9+
keyBuffer.append((char) (hex < 10 ? ('0' + hex) : ('a' + hex - 10)));
1110
}
12-
return key;
11+
return keyBuffer.toString();
1312
}
1413

1514
CompoundPipeSession[] pipes;

sources/net.sf.j2s.ajax/ajaxpipe/net/sf/j2s/ajax/SimplePipeHelper.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ synchronized static String registerPipe(SimplePipeRunnable pipe) {
120120
static String nextPipeKey() {
121121
StringBuffer buf = new StringBuffer(SimplePipeRequest.PIPE_KEY_LENGTH);
122122
for (int i = 0; i < SimplePipeRequest.PIPE_KEY_LENGTH; i++) {
123-
int r = (int) Math.round((float) Math.random() * 61); // 0..61, total 62 numbers
123+
int r = (int) Math.floor(Math.random() * 62); // 0..61, total 62 numbers
124124
if (r < 10) {
125125
buf.append((char) (r + '0'));
126126
} else if (r < 10 + 26) {

0 commit comments

Comments
 (0)