一次性密码(OTP)C#到Java转换代码
发布时间:2020-12-15 08:35:03 所属栏目:百科 来源:网络整理
导读:去年我在C#中编写了一次性密码(OTP)生成器.现在我需要在 Java中使用OTP生成器,但是我找不到Java中的等效函数. 这是我去年写的代码:(我知道这个OTP的安全性很低,但我不需要防弹的代码) SHA1CryptoServiceProvider hash = new SHA1CryptoServiceProvider(); //
去年我在C#中编写了一次性密码(OTP)生成器.现在我需要在
Java中使用OTP生成器,但是我找不到Java中的等效函数.
这是我去年写的代码:(我知道这个OTP的安全性很低,但我不需要防弹的代码) SHA1CryptoServiceProvider hash = new SHA1CryptoServiceProvider(); //first hash with sha1 byte[] hashPass = hash.ComputeHash(Encoding.ASCII.GetBytes(pass)); //pass is entered by user HMACMD5 hma = new HMACMD5(hashPass); // use the hashed value as a key to hmac OTPass = hma.ComputeHash(Encoding.ASCII.GetBytes(email + Counter(email)));// generate OTPass,Counter(email) is the counter of the user taken from database increaseCounter(email); // updating the counter this.SetLog(this.GetLog() + Environment.NewLine + "OTPass Generated: " + BitConverter.ToString(OTPass)); // OTP 这是我试图将C#转换为的Java代码:(这只是SHA1部分,我找不到如何用Java编写HMAC-MD5) import java.io.*; import java.security.*; public class otp { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { System.out.println("Please enter your username:"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String username = br.readLine(); System.out.println("Please enter your password:"); String password = br.readLine(); try { MessageDigest md = MessageDigest.getInstance("SHA1"); String input = password; md.update(input.getBytes()); byte[] output = md.digest(); System.out.println(); System.out.println("SHA1(""+input+"") ="); System.out.println(" "+bytesToHex(output)); } catch (Exception e) { System.out.println("Exception: "+e); } } public static String bytesToHex(byte[] b) { char hexDigit[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; StringBuffer buf = new StringBuffer(); for (int j=0; j<b.length; j++) { buf.append(hexDigit[(b[j] >> 4) & 0x0f]); buf.append(hexDigit[b[j] & 0x0f]); } return buf.toString(); } } 感谢帮助 解决方法
我一直用
BouncyCastle
您可以查看以下几个页面: BouncyCastle HMac BouncyCastle Specs 或者坚持使用Java 6: Mac hmacMd5 = Mac.getInstance("HMACMD5"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容