1 19 21 package org.jahia.utils.keygenerator; 22 23 import java.security.MessageDigest ; 24 import java.security.NoSuchAlgorithmException ; 25 import java.util.Random ; 26 27 import org.jahia.utils.Base64; 28 import org.jahia.utils.JahiaTools; 29 30 31 36 37 38 public class JahiaKeyGen 39 { 40 41 42 46 54 55 static String mLastKey = ""; 56 57 58 65 public static synchronized String getKey(){ 66 67 MersenneTwisterFast mtfRandom = new MersenneTwisterFast(); 68 Random rd = new Random (); 69 mtfRandom.setSeed(rd.nextLong()); 70 String k = Long.toString(mtfRandom.nextLong()); 71 while ( k.equals(mLastKey) || k.startsWith("-") ){ 72 mtfRandom.setSeed(rd.nextLong()); 73 k = Long.toString(mtfRandom.nextLong()); 74 } 75 mLastKey = k; 76 return k; 77 } 78 79 80 89 public static synchronized String getKey(long seed){ 90 91 MersenneTwisterFast mtfRandom = new MersenneTwisterFast(); 92 mtfRandom.setSeed(seed); 93 String k = Long.toString(mtfRandom.nextLong()); 94 while ( k.equals(mLastKey) || k.startsWith("-") ){ 95 k = Long.toString(mtfRandom.nextLong()); 96 } 97 mLastKey = k; 98 return k; 99 } 100 101 102 110 public static synchronized String getKey(int n){ 111 112 MersenneTwisterFast mtfRandom = new MersenneTwisterFast(); 113 Random rd = new Random (); 114 mtfRandom.setSeed(rd.nextLong()); 115 String k = encrypt(Long.toString(mtfRandom.nextLong())); 116 while ( k.equals(mLastKey) || k.startsWith("-") || (k.length()<n) ){ 117 mtfRandom.setSeed(rd.nextLong()); 118 k = encrypt(Long.toString(mtfRandom.nextLong())); 119 } 120 121 String result = JahiaTools.replacePattern(k,"+","01"); 122 result = JahiaTools.replacePattern(result,"/","10"); 123 result = JahiaTools.replacePattern(result,"=","11"); 124 125 mLastKey = k; 126 return result.substring(0,n); 127 128 } 129 130 131 138 private static String encrypt (String data) { 139 140 if (data == null) { 141 return null; 142 } 143 144 if (data.length() == 0) { 145 return null; 146 } 147 148 String result = null; 149 150 try { 151 MessageDigest md = MessageDigest.getInstance ("SHA-1"); 152 if (md != null) 153 { 154 md.reset (); 155 md.update (data.getBytes()); 156 result = new String (Base64.encode (md.digest())); 157 } 158 md = null; 159 } 160 catch (NoSuchAlgorithmException ex) { 161 result = null; 162 } 163 164 return result; 165 } 166 167 168 169 } | Popular Tags |