刚刚加入Java中的安全性,并尝试使用数字签名。问题是我已经手动生成了我的RSA密钥,我想与他们签约。这甚至可能吗?
这是我写的代码,其中sk是服务器私钥,pk是公共服务器密钥,而模数是服务器模块
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值中生成私钥/公钥的方法,但没办法。
会提供任何帮助/考虑。
答案 0 :(得分:1)
虽然密钥太小而无法实际使用,但您仍可将其用于教育目的。请注意,密钥太小,甚至无法使用PKCS#1填充模式,只有" raw" RSA加密(即仅RSA的模幂运算部分)。
以下适用于Bouncy Castle提供商(其中密钥为64位密钥):
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, });