gpt4 book ai didi

Java:生成自定义私钥和公钥?

转载 作者:行者123 更新时间:2023-11-30 11:19:31 25 4
gpt4 key购买 nike

刚刚开始研究 Java 中的安全问题,并尝试使用数字签名。问题是我已经手动生成了我的 RSA key ,我想用它们签名。这可能吗?

这是我写的代码,其中 sk 是服务器私钥,pk 是公共(public)服务器 key ,modulus 是服务器模块

public static byte[] sign(byte[] message, BigInteger sk, BigInteger pk, BigInteger modulus) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException, NoSuchProviderException{   
//Initialize signature
Signature sig = Signature.getInstance("MD5WithRSA");

//Create public and private keys
KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
RSAPrivateKeySpec skey = new RSAPrivateKeySpec(modulus, sk);
RSAPrivateKey serverPrivateKey = (RSAPrivateKey)fact.generatePrivate(skey);
RSAPublicKeySpec pkey = new RSAPublicKeySpec(modulus, pk);
PublicKey serverPublicKey = fact.generatePublic(pkey);

//We assign the key
sig.initSign(serverPrivateKey);
sig.update(message);
byte[] signatureBytes = sig.sign();

return signatureBytes;
}

运行后出现如下错误:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: RSA keys must be at least 512 bits long

你们知道我该如何面对吗?我尝试了几种从我的 BigInteger 值生成私钥/公钥的方法,但没有办法。

希望得到任何帮助/考虑。

最佳答案

虽然 key 对于实际使用而言太小,但您仍然可以将其用于教育目的。请注意, key 非常小,您甚至不能使用 PKCS#1 填充模式,只能使用“原始”RSA 加密(即,只能使用 RSA 的模幂部分)。

以下对于 Bouncy CaSTLe 提供程序( key 是 64 位 key )非常有效:

final Provider bc = new BouncyCastleProvider();

// generating the key from modulus & private exponent
KeyFactory rsaFactory = KeyFactory.getInstance("RSA", bc);
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(key.getModulus(), key.getPrivateExponent());
RSAPrivateKey testKey = (RSAPrivateKey) rsaFactory.generatePrivate(spec);

// using it in a raw cipher
Cipher c= Cipher.getInstance("RSA/ECB/NoPadding", bc);
c.init(Cipher.DECRYPT_MODE, testKey);
c.doFinal(new byte[] {(byte) 0x7F, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, });

关于Java:生成自定义私钥和公钥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23193554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com