Java Diffie-Hellman 密钥交换

2024-04-26

我正在尝试执行代码来执行 Diffie-Hellman 密钥交换。我从网上的一个示例中获取了代码(现在忘记在哪里了)。 我必须导入 bouncycastle.jar,我认为它在执行之前一直有效。

my code:

package testproject;

import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.KeyAgreement;
import javax.crypto.spec.DHParameterSpec;

public class KeyGen {

  private static BigInteger g512 = new BigInteger("1234567890", 16);
  //generates a random, non-negative integer for Base

  private static BigInteger p512 = new BigInteger("1234567890", 16);
  //generates a random, non-negative integer for Prime

  public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    DHParameterSpec dhParams = new DHParameterSpec(p512, g512);
    //Specify parameters to use for the algorithm
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH", "BC");
    //Define specific algorithm to use "diffie-hellman", with provider "bc"

    keyGen.initialize(dhParams, new SecureRandom());
    //initialize with parameters & secure random seed

    KeyAgreement aKeyAgree = KeyAgreement.getInstance("DH", "BC");
    //define algorithm for A's key agreement
    KeyPair aPair = keyGen.generateKeyPair();
    //generate keyPair for A

    KeyAgreement bKeyAgree = KeyAgreement.getInstance("DH", "BC");
    //define algorithm for B's key agreement
    KeyPair bPair = keyGen.generateKeyPair();
    //generate keyPair for B

    aKeyAgree.init(aPair.getPrivate());
    //initialize A's keyAgreement with A's private key
    bKeyAgree.init(bPair.getPrivate());
    //initialize B's keyAgreement with B's private key

    aKeyAgree.doPhase(bPair.getPublic(), true);
    //do last phase of A's keyAgreement with B's public key
    bKeyAgree.doPhase(aPair.getPublic(), true);
    //do last phase of B's keyAgreement with A's public key

    MessageDigest hash = MessageDigest.getInstance("SHA1", "BC");

    System.out.println(new String(hash.digest(aKeyAgree.generateSecret())));
    //generate secret key for A, hash it.
    System.out.println(new String(hash.digest(bKeyAgree.generateSecret())));
    //generate secret key for B, hash it.
  }
}

这是导致问题的行:

KeyPair aPair = keyGen.generateKeyPair();

我对错误是什么感到困惑,因为我发现它返回“未知来源”的每个方法。

任何对此的启发将不胜感激。

续(编辑):Java - Diffie-Hellman 加密 - 错误的输出 https://stackoverflow.com/questions/22492417/java-diffie-hellman-encryption-wrong-output


您已经首选 bouncycastle 版本。但出于学习目的,我实现了它的一个小 helloworld 版本。也许它对于那些只想在纯 Java 中使用 Diffie-Hellman 而无需依赖的人会有所帮助:

// 1. ------------------------------------------------------------------
// This is Alice and Bob
// Alice and Bob want to chat securely. But how?

final Person alice = new Person();
final Person bob   = new Person();

//    ?                                        ?
//
//    O                                        O
//   /|\                                      /|\
//   / \                                      / \
//
//  ALICE                                     BOB

// 2. ------------------------------------------------------------------
// Alice and Bob generate public and private keys.

alice.generateKeys();
bob.generateKeys();

//
//    O                                        O
//   /|\                                      /|\
//   / \                                      / \
//
//  ALICE                                     BOB
//  _ PUBLIC KEY                              _ PUBLIC KEY
//  _ PRIVATE KEY                             _ PRIVATE KEY

// 3. ------------------------------------------------------------------
// Alice and Bob exchange public keys with each other.

alice.receivePublicKeyFrom(bob);
bob.receivePublicKeyFrom(alice);

//
//    O                                        O
//   /|\                                      /|\
//   / \                                      / \
//
//  ALICE                                     BOB
//  + public key                              + public key
//  + private key                             + private key
//  _ PUBLIC KEY <------------------------->  _ PUBLIC KEY

// 4. ------------------------------------------------------------------
// Alice generates common secret key via using her private key and Bob's public key.
// Bob generates common secret key via using his private key and Alice's public key.
// Both secret keys are equal without TRANSFERRING. This is the magic of Diffie-Hellman algorithm.

alice.generateCommonSecretKey();
bob.generateCommonSecretKey();

//
//    O                                        O
//   /|\                                      /|\
//   / \                                      / \
//
//  ALICE                                     BOB
//  + public key                              + public key
//  + private key                             + private key
//  + public key                              + public key
//  _ SECRET KEY                              _ SECRET KEY

// 5. ------------------------------------------------------------------
// Alice encrypts message using the secret key and sends to Bob

alice.encryptAndSendMessage("Bob! Guess Who I am.", bob);

//
//    O                                        O
//   /|\ []-------------------------------->  /|\
//   / \                                      / \
//
//  ALICE                                     BOB
//  + public key                              + public key
//  + private key                             + private key
//  + public key                              + public key
//  + secret key                              + secret key
//  + message                                 _ MESSAGE

// 6. ------------------------------------------------------------------
// Bob receives the important message and decrypts with secret key.

bob.whisperTheSecretMessage();

//
//    O                     (((   (((   (((   \O/   )))
//   /|\                                       |
//   / \                                      / \
//
//  ALICE                                     BOB
//  + public key                              + public key
//  + private key                             + private key
//  + public key                              + public key
//  + secret key                              + secret key
//  + message                                 + message

https://github.com/firatkucuk/diffie-hellman-helloworld https://github.com/firatkucuk/diffie-hellman-helloworld

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java Diffie-Hellman 密钥交换 的相关文章

随机推荐

  • 多个网站,单点登录设计[关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我有个问题 我最近一直在做一些工作的一个客户有一系列具有不同登录机制的网站 他正在寻求慢慢迁移到单点登录他的网站机制 全部写在asp net m
  • 使用 Nodejs 和 body-parser 发布表单数据

    我现在已经进行了几次不同的在线尝试 但我的帖子数据一直未定义 并且 console log JSON stringify req body 也没有返回任何内容 所以我在某个地方出错了 HTML
  • SSE、内在函数和对齐

    我使用大量 SSE 编译器内在函数编写了一个 3D 矢量类 一切都工作正常 直到我开始使用 new 来实例化具有 3D 向量作为成员的类 我在发布模式下经历了奇怪的崩溃 但在调试模式下却没有 反之亦然 因此 我阅读了一些文章 并认为我需要将
  • 使用 pip 安装 pycrypto 失败

    我在尝试下载某个包时遇到了问题 C Python27 Scripts gt pip install pycrypto Collecting pycrypto Using cached https files pythonhosted org
  • gcc 中“-l”选项的放置

    我在放置时遇到一些问题 l使用时的选项gcc 这是一个用于重现问题的精简版本 t c include
  • 从数字字符串生成行

    我有一个 Oracle 18c 表 其中包含如下字符串 select 0 5 0 10 10 11 18 30 0 33 54 50 10 33 54 60 10 43 54 as multipart lines There are mor
  • 在 WPF 绑定中使用“真实”CultureInfo.CurrentCulture,而不是 IetfLanguageTag 中的 CultureInfo

    就我而言 我有一个 TextBlock 绑定到 DateTime 类型的属性 我希望它按照用户的区域设置显示
  • Maven:我应该保留还是删除声明的依赖项,这些依赖项也是传递依赖项?

    您认为删除 Maven pom 中可以找到的所有传递依赖项是一个好习惯吗 Example 我的项目依赖于A和B B 也是 A 的传递依赖 我应该将 B 保留在我的 pom 中还是将其删除 哪个最好 拥有所有已知的 jar 甚至是传递性的 j
  • Spark:将 bytearray 转换为 bigint

    尝试使用 pyspark 和 Spark sql 将 kafka 键 二进制 字节数组 转换为 long bigint 会导致数据类型不匹配 无法将二进制转换为 bigint 环境详情 Python 3 6 8 Anaconda custo
  • 如何使用 Objective-C 使文件在 Finder 中不可见

    如果可能的话 我需要使用 Objective C 或使用 C 调用将文件隐藏在查找器中以及聚光灯下 Thanks 您可以使用 chflags path to file UF HIDDEN 隐藏任何文件 See 手动更改标志 2 https
  • 实体框架无法使用复合键更新表中的数据 (Oracle)

    我们有一个具有三列复合键的 Oracle 表 这些列通过实体框架数据模型正确映射到 C 对象中 当我们从数据库中查询记录然后更新非键列时 我们总是收到一条错误消息 指出我们正在尝试更新主键 测试摘录如下 var connection new
  • 始终“具有离线访问权限”|谷歌 OAuth 2

    我正在尝试使用 Google OAuth2 api 获取用户的个人资料 用户身份验证后 在同意页面上 总是要求我 具有离线访问权限 浏览器中的 URL 如下所示 https accounts google com o oauth2 auth
  • Ember Data 未找到模型,但它显然存在

    我和其他许多人一样将我的 ember 应用程序升级到了最新版本 但升级后 我的应用程序仍然无法工作 我已经简化了很多 这归结为我的路线 我的路线是这样的 按照过渡指南中的建议 App BoxesRoute Ember Route exten
  • c++ pthread - 如何使地图访问线程安全?

    我有一个映射作为成员变量和多个访问该映射的线程 读写访问 现在我必须确保只有一个线程可以访问该地图 但我该如何点呢 最好的解决方案是什么 Boost 包含一些用于共享访问的很好的锁实现 看看文档 http www boost org doc
  • Google Play 游戏服务 - 未显示解锁成就弹出窗口

    当我解锁成就时 成就已解锁 弹出窗口不会弹出 但成就已解锁 正如我在成就列表中看到的那样 我已经尝试过了this https stackoverflow com a 26474719 2543285解决方案 但它不起作用 我在 MainAc
  • 将 JSON 数据从 php 传递到 html-data 属性,然后传递到 Javascript

    我正在创建一个插件 用户可以在其中添加自定义设置data HTML 中的属性 设置采用 JSON 格式 我在 Javascript 中使用这些设置 它有preview base and paths特性 preview and base有字符
  • Zurb Foundation:如何在调整大小到较小的屏幕时使按钮变小?

    在 Zurb Foundation 4 中 是否有一种方法可以在浏览器尺寸调整得较小或在较小的屏幕上时自动切换到较小的按钮样式 例如 当屏幕是标准桌面屏幕时 请执行以下操作 a href class primary button Butto
  • 计算具有特定子集大小的集合分区

    给定一组n元素 我需要找到该集合的所有分区k大小几乎相等的子集 例如 对于一个包含 7 个元素和 3 个子集的集合 我只需要其中有两个子集 每个子集包含 2 个元素 和一个子集包含 3 个元素的分区 我不想要一个包含 1 2 和 4 个元素
  • Visual Studio Javascript 断点未命中,为什么?

    可以为 javascript 代码块设置断点 如下图所示 我们如何使用它们 VS总是忽略 如果调试时将 Internet Explorer 设置为浏览器 理论上 Visual Studio 能够在客户端脚本设置的断点处停止 要使用该功能 您
  • Java Diffie-Hellman 密钥交换

    我正在尝试执行代码来执行 Diffie Hellman 密钥交换 我从网上的一个示例中获取了代码 现在忘记在哪里了 我必须导入 bouncycastle jar 我认为它在执行之前一直有效 my code package testproje