2013-10-27 2 views
4

Java에서 RSA 알고리즘을 사용하여 암호화/해독하는 간단한 프로그램을 작성하고 있습니다.Java를 사용한 RSA 암호화/암호 해독

//Create a Cipher object 
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding"); 

I 암호화를 수행하여 암호화 함수 호출 : 같이

String cipher=encrypt(textByte, pair, rsaCipher); 
System.out.println("The Encryption using RSA Algorithm : "+cipher); 

복호를 : I 출력을 표시 할 때

//Decryption 
String plain=decrypt(Base64.decodeBase64(cipher),pair, rsaCipher); 
System.out.println("The Decryption using RSA Algorithm : "+plain); 

, 다음 I는 암호 객체를 만들 복호화 출력은 원본 텍스트보다 긴 공간을 반환합니다. enter image description here

그러나 Cipher 객체를 생성하기위한 코드를 다음과 같이 편집합니다. // 암호 객체 만들기 암호 rsaCipher = Cipher.getInstance ("RSA");

즉은, 동작 모드 및 패딩 인수를 제거하여 문제가 해결 얻을 출력이된다 : enter image description here

가 어디에 문제입니다. 첫 번째 경우 (공백이 나타날 때), NoPadding을 지정 했습니까? 해독 된 메시지에 공백이 나타나는 이유는 무엇입니까? 패딩을 사용해도 이런 일이 일어나지 않아야합니다.

편집 : 이것은 암호화이고 암호 해독 방법 :

public static String encrypt(byte[] textBytes, KeyPair pair, Cipher rsaCipher) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException 
{ 
    //get the public key 
    PublicKey pk=pair.getPublic(); 


    //Initialize the cipher for encryption. Use the public key. 
    rsaCipher.init(Cipher.ENCRYPT_MODE, pk); 

    //Perform the encryption using doFinal 
    byte[] encByte = rsaCipher.doFinal(textBytes); 

    // converts to base64 for easier display. 
    byte[] base64Cipher = Base64.encodeBase64(encByte); 

    return new String(base64Cipher); 
}//end encrypt 

public static String decrypt(byte[] cipherBytes, KeyPair pair, Cipher rsaCipher) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException 
{ 
    //get the public key 
    PrivateKey pvk=pair.getPrivate(); 

    //Create a Cipher object 
    //Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding"); 

    //Initialize the cipher for encryption. Use the public key. 
    rsaCipher.init(Cipher.DECRYPT_MODE, pvk); 

    //Perform the encryption using doFinal 
    byte[] decByte = rsaCipher.doFinal(cipherBytes); 

    return new String(decByte); 

}//end decrypt 
+0

'encrypt' 및'decrypt' 메소드를 보여줄 수 있습니까? – Craigy

답변

5

귀하의 문제는 패딩 참이다. 실제로 PKCS # 1 1.5 또는 OAEP 패딩 중 일부 패딩이 보안 RSA 기능에 필요합니다. 또한 암호화 된 일반 텍스트의 시작과 끝을 찾아야합니다.

RSA의 모듈러 지수는 큰 정수를 사용하여 수행됩니다. 이 연산의 결과는 옥텟 문자열로 표현됩니다. 이러한 옥텟 문자열은 기본적으로 큰 엔디안, 부호없는 고정 길이의 정수 표현입니다. 이 정수는 00 바이트 (이것은 RSA 표준에서 I2OS 프리미티브라고 함)로 채워져 있습니다. 그래서 여러분이보고있는 것은 모듈화 된 지수의 결과입니다. 00 패딩이 여전히 존재합니다.

짧은 이야기이므로 항상 패딩 방식을 사용하십시오. 요즘에는 OAEP가 바람직 할 것입니다. 하이브리드 암호화 체계와 함께 사용하거나 CMS 또는 PGP와 같은 상위 컨테이너 형식을 사용하십시오.

0

RSA의 모듈러 지수는 큰 정수를 사용하여 수행됩니다. 이 연산의 결과는 옥텟 문자열로 표현됩니다. 이러한 옥텟 문자열은 기본적으로 큰 엔디안, 부호없는 고정 길이의 정수 표현입니다. 이 정수는 00 바이트로 채워져 있습니다 (RSA 표준에서 I2OS 프리미티브라고 함). 그래서 당신이보고있는 것은 모듈화 된 지수의 결과입니다. 00은 여전히 ​​채워져 있습니다.

-2

희망이 도움이됩니다. :)

import java.util.*; 
import java.math.*; 
class RSA 
{ 
public static void main(String args[]) 
{ 
BigInteger one, p, q, E, D, n,P,Q; 
Scanner s = new Scanner(System.in); 
Scanner t = new Scanner(System.in); 
System.out.println("Enter A's prime number!"); 
p = s.nextBigInteger(); 
System.out.println("Enter B's prime number!"); 
q = s.nextBigInteger(); 
n = p.multiply(q); 
P = p.subtract(BigInteger.ONE); 
Q = q.subtract(BigInteger.ONE); 
int x = 0; 
do 
{ 
System.out.println("Enter Public key "); 
E =s.nextBigInteger(); 
if(((P.gcd(E)).equals(BigInteger.ONE))&&((Q.gcd(E)).equals(BigInteger.ONE))) 
{x++;} 
}while(x==0); 
for(int i = 1;;i++) 
{ 
D=new BigInteger(String.valueOf(i)); 
if(((D.multiply(E)).mod(P.multiply(Q))).equals(BigInteger.ONE)) 
break; 
} 
System.out.println("Enter Plain text!"); 
String in = "", out ="", text = t.nextLine(); 
for(int i = 0;i < text.length();i++){ 
BigInteger T = new BigInteger(String.valueOf((int)(text.charAt(i)))), O, TF; 
O = T.modPow(E,n); 
out += (char)O.intValue(); 
TF = O.modPow(D,n); 
in += (char)TF.intValue(); 
} 
System.out.println("Encrypted text : " + out); 
System.out.println("Decrypted text : "+ in); 
} 
} 
+1

OP 작성을 위해 필요한 변경 사항에 대해 설명해 주시겠습니까? –