2016-03-29 18 views
0

RSA 2048ビットキーを使用してテキストを暗号化するAndroidアプリがあります。RSA暗号化JavaでのAndroidと復号化:javax.crypto.BadPaddingException:復号化エラー

暗号化と復号化がアプリでうまく機能しています。

私の問題は、私はアプリケーションで暗号化しようとしているし、復号化のために外部Javaプログラムに暗号を送ることです。私は

javax.crypto.BadPaddingException: Decryption error 
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380) 
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291) 
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363) 
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389) 
    at javax.crypto.Cipher.doFinal(Cipher.java:2165) 
    at RSA.decrypt(RSA.java:94) 
    at RSA.main(RSA.java:116) 

何をしないのです:私はエラーを取得しています暗号を解読しようとしていたときに

public static PrivateKey getPrivateKey(String key) { 
    try { 
     /* Add PKCS#8 formatting */ 
     byte[] byteKey = Base64.getDecoder().decode(key.getBytes()); 
     ASN1EncodableVector v = new ASN1EncodableVector(); 
     v.add(new ASN1Integer(0)); 
     ASN1EncodableVector v2 = new ASN1EncodableVector(); 
     v2.add(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.rsaEncryption.getId())); 
     v2.add(DERNull.INSTANCE); 
     v.add(new DERSequence(v2)); 
     v.add(new DEROctetString(byteKey)); 
     ASN1Sequence seq = new DERSequence(v); 
     byte[] privKey = seq.getEncoded("DER"); 

     PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKey); 
     KeyFactory kf = KeyFactory.getInstance("RSA"); 
     return kf.generatePrivate(keySpec); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

public static String decrypt(String cipherString,PrivateKey privateKey){ 
    try{ 
     Cipher cipher = Cipher.getInstance("RSA"); 
     cipher.init(Cipher.DECRYPT_MODE, privateKey); 
     byte[] plainByte = cipher.doFinal(Base64.getDecoder().decode(cipherString)); 
     return Base64.getEncoder().encodeToString(plainByte); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

しかし:ここ

は、それがどのように行われるかですか?

UPDATE 私は、Java自体の中のキーの新しいペアを再生成し、一部を処分した:

/* Add PKCS#8 formatting */ 
byte[] byteKey = Base64.getDecoder().decode(key.getBytes()); 
ASN1EncodableVector v = new ASN1EncodableVector(); 
v.add(new ASN1Integer(0)); 
ASN1EncodableVector v2 = new ASN1EncodableVector(); 
v2.add(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.rsaEncryption.getId())); 
v2.add(DERNull.INSTANCE); 
v.add(new DERSequence(v2)); 
v.add(new DEROctetString(byteKey)); 
ASN1Sequence seq = new DERSequence(v); 
byte[] privKey = seq.getEncoded("DER"); 

が、私は同じエラーでこだわっています!

+0

暗号化コードは表示されていますが、暗号化コードはありません。 –

答えて

1

パディングが設定されていないか、間違って設定されています。

は、それが動作しない場合は、他のパディングモードのhereを見ることができますCipher cipher = Cipher.getInstance("RSA");Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

を変更してみてください。