2013-10-23 2 views
0

다음 코드를 사용하여 키를 만들었지 만 KeyGeneration.getPublicKey()을 사용하려고하면 null을 반환합니다. 아래공용 및 개인 키 만들기

public KeyGeneration() throws Exception,(more but cleared to make easier to read) 
{ 
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); 
    kpg.initialize(1024); 
    KeyPair kp = kpg.genKeyPair(); 
    PublicKey publicKey = kp.getPublic(); 
    PrivateKey privateKey = kp.getPrivate(); 

} 

public static PublicKey getPublicKey() { return publicKey; } 

오류 메시지 : 당신이 전체 코드를보고 싶은 경우

java.security.InvalidKeyException: No installed provider supports this key: (null) 
    at javax.crypto.Cipher.chooseProvider(Cipher.java:878) 
    at javax.crypto.Cipher.init(Cipher.java:1213) 
    at javax.crypto.Cipher.init(Cipher.java:1153) 
    at RSAHashEncryption.RSAHashCipher(RSAHashEncryption.java:41) 
    at RSAHashEncryption.exportEHash(RSAHashEncryption.java:21) 
    at Main.main(Main.java:28) 

, 내가 여기에 게시 할 수 있습니다.

PublicKey publicKey = kp.getPublic(); 

지역 변수에 기록하지만,이된다 :

public static PublicKey getPublicKey() { return publicKey; } 
+0

사용중인 자바 버전은 무엇입니까? –

+0

전체 코드가 필요하지 않습니다. [SSCCE] (http://www.sscce.org) =) –

답변

1

사용자가 제공 한 코드가 실제 클래스의 진정한 반사 경우

는 다음 문제는이 때문이다

값이 다른 변수를 반환합니다. 사실 그것은 둘러싸는 클래스의 정적 필드 여야합니다 ... 초기화하지 않았기 때문에 그것이 null이라고 기대합니다!

여기 실제 문제는 자바 인스턴스 변수, 정적 변수 및 로컬 변수의 차이를 실제로 이해하지 못한다는 것입니다. 조각을 합치면 코드가 실제로 다음과 같아야합니다.

public class KeyGeneration { 

    private PublicKey publicKey; 
    private PrivateKey privateKey; 

    public KeyGeneration() throws Exception /* replace with the actual list ... */ { 
     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); 
     kpg.initialize(1024); 
     KeyPair kp = kpg.genKeyPair(); 
     publicKey = kp.getPublic(); 
     privateKey = kp.getPrivate(); 
    } 

    public PublicKey getPublicKey() { return publicKey; } 

    public PrivateKey getPrivateKey() { return privateKey; } 

}