【问题标题】:Java: Generate a custom Private and Public key?Java:生成自定义私钥和公钥?
【发布时间】:2014-04-21 08:16:23
【问题描述】:

刚刚涉足 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 值生成私钥/公钥的方法,但没有办法。

希望有任何帮助/考虑。

【问题讨论】:

  • 根据该链接,keysize = 模数大小。我检查了该值及其 8 字节长。不应该这样吗?
  • 您正在使用 128 的密钥集进行初始化,而 RSA 预计至少为 512。
  • 如果模数确实是 8 字节,那么它太小而无法保证安全 - 分解一个 8 字节(64 位)的数字可以在

标签: java security cryptography key rsa


【解决方案1】:

虽然密钥对于实际使用来说太小了,但您仍然可以将其用于教育目的。请注意,密钥非常小,您甚至无法使用 PKCS#1 填充模式,只能使用“原始”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, });

【讨论】: