2011-06-12 12 views
6

के जावा रूपांतरण के लिए वन-टाइम-पासवर्ड (ओटीपी) सी # पिछले वर्ष मैंने सी # में एक वन-टाइम-पासवर्ड (ओटीपी) जेनरेटर लिखा था। अब मुझे जावा में एक ओटीपी जनरेटर का उपयोग करने की आवश्यकता है लेकिन मुझे जावा में समकक्ष फ़ंक्शन नहीं मिल सका।कोड

यहाँ कोड मैं पिछले साल लिखा है: (मैं जानता हूँ कि इस 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 

यहाँ जावा कोड मैं सी # में परिवर्तित करने की कोशिश की है में:

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();   
} 
} 

मदद के लिए धन्यवाद

+3

जो लोग नहीं जानते के लिए, ओटीपी "एक बार पासवर्ड" के लिए एक संक्षिप्त शब्द है। (बस विकिपीडिया :-) के लिए बैंडविड्थ को बचाने की कोशिश कर रहा है।) –

उत्तर

8

मैं हमेशा इस्तेमाल किया है (यह सिर्फ SHA1 हिस्सा है, मैं जावा में HMAC-MD5 लिखने के लिए कैसे नहीं पा सके) BouncyCastle

आप इन पृष्ठों के कुछ पर एक नजर है कर सकते हैं:

BouncyCastle HMac

BouncyCastle Specs

या जावा 6 के साथ रहना:

Mac hmacMd5 = Mac.getInstance("HMACMD5"); 
+1

लिंक के लिए धन्यवाद। मैं उन्हें देख लूंगा। – Jail