当前位置: 代码网 > it编程>编程语言>Java > Java实现OTP(动态口令)服务

Java实现OTP(动态口令)服务

2025年03月10日 Java 我要评论
什么是 otp?otp 的全称是 one-time password,中文常称为“一次性密码”或“动态口令”。它是一种动态生成的短时有效密码,用于身份验

什么是 otp?

otp 的全称是 one-time password,中文常称为“一次性密码”或“动态口令”。它是一种动态生成的短时有效密码,用于身份验证,通常在登录或执行敏感操作时提供额外的安全保障。otp 广泛应用于 google、微软、github 等主流平台,以增强用户账户的安全性。

otp 的特点包括:

  • 一次性使用:每个密码只能使用一次,无法重复。
  • 时效性:密码在短时间内有效,过期后无法使用。
  • 动态生成:密码基于时间或计数器动态生成。

otp 的生成原理

常见的 otp 实现标准有两种:

  • hotp(hmac-based one-time password):基于计数器的 otp。

  • totp(time-based one-time password):基于时间的 otp。

totp 是目前使用最广泛的标准。它以共享密钥(secret key)和当前时间为输入,结合 hmac-sha1 算法生成短数字密码。以下是 totp 的主要步骤:

  • 将当前时间戳除以时间步长(例如 30 秒)得到时间索引。

  • 使用 hmac 算法计算时间索引的哈希值。

  • 提取哈希值的动态偏移量,并生成一个 6 位或 8 位的数字密码。

用 java 实现 otp 服务

以下是一个基于 java 的 otp 服务实现,支持生成和验证 otp。

引入依赖

在项目的 pom.xml 文件中添加以下依赖:

<dependencies>
    <dependency>
        <groupid>commons-codec</groupid>
        <artifactid>commons-codec</artifactid>
        <version>1.15</version>
    </dependency>
</dependencies>

实现 otp 生成逻辑

以下代码实现了基于时间的 totp 生成和验证功能:

import java.nio.bytebuffer;
import java.time.instant;
import org.apache.commons.codec.binary.base32;
import java.util.concurrent.concurrenthashmap;
import java.util.concurrent.atomic.atomicinteger;

import javax.crypto.mac;
import javax.crypto.spec.secretkeyspec;

public class otpservice {

    private static final int time_step = 30; // 时间步长(秒)
    private static final int otp_length = 6; // otp 长度
    private static final int max_attempts = 5; // 最大尝试次数
    private static final long block_duration = 300_000; // 封锁时间(毫秒)

    private final concurrenthashmap<string, atomicinteger> attemptcounter = new concurrenthashmap<>();
    private final concurrenthashmap<string, long> blockedusers = new concurrenthashmap<>();

    // 生成 totp
    public string generatetotp(string secret) throws exception {
        long timeindex = instant.now().getepochsecond() / time_step;
        return generateotp(secret, timeindex);
    }

    // 验证 totp
    public boolean validatetotp(string secret, string otp, string userid) throws exception {
        if (isblocked(userid)) {
            system.out.println("user is temporarily blocked: " + userid);
            return false;
        }

        long timeindex = instant.now().getepochsecond() / time_step;

        // 在验证窗口内检查 otp
        for (int i = -1; i <= 1; i++) {
            string generatedotp = generateotp(secret, timeindex + i);
            if (generatedotp.equals(otp)) {
                resetattempts(userid);
                return true;
            }
        }

        recordfailedattempt(userid);
        return false;
    }

    private string generateotp(string secret, long timeindex) throws exception {
        // 解码 base32 密钥
        base32 base32 = new base32();
        byte[] keybytes = base32.decode(secret);

        // 转换时间索引为字节数组
        byte[] timebytes = bytebuffer.allocate(8).putlong(timeindex).array();

        // 使用 hmac-sha1 生成哈希
        mac mac = mac.getinstance("hmacsha1");
        secretkeyspec keyspec = new secretkeyspec(keybytes, "hmacsha1");
        mac.init(keyspec);
        byte[] hash = mac.dofinal(timebytes);

        // 提取动态偏移量
        int offset = hash[hash.length - 1] & 0x0f;
        int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16)
                | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff);

        // 生成 otp
        int otp = binary % (int) math.pow(10, otp_length);
        return string.format("%0" + otp_length + "d", otp);
    }

    private void recordfailedattempt(string userid) {
        attemptcounter.putifabsent(userid, new atomicinteger(0));
        int attempts = attemptcounter.get(userid).incrementandget();

        if (attempts >= max_attempts) {
            blockedusers.put(userid, system.currenttimemillis());
            system.out.println("user blocked due to multiple failed attempts: " + userid);
        }
    }

    private void resetattempts(string userid) {
        attemptcounter.remove(userid);
        blockedusers.remove(userid);
    }

    private boolean isblocked(string userid) {
        long blocktime = blockedusers.get(userid);
        if (blocktime == null) {
            return false;
        }

        if (system.currenttimemillis() - blocktime > block_duration) {
            blockedusers.remove(userid);
            return false;
        }
        return true;
    }
}

测试服务

以下是使用上述 otp 服务生成和验证 otp 的示例:

public class otpservicetest {
    public static void main(string[] args) throws exception {
        otpservice otpservice = new otpservice();

        // 使用 base32 编码密钥
        string secret = "jbswy3dpehpk3pxp";
        string userid = "user123";

        // 生成 otp
        string otp = otpservice.generatetotp(secret);
        system.out.println("generated otp: " + otp);

        // 尝试验证 otp
        for (int i = 0; i < 7; i++) {
            boolean isvalid = otpservice.validatetotp(secret, otp, userid);
            system.out.println("attempt " + (i + 1) + ": is otp valid: " + isvalid);
        }
    }
}

优化建议

安全性

  • 使用安全随机数生成器生成共享密钥。

  • 通过 https 传输数据,防止中间人攻击。

时间同步

  • 客户端和服务器之间的时间必须同步,否则 otp 验证可能失败。

防止 暴 力 破 解

  • 增加失败尝试次数限制和封锁机制。

生产环境

  • 在数据库中安全存储共享密钥,避免泄露。

  • 实现速率限制以防止暴 力 破 解攻击。

本文介绍了 otp 的基本原理,并通过 java 实现了一个简单的 otp 服务,能够兼容 google authenticator 和 microsoft authenticator 等主流应用。otp 技术通过动态密码的方式为用户提供了额外的身份验证安全保障,是目前最可靠的双因素认证技术之一。

到此这篇关于java实现otp(动态口令)服务的文章就介绍到这了,更多相关java otp动态口令内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com