2017-04-21 1 views
2

Je travaille sur un projet dans lequel je dois chiffrer un mot de passe à l'aide de la clé publique RSA. J'ai essayé plusieurs échantillons et des solutions de SO comme comme suitChaîne de chiffrement Android à l'aide de la clé publique RSA

  1. Android RSA encryption from public string

  2. RSA using SpongyCastle

Mais aucune des solutions travaillé dans mon cas malheureusement. Je recevais des exceptions suivantes à plusieurs reprises si je tente avec un travail autour

Error Log:

04-21 07:50:57.876 18842-18842/com.takeoffandroid.passwordencryption W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable 
04-21 07:50:57.986 18842-18842/com.takeoffandroid.passwordencryption W/System.err: java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG 
04-21 07:50:57.986 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at com.android.org.conscrypt.OpenSSLKey.getPublicKey(OpenSSLKey.java:250) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at com.android.org.conscrypt.OpenSSLRSAKeyFactory.engineGeneratePublic(OpenSSLRSAKeyFactory.java:47) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at java.security.KeyFactory.generatePublic(KeyFactory.java:172) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at com.takeoffandroid.passwordencryption.MainActivity.RSAEncrypt(MainActivity.java:181) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at com.takeoffandroid.passwordencryption.MainActivity.onCreate(MainActivity.java:80) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.app.Activity.performCreate(Activity.java:6532) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2383) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.app.ActivityThread.access$900(ActivityThread.java:157) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.os.Handler.dispatchMessage(Handler.java:102) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.os.Looper.loop(Looper.java:148) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at android.app.ActivityThread.main(ActivityThread.java:5437) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at java.lang.reflect.Method.invoke(Native Method) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err: Caused by: java.lang.RuntimeException: error:0c0890ba:ASN.1 encoding routines:asn1_check_tlen:WRONG_TAG 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at com.android.org.conscrypt.NativeCrypto.d2i_PUBKEY(Native Method) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err:  at com.android.org.conscrypt.OpenSSLKey.getPublicKey(OpenSSLKey.java:248) 
04-21 07:50:57.987 18842-18842/com.takeoffandroid.passwordencryption W/System.err: ... 16 more 

Mon exigence:

J'ai une clé publique avec moi et je voulais chiffrer le texte entré dans l'edittext avec cette clé publique. Par exemple: Le mot de passe @ 123 doit être chiffré à l'aide de la clé publique.

clé publique:

public static String PUBLIC_KEY = "-----BEGIN RSA PUBLIC KEY-----\n" + 
      "MMDDFDFK43545mmdf499Mdfdasl43ND/GGKLGKL4434safddEcBFfbTZUM517\n" + 
      "VDSVFS45fwdGJGGLKGGL332XSA3=d/S/2ETegJPFQ4sjiY7/DsS2o9Gr\n" + 
      "asBASF3465243FCDXSDCDxsSFC39NkDiNO2QKNXivAQVpuJeuoDeK\n" + 
      "wNGmwDkIsvxBn8u55QpOwvdaRBeLqllJ6xoF6OuwnD0IB4tVDL2MbMVj1U9GtEGL\n" + 
      "DJKHSJAH434jjhdds54KkhjbvGJGGGG/Vn4OYNooIWE9uuiyxm2M\n" + 
      "AFSDAFXZB546FGHxcvv324FDGJIYTaa346/9xQIDAQAB\n" + 
      "-----END RSA PUBLIC KEY-----"; 

code Implémentations J'ai essayé:

Exemple I:

public static String encryptDataRSA(final String data) throws IOException { 
     final byte[] dataToEncrypt = data.getBytes(); 
     byte[] encryptedData = null; 

     try { 

      PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(RSAUtils.PUBLIC_KEY.getBytes())); 

      final Cipher cipher = Cipher.getInstance("RSA"); 
      cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
      encryptedData = cipher.doFinal(dataToEncrypt); 

      try { 
       final String encryptedText = new String(Base64.encode(encryptedData, Base64.DEFAULT), "UTF-8"); 
       return encryptedText.toString(); 
      } 
      catch (final UnsupportedEncodingException e1) { return null; } 
     } catch (Exception e) { e.printStackTrace(); } 

     return "ERROR"; 
    } 

Exemple II:

public byte[] RSAEncrypt(final String plain) throws NoSuchAlgorithmException, NoSuchPaddingException, 
      InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException { 
     KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); 
     kpg.initialize(1024); 
     KeyPair kp = kpg.genKeyPair(); 
     PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(RSAUtils.PUBLIC_KEY.getBytes())); 

     Cipher cipher = Cipher.getInstance("RSA"); 
     cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
     byte[] encryptedBytes = cipher.doFinal(plain.getBytes()); 
     System.out.println("EEncrypted?????" + org.apache.commons.codec.binary.Hex.encodeHexString(encryptedBytes)); 
     return encryptedBytes; 
    } 

Exemple III:

public static String encryptRSAToString(String text, String strPublicKey) { 
     byte[] cipherText = null; 
     String strEncryInfoData=""; 
     try { 

      KeyFactory keyFac = KeyFactory.getInstance("RSA"); 
      KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(strPublicKey.trim().getBytes(), Base64.DEFAULT)); 
      Key publicKey = keyFac.generatePublic(keySpec); 

      // get an RSA cipher object and print the provider 
      final Cipher cipher = Cipher.getInstance("RSA"); 
      // encrypt the plain text using the public key 
      cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
      cipherText = cipher.doFinal(text.getBytes()); 
      strEncryInfoData = new String(Base64.encode(cipherText,Base64.DEFAULT)); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return strEncryInfoData.replaceAll("(\\r|\\n)", ""); 
    } 

Toute aide ou suggestion serait vraiment utile pour moi. Merci d'avance.

+1

Votre clé publique est clairement corrompu. Vous avez un signe égal ('=') au milieu de la chaîne base64 qui n'est pas valide. Même si j'enlève que la clé est toujours invalide. –

+0

En fait, j'ai posté un exemple de clé publique. La clé que j'utilise est complètement différente. – Chandru

+0

@JamesKPolk S'il vous plaît trouver la clé réelle ici https://pastebin.com/7beLfTpK – Chandru

Répondre

3

essayez ceci.

public static String PUBLIC_KEY = "YOUR PUBLIC KEY"; 

static String enccriptData(String txt) 
{ 
    String encoded = ""; 
    byte[] encrypted = null; 
    try { 
     byte[] publicBytes = Base64.decode(PUBLIC_KEY, Base64.DEFAULT); 
     X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); 
     KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
     PublicKey pubKey = keyFactory.generatePublic(keySpec); 
     Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); //or try with "RSA" 
     cipher.init(Cipher.ENCRYPT_MODE, pubKey); 
     encrypted = cipher.doFinal(txt.getBytes()); 
     encoded = Base64.encodeToString(encrypted, Base64.DEFAULT); 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return encoded; 
} 

EDIT:

Vous pouvez utiliser mon code, mais lire le commentaire de James K Polk, il a raison

+0

Merci d'avoir répondu. Encore une fois j'ai eu l'exception suivante – Chandru

+0

https://pastebin.com/ukNUsL06 – Chandru

+0

Vous mettez la clé comme dans l'exemple? X509EncodedKeySpec attend des données codées DER non PEM Le code fonctionne correctement pour moi. . – Israel