Java:生成自定义私钥和公钥?
刚刚开始使用Java的安全技术,并试图使用数字签名。问题是我已经手动生成了我的RSA密钥,我想用它们签名。这可能吗 这是我写的代码,其中sk是服务器私钥,pk是公共服务器密钥,module是服务器模块Java:生成自定义私钥和公钥?,java,security,cryptography,key,rsa,Java,Security,Cryptography,Key,Rsa,刚刚开始使用Java的安全技术,并试图使用数字签名。问题是我已经手动生成了我的RSA密钥,我想用它们签名。这可能吗 这是我写的代码,其中sk是服务器私钥,pk是公共服务器密钥,module是服务器模块 public static byte[] sign(byte[] message, BigInteger sk, BigInteger pk, BigInteger modulus) throws NoSuchAlgorithmException, InvalidKeyException, Sig
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值生成私钥/公钥,但没有办法
非常感谢您的帮助/注意事项。尽管钥匙太小,无法实际使用,但您仍可以将其用于教育目的。请注意,密钥非常小,您甚至无法使用PKCS#1填充模式,只能使用“原始”RSA加密(即仅RSA的模幂部分) 以下内容适用于Bouncy Castle提供程序(其中密钥为64位密钥):
根据该链接查看,键大小=模数大小。我检查了该值及其8字节长。这不适合吗?请看,您正在使用128个密钥集初始化此密钥集,RSA要求至少512个。如果模数确实为8字节,则它太小而不安全-分解8字节(64位)数可以在<1秒内完成。
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, });