49

Android で RSA 暗号化と復号化のデモを実装しています。暗号化は非常にうまく実行できますが、復号化では例外が発生します: >>java.security.InvalidKeyException: unknown key type passed to RSA.

    KeyPairGenerator kpg;
    KeyPair kp;
    PublicKey publicKey;
    PrivateKey privateKey;
    byte [] encryptedBytes,decryptedBytes;
    Cipher cipher,cipher1;
    String encrypted,decrypted;

    public String RSAEncrypt (final String plain) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException 
    {
        kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        kp = kpg.genKeyPair();
        publicKey = kp.getPublic();
        privateKey = kp.getPrivate();

        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        encryptedBytes = cipher.doFinal(plain.getBytes());
        encrypted = new String(encryptedBytes);
        System.out.println("EEncrypted?????"+encrypted);
        return encrypted;

    }

    public String RSADecrypt (final String result) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException 
    {

        cipher1=Cipher.getInstance("RSA");
        cipher1.init(Cipher.DECRYPT_MODE, privateKey);
        decryptedBytes = cipher1.doFinal(result.getBytes());
        decrypted = new String(decryptedBytes);
        System.out.println("DDecrypted?????"+decrypted);
        return decrypted;

    }

そして、私はここから関数を呼び出しています:

encrypt.setOnClickListener(new OnClickListener()
        { 
            public void onClick(View arg0) 
            {
                    try
                    {
                        RSAEncrypt rsaencrypt=new RSAEncrypt();
                        rsaencrypt.RSAEncrypt(name);

                        result=rsaencrypt.RSAEncrypt(name);
                        Toast.makeText(getBaseContext(), result.toString(),Toast.LENGTH_SHORT).show();

                        System.out.println("Result:"+result);
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                        Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
                    }
            }
        });

        decrypt.setOnClickListener(new OnClickListener()
        { 
            public void onClick(View arg0) 
            {
                {
                    try
                    {
                        RSAEncrypt rsadecrypt=new RSAEncrypt();

                        rsadecrypt.RSADecrypt(result);

                        ans=rsadecrypt.RSADecrypt(result);
                        System.out.println("Result is"+ans);
                        Toast.makeText(getBaseContext(), ans.toString(),Toast.LENGTH_LONG).show();
                    }
                    catch(Exception e)
                    {
                        e.printStackTrace();
                        Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
                        System.out.println("Exception is>>"+e);
                    }
            }
        });
4

5 に答える 5

50

RSA では、暗号化に公開鍵を使用し、復号化に秘密鍵を使用する必要があります。

サンプル コードでは、暗号化と復号化に公開キーを使用しています。これは機能しません。

したがって、復号化部分では、暗号を次のように初期化する必要があります。

cipher1.init(Cipher.DECRYPT_MODE, privateKey);

さらに、コードには 2 番目の重大なバグがあります。

バイナリ コンテンツを含むバイト配列を文字列に変換しています。

バイナリ データを文字列に変換しないでください。

文字列は、バイナリ データではなく、文字列文字用です。バイナリ データを文字列にパックする場合は、たとえば Hex や Base64 を使用して印刷可能な文字にエンコードします。

次の例では、 org.apache.common.codecパッケージの 16 進エンコーダーを使用しています。サードパーティ ライブラリをインストールする必要があります。

public byte[] RSAEncrypt(final String plain) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    kp = kpg.genKeyPair();
    publicKey = kp.getPublic();
    privateKey = kp.getPrivate();

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

public String RSADecrypt(final byte[] encryptedBytes) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    cipher1 = Cipher.getInstance("RSA");
    cipher1.init(Cipher.DECRYPT_MODE, privateKey);
    decryptedBytes = cipher1.doFinal(encryptedBytes);
    decrypted = new String(decryptedBytes);
    System.out.println("DDecrypted?????" + decrypted);
    return decrypted;
}
于 2012-09-18T09:32:06.777 に答える
11

Android の例を次に示します。

  • 秘密/公開 RSA キー ペアの生成
  • 文字列の暗号化
  • 暗号化された文字列の復号化

これらのメソッドは、すべての base 64 エンコード/デコードを処理します。

    public void TestEncryptData(String dataToEncrypt) {
        // generate a new public/private key pair to test with (note. you should only do this once and keep them!)
        KeyPair kp = getKeyPair();

        PublicKey publicKey = kp.getPublic();
        byte[] publicKeyBytes = publicKey.getEncoded();
        String publicKeyBytesBase64 = new String(Base64.encode(publicKeyBytes, Base64.DEFAULT));

        PrivateKey privateKey = kp.getPrivate();
        byte[] privateKeyBytes = privateKey.getEncoded();
        String privateKeyBytesBase64 = new String(Base64.encode(privateKeyBytes, Base64.DEFAULT));

        // test encryption
        String encrypted = encryptRSAToString(dataToEncrypt, publicKeyBytesBase64);

        // test decryption
        String decrypted = decryptRSAToString(encrypted, privateKeyBytesBase64);
    }

    public static KeyPair getKeyPair() {
        KeyPair kp = null;
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            kp = kpg.generateKeyPair();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return kp;
    }

    public static String encryptRSAToString(String clearText, String publicKey) {
        String encryptedBase64 = "";
        try {
            KeyFactory keyFac = KeyFactory.getInstance("RSA");
            KeySpec keySpec = new X509EncodedKeySpec(Base64.decode(publicKey.trim().getBytes(), Base64.DEFAULT));
            Key key = keyFac.generatePublic(keySpec);

            // get an RSA cipher object and print the provider
            final Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
            // encrypt the plain text using the public key
            cipher.init(Cipher.ENCRYPT_MODE, key);

            byte[] encryptedBytes = cipher.doFinal(clearText.getBytes("UTF-8"));
            encryptedBase64 = new String(Base64.encode(encryptedBytes, Base64.DEFAULT));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return encryptedBase64.replaceAll("(\\r|\\n)", "");
    }

    public static String decryptRSAToString(String encryptedBase64, String privateKey) {

        String decryptedString = "";
        try {
            KeyFactory keyFac = KeyFactory.getInstance("RSA");
            KeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey.trim().getBytes(), Base64.DEFAULT));
            Key key = keyFac.generatePrivate(keySpec);

            // get an RSA cipher object and print the provider
            final Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
            // encrypt the plain text using the public key
            cipher.init(Cipher.DECRYPT_MODE, key);

            byte[] encryptedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            decryptedString = new String(decryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return decryptedString;
    }
于 2016-12-05T15:47:26.080 に答える
1

問題は、暗号の暗号化と復号化に同じ鍵ペアを使用する必要があることだと思います。JavaDoc を参照します。

 genKeyPair() This will generate a new key pair every time it is called.
于 2012-09-18T08:33:27.000 に答える