2012-10-10 6 views
2

파일의 키를 사용하여 암호화하고 암호 해독하려고 할 때 몇 가지 문제가 있습니다.파일에서 공개 키 및 비공개 키 복구 (Android)

그것은 해독 나에게 오류를 제공
//**The main function:** 

File inputfile = new File(fileToEncrypt); // I receive fileToEncrypt for the function. 

try { 
    inputbytes = readFromFile(inputfile); 
} 

catch (IOException e) { 
    Toast.makeText(this, "ERROR READING", Toast.LENGTH_LONG).show(); 
} 

byte[] outputbytes = rsaEncrypt(inputbytes, raiz.getAbsolutePath()+"/PublicKeyFile.key"); 
byte[] inputbytes = rsaDecrypt(outputbytes, raiz.getAbsolutePath()+"/Privada.key"); 


    //**Used functions** 

    public byte[] rsaEncrypt(byte[] src, String direccion) { 
    try { 
     File archivo_llave_publica = new File(direccion); 
     byte[] bytes_llave = leer(archivo_llave_publica); 
     KeyFactory keyFactory = KeyFactory.getInstance("RSA");   
     EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bytes_llave); 
     PublicKey pubKey = keyFactory.generatePublic(publicKeySpec); 
     Cipher cipher = Cipher.getInstance("RSA"); 
     cipher.init(Cipher.ENCRYPT_MODE, pubKey); 
     byte[] cipherData = cipher.doFinal(src); 
     return cipherData; 
    } catch (Exception e) { 
     Toast.makeText(this, "Error encriptando!!", Toast.LENGTH_LONG).show(); 
    } 
    Toast.makeText(this, "ERROR ENCRYPT!", Toast.LENGTH_LONG).show(); 
    return null; 
} 

public byte[] rsaDecrypt(byte[] src, String direccion) { 
    try { 
     File archivo_llave_privada = new File(direccion); 
     byte[] bytes_llave = leer(archivo_llave_privada); 
     KeyFactory keyFactory = KeyFactory.getInstance("RSA");   
     EncodedKeySpec privateKeySpec = new X509EncodedKeySpec(bytes_llave); 
     PrivateKey priKey = keyFactory.generatePrivate(privateKeySpec); 
     Cipher cipher = Cipher.getInstance("RSA"); 
     cipher.init(Cipher.DECRYPT_MODE, priKey); 
     byte[] cipherData = cipher.doFinal(src); 
     return cipherData; 
    } catch (Exception e) { 
     Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); 
    } 
    return null; 
} 

public byte[] readFromFile(File archivo) throws IOException{   
    FileInputStream lector = new FileInputStream(archivo); 
    long length = archivo.length(); 
    byte[] input = new byte[(int) length]; 
    for (int i=0; i<(int)length; i++) 
    { 
     input[i]=(byte) lector.read(); 
    } 
    lector.close(); 
     return input; 
} 

... 당신은 내 실수를 발견하면 알려 주시기 바랍니다 :

문제와 내 코드의 일부이다. 감사!

+1

누군가가 도울 수 있도록 오류 메시지를 게시하십시오. –

+0

그리고 메시지 자체 만이 아니라 전체 스택 추적으로 만듭니다. – Fildor

+0

나는 이미 그것을 고쳤다 :) 문제는 encode 유형 해독이었다. X509 대신 PKCS8입니다. –

답변

0

문제는 인코딩 유형 해독입니다. X509 대신 PKCS8입니다.