获取指定长度的随机字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取指定长度的随机字符串相关的知识,希望对你有一定的参考价值。

  1 package unit;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.BufferedWriter;
  5 import java.io.ByteArrayInputStream;
  6 import java.io.File;
  7 import java.io.FileInputStream;
  8 import java.io.FileNotFoundException;
  9 import java.io.FileOutputStream;
 10 import java.io.FileWriter;
 11 import java.io.IOException;
 12 import java.io.InputStream;
 13 import java.io.InputStreamReader;
 14 import java.io.OutputStreamWriter;
 15 import java.security.MessageDigest;
 16 import java.security.NoSuchAlgorithmException;
 17 import java.security.PublicKey;
 18 import java.security.cert.Certificate;
 19 import java.security.cert.CertificateException;
 20 import java.security.cert.CertificateFactory;
 21 import java.security.cert.X509Certificate;
 22 import java.text.SimpleDateFormat;
 23 import java.util.Date;
 24 import java.util.Random;
 25 
 26 import javax.crypto.Mac;
 27 import javax.crypto.spec.SecretKeySpec;
 28 
 29 import org.apache.commons.codec.binary.Base64;
 30 
 31 /**
 32  * 加密工具类
 33  * @author jia
 34  */
 35 public class EncryUtil {
 36     /**
 37      * 获取指定长度的随机字符串
 38      * @param pwd_len 指定长度
 39      * @return
 40      */
 41     public static String genRandomNum(int pwd_len) {
 42         // 35是因为数组是从0开始的,26个字母+10个数字
 43         final int maxNum = 36;
 44         int i; // 生成的随机数
 45         int count = 0; // 生成的密码的长度
 46 
 47         char[] str = { ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘, ‘i‘, ‘j‘, ‘k‘, ‘l‘, ‘m‘, ‘n‘, ‘o‘, ‘p‘, ‘q‘, ‘r‘, ‘s‘,
 48                 ‘t‘, ‘u‘, ‘v‘, ‘w‘, ‘x‘, ‘y‘, ‘z‘, ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘ };
 49         StringBuffer pwd = new StringBuffer("");
 50         Random r = new Random();
 51         while (count < pwd_len) {
 52             // 生成随机数,取绝对值,防止生成负数,
 53             i = Math.abs(r.nextInt(maxNum)); // 生成的数最大为36-1
 54             if (i >= 0 && i < str.length) {
 55                 pwd.append(str[i]);
 56                 count++;
 57             }
 58         }
 59 
 60         return pwd.toString();
 61     }
 62 
 63     /**
 64      * 获取服务器时间与客户端时间戳 offSet
 65      * @param serverDateLong 服务器时间戳
 66      * @param serverDateLong 客户端时间戳
 67      * @return
 68      */
 69     public static Long getOffSet(String serverDateLong, String clientDateLong) {
 70         long serverLong = Long.parseLong(serverDateLong);
 71         long clientLong = Long.parseLong(clientDateLong);
 72         long offSet = serverLong - clientLong ;
 73         return offSet;
 74     }
 75 
 76     /**
 77      * 获取时间戳分散参数
 78      * @param timeStamp 待计算时间戳 
 79      * @return
 80      */
 81     public static byte[] getStr2Bcd(Long timeStamp) {
 82         Date date = new Date(timeStamp);
 83         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
 84         String serverDateStr = simpleDateFormat.format(date);
 85         byte[] dispersionParameter = BcdUtil.getDispersionParameter(serverDateStr);
 86         return dispersionParameter;
 87     }
 88 
 89     
 90 
 91     /**
 92      * SHA_1计算消息摘要
 93      * @param bytes 待计算数据
 94      * @return
 95      */
 96     public static String SHA_1(byte[] bytes) {
 97         String encodeBase64String = null;
 98         try {
 99             MessageDigest md = MessageDigest.getInstance("SHA1");
100             md.update(bytes);
101             byte[] _bytes = md.digest();
102             encodeBase64String = Base64.encodeBase64String(_bytes);
103         } catch (NoSuchAlgorithmException ex) {
104             ex.printStackTrace();
105         }
106         return encodeBase64String;
107     }
108 
109     /**
110      * HMAC算法加密
111      * @param message 待加密信息
112      * @param key 密钥
113      * @return 
114      */
115     public static String HmacSHA256(byte[] message, byte[] key){
116         long begin = System.currentTimeMillis();
117         try {
118             Mac hmacSha256Mac = Mac.getInstance("HMACSha256");
119             SecretKeySpec secretKey = new SecretKeySpec(key, "HMACSha256");
120             hmacSha256Mac.init(secretKey);
121             byte[] result = hmacSha256Mac.doFinal(message);
122             long end = System.currentTimeMillis();
123             return Base64.encodeBase64String(result);
124         } catch (Exception e) {
125             e.printStackTrace();
126             return "";
127         }
128 
129     }
130 
131     /**
132      * 将String型证书写入文件中
133      * @param serverCertificate 证书字符串
134      * @param path  写入路径
135      */
136     public static void writePem(String serverCertificate, String path) {
137         
138         File file = new File(path);
139         try {
140             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
141             bw.write(serverCertificate);
142             bw.newLine();
143             bw.flush();
144             bw.close();
145         } catch (FileNotFoundException e1) {
146             e1.printStackTrace();
147         } catch (IOException e) {
148             e.printStackTrace();
149         }
150     }
151 
152     /**
153      * 读取文件信息
154      * @param src  文件路径
155      * @return String
156      */
157     public static String readCacert(String src) {
158         StringBuilder sb = new StringBuilder();
159         try {
160             BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(src))));
161             String CacertStr = null;
162             while (null != (CacertStr = br.readLine())) {
163                 sb.append(CacertStr);
164             }
165             br.close();
166         } catch (Exception e) {
167             e.printStackTrace();
168         }
169         return sb.toString();
170     }
171 
172     /**
173      * 获取文件中证书公钥
174      * @param path   文件路径
175      * @return PublicKey 证书公钥
176      */
177     public static PublicKey getServerPublicKey(String path) {
178         X509Certificate certificate = getCertificateFromFile(path);
179         PublicKey publicKey = certificate.getPublicKey();
180         return publicKey;
181     }
182 
183     /**
184      * 文件中获取证书
185      * @param path    文件路径
186      * @return X509Certificate 证书
187      */
188     public static X509Certificate getCertificateFromFile(String path) {
189         File file = null;
190         InputStream inStream;
191         try {
192             file = new File(path);
193             inStream = new FileInputStream(file);
194             CertificateFactory cf = CertificateFactory.getInstance("X.509");
195             X509Certificate oCert = (X509Certificate) cf.generateCertificate(inStream);
196             return oCert;
197         } catch (FileNotFoundException e) {
198             e.printStackTrace();
199         } catch (CertificateException e) {
200             e.printStackTrace();
201         }
202         return null;
203     }
204 
205     /**
206      * 字符串转化为X509Certificate
207      * @param scert 字符串X509Certificate
208      * @return X509Certificate
209      */
210     public static X509Certificate getStringToCA(String scert) {
211         X509Certificate oCert = null;
212         try {
213 //            byte[] byteCert = Base64.decodeBase64(scert);
214             byte[] byteCert = scert.getBytes();
215             ByteArrayInputStream bain = new ByteArrayInputStream(byteCert);
216             CertificateFactory cf = CertificateFactory.getInstance("X.509");
217             oCert = (X509Certificate) cf.generateCertificate(bain);
218         } catch (CertificateException e) {
219             e.printStackTrace();
220         }
221         return oCert;
222     }
223 
224     /**
225      * 使用ca根证书验证服务器证书是否合法
226      * @param publicKey    CA根证书证书公钥 
227      * @param certificate 待校验证书
228      */
229     public static boolean checkCer(PublicKey publicKey, Certificate certificate) {
230         boolean result = false;
231         try {
232             // 校验证书
233             certificate.verify(publicKey);
234             result = true;
235         } catch (Exception e) {
236             result = false;
237             System.out.println(e);
238         }
239         return result;
240     }
241     
242     /**
243      * MD5加密
244      * @param strObj 待加密数据
245      * @return
246      */
247     public static byte[] MD5(String strObj) {
248         byte[] resultString = null;
249         try {
250             MessageDigest md = MessageDigest.getInstance("MD5");
251             resultString = md.digest(strObj.getBytes());
252         } catch (NoSuchAlgorithmException ex) {
253             ex.printStackTrace();
254         }
255         return resultString;
256     }
257     
258     /**
259      * 存储字符串到指定目录下的文件(追加存储)
260      * @param message
261      * @param fileName
262      */
263     public static void writeMessage(String message, String fileName) {
264         try {
265             File file = new File(fileName);
266             File file2 = new File(file.getParent());
267             if(file.length() > 2000000) {
268                 file.delete();
269             }
270             if (!file2.exists()) {
271                 file2.mkdirs();
272             }
273             if (!file.exists()) {
274                 file.createNewFile();
275             }
276             FileWriter fileWritter = new FileWriter(file, true);
277             BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
278             bufferWritter.write(message);
279             bufferWritter.newLine();
280             bufferWritter.close();
281         } catch (IOException e) {
282             e.printStackTrace();
283         }
284     }
285 }

 

以上是关于获取指定长度的随机字符串的主要内容,如果未能解决你的问题,请参考以下文章

获取指定长度的随机字符串

获取指定长度的随机字符串

java实现输出指定长度的随机字符(大小写字母和数字)遇到问题?

常用JS方法整理

Python随机生成指定长度字符串并保存到mysql中

生成仅包含指定字符的指定长度的随机字符串(在 Java 中)