简体   繁体   English

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

[英]Java: Generate a custom Private and Public key?

Just jumped into security stuff in Java and was trying to use a digital signature. 刚跳入Java的安全性知识,并试图使用数字签名。 The thing is that I already generated my RSA keys manually and I would like to sign with them. 事实是,我已经手动生成了RSA密钥,我想用它们签名。 Is that even possible? 那有可能吗?

This Is the code I wrote where sk is the servers privatekey, pk is the public server key and modulus is the servers module 这是我编写的代码,其中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;
}

After running it, I got the following error: 运行它后,出现以下错误:

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

Do you guys know how could I face this? 你们知道我怎么面对这个吗? I tried several ways of producing a Private / Public key out of my BigInteger values and there was no way. 我尝试了几种通过BigInteger值生成私钥/公钥的方法,但是没有办法。

Would apreciate any help/considerations. 会感激任何帮助/注意事项。

Although the key is too small for practical use, you may still use it for educational purposes. 尽管密钥太小而无法实际使用,但您仍可以将其用于教育目的。 Note that the key is so small that you cannot even use PKCS#1 padding modes, only "raw" RSA encryption (ie only the modular exponentiation part of RSA). 请注意,密钥是如此之小,以至于您甚至不能使用PKCS#1填充模式,只能使用“原始” RSA加密(即,仅使用RSA的模块化指数部分)。

The following works perfectly well for the Bouncy Castle provider (where the key is a 64 bit key): 对于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, });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM