如何为事务实现OTP

时间:2018-04-10 17:03:58

标签: android sqlite one-time-password

我正在使用android studio和SQLite db。我想在我的应用程序中实现OTP。有发件人收件人用户。 接收方会生成otp并将其提供给发件人。然后发件人将使用此otp发送资金。

现在我能够使用随机数生成器生成otp,我想让这个otp在5分钟内有效,如果发件人进行交易,那么就可以了otp将失效,交易将失败。这该怎么做?是否可以使用SQLite db?我有交易表,其中 otp 作为其列之一。直到现在我只有以下代码来生成otp。有人帮我提供了更多代码。

otp在 MainActivity 接收器生成代码 -

public int generateOTP(int maxNumber,int minNumber){
  Random r=new Random();
  int randomNumber = r.nextInt((maxNumber-minNumber)+1)+minNumber;
  return randomNumber;
}

2 个答案:

答案 0 :(得分:0)

你可以添加一个额外的列,说 otpissued 用于存储交易时间和OTP,然后检查这是在时间范围内。

请求的发送者不会得到时间或提供它而不是当前时间,因此无法绕过检查(除非发送者可以使用数据库操纵设备上的时间)。 / p>

e.g。以下是交易表: -

enter image description here

使用: -

`INSERT INTO transactions VALUES(null,1234, julianday('now'));`
  • 注意 1234 用于演示目的,它将是生成的密码

会添加一行。

对于演示行,可以使用

显示
  • SELECT id, otp, otpissued, strftime('Addded on %Y-%m-%d at %H:%M:%S',otpissued) AS issued_date_time FROM transactions;
  • 这只会使交易的日期更具人性化。

所以交易表可以是: -

ADD IMAGE 1 HERE

  • 实际表格为:
  • enter image description here

可以使用以下方式检查交易: -

-- Check if the transaction is valid no row = timed out 1 row = valid
SELECT id,
        CASE WHEN julianday('now') >= otpissued 
            AND julianday('now') <= julianday(otpissued,'+5 minutes') 
        THEN 'VALID' 
        ELSE 'INVALID'
    END AS validation,
    -- Used for testing/demonstation
            otp,
            strftime('%Y-%m-%d %H:%M %S',julianday('now')) AS current_date_time, -- FOR TESTING/DEMO
            strftime('%Y-%m-%d %H:%M %S',otpissued) AS otp_date_time, -- FOR TESTING/DEMO
            strftime('%Y-%m-%d %H:%M %S',otpissued, '+5 minutes') AS otp_expiry , -- FOR TESTING/DEMO
            julianday(otpissued) AS issued_jd, -- FOR TESTING/DEMO
            julianday(otpissued,'+5 minutes') as expiry_jd -- FOR TESTING/DEMO
    -- End of additional columns for testing/demonstration
    FROM transactions
    WHERE otp = 1234 
    --Alternative will output no rows if invalid (outside time-frame) 1 or more rows if valid (within time-frame)
    --WHERE otp = 1234 AND (julianday('now') >= otpissued AND julianday('now') <= julianday(otpissued,'+5 minutes'));

可能导致(超过5分钟过期): -

enter image description here

当然上面的检查将是: -

SELECT id,
        CASE WHEN otp = 1234 
            AND julianday('now') >= otpissued 
            AND julianday('now') <= julianday(otpissued,'+5 minutes') 
        THEN 'VALID' 
        ELSE 'INVALID'
    END AS validation
    FROM transactions
    WHERE otp = 1234;

在这种情况下,结果将是(如果没有交易满足WHERE标准,即具有正确的otp,则为空): -

如果添加了新行: - enter image description here

测试有效

请注意,您可能没有相同的 OTP ,也可能更具选择性,例如使用事务ID,因此您只需要检查1行,但这是演示

enter image description here

然后长卷的检查会导致: -

enter image description here

紧凑检查将是: -

enter image description here

答案 1 :(得分:0)

我认为最好实现RFC6238也称为基于时间的一次性密码,以便获得正确的OTP实施。

此外,Random不是在安全性方面接收一次性密码的最佳方式。