用Java创建RSA密钥

时间:2014-08-14 21:41:00

标签: java rsa

对于Java来说,我是业余爱好者。我需要使用java程序来制作RSA公钥。我有一个想要密钥的perosn给我的脚本,它看起来像这样:

import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class CustomRSAKeyPairGenerator{

 public void generate() {
    try {
        KeyPairGenerator objlRSAKeyPairGen =
        KeyPairGenerator.getInstance("RSA");
        objlRSAKeyPairGen.initialize(2048);
        KeyPair objlRSAKeyPair = objlRSAKeyPairGen.generateKeyPair();
        RSAPublicKey objlPublicKey = (RSAPublicKey) objlRSAKeyPair.getPublic();
        RSAPrivateKey objlPrivateKey = (RSAPrivateKey) objlRSAKeyPair.getPrivate();
        StringBuffer strblPublicKey = new StringBuffer();
        strblPublicKey.append(objlPublicKey.getModulus().toString(16).toUpperCase());
        strblPublicKey.append('~');
        strblPublicKey.append(objlPublicKey.getPublicExponent().toString(16).toUpperCase()
    ); 

    System.out.println(strblPublicKey.toString());
    StringBuffer strblPrivateKey = new StringBuffer();
    strblPrivateKey.append(objlPrivateKey.getModulus().toString(16).toUpperCase());
    strblPrivateKey.append('~');
    strblPrivateKey.append(objlPrivateKey.getPrivateExponent().toString(16).toUpperCase());

    System.out.println(strblPrivateKey.toString()); 

    }catch (NoSuchAlgorithmException noSuchAlgrtm){
        System.out.println(noSuchAlgrtm.getMessage());
    }catch (NoSuchProviderException noSuchProvdr) { 
        System.out.println((noSuchProvdr.getMessage());
    }
 }
}

但是当我跑步时,我得到了:

CustomRSAKeyPairGenerator.java:51:')'预期             的System.out.println((noSuchProvdr.getMessage());                                                           ^ 1错误

我不明白这里的问题。我对java很熟悉,接下来该怎么办?这只是一个错字吗?

2 个答案:

答案 0 :(得分:1)

问题出在代码底线的第4位:

System.out.println((noSuchProvdr.getMessage());
                   ^

从那里删除额外的括号以使其成为

System.out.println(noSuchProvdr.getMessage());

修改:如果编译器告诉您java.security.NoSuchProviderException is never thrown in body of corresponding try statement,请删除最后catch

catch (NoSuchProviderException noSuchProvdr) { 
    System.out.println((noSuchProvdr.getMessage());
}

答案 1 :(得分:0)

计算那条线上的parens。