首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >错误: RSA routines:decrypt:DATA_LEN_NOT_EQUAL_TO_MOD_LEN

错误: RSA routines:decrypt:DATA_LEN_NOT_EQUAL_TO_MOD_LEN
EN

Stack Overflow用户
提问于 2018-03-28 06:22:38
回答 1查看 2.1K关注 0票数 2

我需要加密ACCESS_TOKEN。解密时,获取错误:**错误:0407806d:RSA routines:decrypt:DATA_LEN_NOT_EQUAL_TO_MOD_LEN**

私有字符串ACCESS_TOKEN =“承载ACCESS_TOKEN”

请参阅代码:

代码语言:javascript
复制
import android.util.Base64;

import com.itc.classmate.application.MyApplication;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 */

public enum EncryptMoreThn256Byte {
    INSTANCE;
    private SecretKey secKey;
   // private String ACCESS_TOKEN = "bearer nG25Uokr3eF0WAisEcoS4hb1isLwR2qbOGu3UnwARGfeBNlP7RToSf3DCmowl99-TX0nrwL1qElIRZALFNbBXQPL6weVhJk9LRjJAoD9oBlTPtfDNMAZXlLqBqWnYZoxNyfQoPUE_Y0iMBcj_j6RqOfJc4Npid7Wo1AoipXOPYt1JLMfdHN9TZvtn6SxNP9UFipDANkcnHsurDwjPV_X0PdzyqsgXuoIjfAQLd7IonVYGZYmB_SYO68q5CorhH7hA01iIm7TDeUrOAM1p2C9W84rV6nMzMZS-7LPoweMWPxaLHcj15ex3TR16PGNGwbfiRPMLxNjmpqQEi3Mfqax2mk9qHL6LNb-OQK_5y9Zo9w1nC55iQhM-PbF96kgYa5zM2o94yI1IhcWAs-fJEe5tPsT3Dj_QfLWeNVblzDysfNwNajCGnauuPLzG-5qrGgNRtw0Dou8eNhk1lplDXxqu-G9kRyK1KKnPtuyCawzEJ_-4aEHdeA3-QSEqWCphu6w";
  //  private String initialText = "this is working";

    private EncryptMoreThn256Byte() {
        AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "called constructor of EncryptMoreThn256Byte");
        KeyGenerator generator = null;
        try {
            generator = KeyGenerator.getInstance("AES");
            generator.init(128); // The AES key size in number of bits
            secKey = generator.generateKey();
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "EncryptMoreThn256Byte: secKey+++ " + secKey.getEncoded());

//            SecureRandom random = new SecureRandom();
//            byte[] salt = new byte[(256/8)];
//            random.nextBytes(salt);
//            KeySpec keySpec = new PBEKeySpec(initialText.toCharArray(), salt, 1000, 256);
//            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
//            byte[] decrptedSecrateKey = keyFactory.generateSecret(keySpec).getEncoded();
//           // secKey = new SecretKeySpec(decrptedSecrateKey, "AES");
//            secKey = new SecretKeySpec(decrptedSecrateKey, 0, decrptedSecrateKey.length, "AES");
        } catch (Exception e) {
            AppLog.errLog(EncryptMoreThn256Byte.class.getSimpleName(), e.getMessage());
        }
    }


    public String encryptAccessTokenUsingAES(String plainText) {
        AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptAccessTokenUsingAES: plainText " + plainText);

        if (plainText != null || !plainText.isEmpty()) {
            String encrytedSecretKey = SharedPreferences.getInstance(MyApplication.getInstance().getApplicationContext()).getEncrytedSecretKey();
            if (encrytedSecretKey != null) {
                AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptAccessTokenUsingAES: encrytedSecretKey >+++ " + encrytedSecretKey);
                byte[] decrptedSecrateKey = decryptSecretKeyUsingRSA(encrytedSecretKey);
                if (decrptedSecrateKey != null) {
                    secKey = new SecretKeySpec(decrptedSecrateKey, 0, decrptedSecrateKey.length, "AES");
                }
            } else {
                encryptSecretKeyUsingRSA(secKey);
            }

            String str = new String(encryptText(secKey, plainText));
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "final encryptAccessTokenUsingAES is: " + str);
            return str;
        }

        AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptAccessTokenUsingAES: value " + null);
        return null;
    }


    public String decryptAccessTokenUsingAES(String encrptedAssessToken) {
        String encrpted_secretkey = SharedPreferences.getInstance(MyApplication.getInstance().getApplicationContext()).getEncrytedSecretKey();
        AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "decryptAccessTokenUsingAES encrpted_secretkey:: " + encrpted_secretkey);
        AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "decryptAccessTokenUsingAES accesstoken:: " + encrptedAssessToken);
        if (encrpted_secretkey != null) {
            byte[] decrptedSecrateKey = decryptSecretKeyUsingRSA(encrpted_secretkey);
            if (decrptedSecrateKey != null) {
                SecretKey secKey = new SecretKeySpec(decrptedSecrateKey, 0, decrptedSecrateKey.length, "AES");
                AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "decryptAccessTokenUsingAES secKey.getEncoded():: " + secKey.getEncoded());
                String str = decryptText(secKey, encrptedAssessToken);
                AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "final decryptAccessTokenUsingAES is: " + str);
                return str;
            }
        }
        return null;
    }

    private byte[] encryptSecretKeyUsingRSA(SecretKey secKey) {
        AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptSecretKeyUsingRSA SecretKey:: " + secKey);
        KeyPairGenerator kpg = null;
        byte[] encryptedSecrteKey = null;
        try {
            kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            KeyPair keyPair = kpg.generateKeyPair();
            PublicKey puKey = keyPair.getPublic();
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.PUBLIC_KEY, puKey);
            //AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptSecretKeyUsingRSA secKey.getEncoded():: " + secKey.getEncoded());
            //AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptSecretKeyUsingRSA secKey.getEncoded().length:: " + secKey.getEncoded().length);
            //byte[] encryptedSecrteKey = cipher.doFinal(secKey.getEncoded());
            //byte[] encryptedSecrteKey=cipher.doFinal(initialText.getBytes("UTF-8"));
            encryptedSecrteKey = cipher.doFinal(secKey.getEncoded());
            // String str =  Base64.encodeToString(encryptedSecrteKey, Base64.DEFAULT);
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptSecretKeyUsingRSA encryptedSecrteKey[]:: " + encryptedSecrteKey.length);
            //AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptSecretKeyUsingRSA encrytionSecretKey:: " + str);
            //AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptSecretKeyUsingRSA encrytionSecretKey length:: " + str.length());
            SharedPreferences.getInstance(MyApplication.getInstance().getApplicationContext()).setEncrytedSecretKey(encryptedSecrteKey.toString());
        } catch (Exception e) {
            AppLog.errLog(EncryptMoreThn256Byte.class.getSimpleName(), "encryptSecretKeyUsingRSA::+" + e.getMessage());
        } finally {
            return encryptedSecrteKey;
        }
    }


    private byte[] decryptSecretKeyUsingRSA(String encryptSecretKey) {
        KeyPairGenerator kpg = null;
        byte[] bytes = null;
        try {
            kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(2048);
            KeyPair keyPair = kpg.generateKeyPair();
            PrivateKey prKey = keyPair.getPrivate();
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.PRIVATE_KEY, prKey);
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "decryptSecretKeyUsingRSA encryptSecretKey.getBytes():: " + encryptSecretKey.getBytes());
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "decryptSecretKeyUsingRSA encryptSecretKey.getBytes().length:: " + encryptSecretKey.getBytes().length);
           // bytes = cipher.doFinal(Base64.decode(encryptSecretKey, Base64.DEFAULT));
            bytes = cipher.doFinal(encryptSecretKey.getBytes());
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "decryptSecretKeyUsingRSA cipher.doFinal(encryptSecretKey.getBytes():: " + bytes.toString());
        } catch (Exception e) {
            AppLog.errLog(EncryptMoreThn256Byte.class.getSimpleName(), "decryptSecretKeyUsingRSA++++ " + e.getMessage());
        }
        return bytes;
    }


    private byte[] encryptText(SecretKey pSecKey, String plainText) {
        byte[] encryptAccessToken = null;
        try {
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptText::secKey: " + pSecKey.getEncoded());
            Cipher aesCipher = Cipher.getInstance("AES");
            aesCipher.init(Cipher.ENCRYPT_MODE, pSecKey);
            encryptAccessToken = aesCipher.doFinal(plainText.getBytes());
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptText:::: " + encryptAccessToken.toString());
        } catch (Exception e) {
            AppLog.errLog(EncryptMoreThn256Byte.class.getSimpleName(), "encryptTextUsingAES " + e.getMessage());
        }
        return encryptAccessToken;
    }

    /**
     * Convert bytes to AES SecertKey so we can decrypt access token
     *
     * @return
     */
    private String decryptText(SecretKey originalKey, String decryptedAccessToken) {
        byte[] bytePlainText = null;
        try {
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "encryptText::originalKey: " + originalKey.getEncoded());
            //SecretKey originalKey = new SecretKeySpec(decryptedKey, 0, decryptedKey.length, "AES");
            Cipher aesCipher = null;
            aesCipher = Cipher.getInstance("AES");
            aesCipher.init(Cipher.DECRYPT_MODE, originalKey);
            bytePlainText = aesCipher.doFinal(decryptedAccessToken.getBytes());
            AppLog.log(EncryptMoreThn256Byte.class.getSimpleName(), "decryptText bytePlainText:: " + bytePlainText.toString());
        } catch (Exception e) {
            AppLog.errLog(EncryptMoreThn256Byte.class.getSimpleName(), "encryptTextUsingAES " + e.getMessage());
        }
        return new String(bytePlainText);
    }


    private byte[] encrytAT(String plaintext, String password) throws InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[(256 / 8)];
        random.nextBytes(salt);
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 1000, 256);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
        SecretKey key = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iv = new byte[cipher.getBlockSize()];
        random.nextBytes(iv);
        IvParameterSpec ivParams = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
        return cipher.doFinal(plaintext.getBytes("UTF-8"));
    }

}

还可以找到相同代码的日志:

代码语言:javascript
复制
03-28 11:47:59.536 12795-12795/? D/debug_log: EncryptMoreThn256Byte :encryptAccessTokenUsingAES: encrytedSecretKey >+++ [B@b56ec6b 03-2811:48:00.803 12795-12795/? D/debug_log: EncryptMoreThn256Byte :decryptSecretKeyUsingRSA encryptSecretKey.getBytes():: [B@43f8244
03-28 11:48:00.804 12795-12795/? D/debug_log: EncryptMoreThn256Byte :decryptSecretKeyUsingRSA encryptSecretKey.getBytes().length:: 10 03-2811:48:00.804 12795-12795/? E/error_log: Exception from:EncryptMoreThn256Byte : decryptSecretKeyUsingRSA++++error:0407806d:RSA routines:decrypt:DATA_LEN_NOT_EQUAL_TO_MOD_LEN
03-28 11:48:00.805 12795-12795/? D/debug_log: EncryptMoreThn256Byte :encryptText::secKey: [B@d535f2d 
03-28 11:48:00.808 12795-12795/? D/debug_log: EncryptMoreThn256Byte : encryptText:::: [B@d4d6c62 03-2811:48:00.808 12795-12795/? D/debug_log: EncryptMoreThn256Byte : finalencryptAccessTokenUsingAES is: (���(z��RW�D 
03-28 11:48:00.808 12795-12795/? D/debug_log: MyApplication : EncryptMoreThn256Byte +++str (���(z��RW�D 
03-28 11:48:00.808 12795-12795/? D/debug_log:EncryptMoreThn256Byte : decryptAccessTokenUsingAESencrpted_secretkey:: [B@b56ec6b 
03-28 11:48:00.808 12795-12795/? D/debug_log: EncryptMoreThn256Byte : decryptAccessTokenUsingAESaccesstoken:: (���(z��RW�D 
03-28 11:48:03.539 12795-12795/? D/debug_log: EncryptMoreThn256Byte : decryptSecretKeyUsingRSAencryptSecretKey.getBytes():: [B@6c931f3 
03-28 11:48:03.540 12795-12795/? D/debug_log: EncryptMoreThn256Byte :decryptSecretKeyUsingRSA encryptSecretKey.getBytes().length:: 10 03-2811:48:03.540 12795-12795/? E/error_log: Exception from:EncryptMoreThn256Byte : decryptSecretKeyUsingRSA++++error:0407806d:RSA routines:decrypt:DATA_LEN_NOT_EQUAL_TO_MOD_LEN
03-28 11:48:03.540 12795-12795/? D/debug_log: MyApplication :EncryptMoreThn256Byte +++ dep null
EN

回答 1

Stack Overflow用户

发布于 2018-03-29 02:46:04

请复习一下这个。

代码语言:javascript
复制
public class AESEncryptor {
    private static final String CIPHER_TYPE = "RSA/ECB/PKCS1Padding";//AES/GCM/NoPadding
    public final String ANDROID_KEY_STORE = "AndroidKeyStore";
    private static AESEncryptor instance;
    private String alias_ = "classmate123";
    private KeyStore keyStore;

    private AESEncryptor() {
    }

    public static AESEncryptor getInstance() {
        if (instance == null) {
            instance = new AESEncryptor();
        }
        return instance;
    }

    public KeyStore initAndroidKeyStore(Context pContext) {
        try {
            if (keyStore == null) {
                keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
                keyStore.load(null);
                createNewKeys(pContext);
            }
        } catch (Exception e) {
            AppLog.errLog("AESEncrytion", "initAndroidKeyStore : " + e.getMessage());
        }
        return keyStore;
    }

    public String encrypt(String key, String cleartext) throws Exception {
        //AppLog.log("AESEncrytion", "encrypt+++ " + cleartext);
        if (cleartext == null || cleartext.trim().length()==0||cleartext.isEmpty()) {
            return "";
        }
        return encryptString(alias_, cleartext);
    }


    public String decrypt(String key, String encryptedValue) throws Exception {
        //AppLog.log("AESEncrytion", "encryptedValue+++ " + encryptedValue);
        if (encryptedValue == null || encryptedValue.trim().length()==0||encryptedValue.isEmpty()) {
            return "";
        }
        return decryptString(alias_, encryptedValue);
    }


    public void createNewKeys(Context pContext) {
        String alias = alias_;
        try {
            // Create new key if needed
            if (!keyStore.containsAlias(alias)) {
                Calendar start = Calendar.getInstance();
                Calendar end = Calendar.getInstance();
                end.add(Calendar.YEAR, 1);
                AlgorithmParameterSpec spec = null;
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    spec = new KeyPairGeneratorSpec.Builder(pContext)
                            // You'll use the alias later to retrieve the key.  It's a key for the key!
                            .setAlias(alias)
                            // The subject used for the self-signed certificate of the generated pair
                            .setSubject(new X500Principal("CN=" + alias))
                            .setSerialNumber(BigInteger.ONE)
                            .setStartDate(start.getTime())
                            .setEndDate(end.getTime())
                            .build();
                }else {
                    // On Android M or above, use the KeyGenparameterSpec.Builder and specify permitted
                    // properties  and restrictions of the key.
                    spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
                            .setCertificateSubject(new X500Principal("CN=" + alias))
                            .setDigests(KeyProperties.DIGEST_SHA256)
                            .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
                            .setCertificateSerialNumber(BigInteger.ONE)
                            .setCertificateNotBefore(start.getTime())
                            .setCertificateNotAfter(end.getTime())
                            .build();
                }
                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", ANDROID_KEY_STORE);
                generator.initialize(spec);
                KeyPair keyPair = generator.generateKeyPair();
               // AppLog.log("AESEncrytion", "createNewKeys keyPair.getPrivate(): " + keyPair.getPrivate());
               // AppLog.log("AESEncrytion", "createNewKeys keyPair.getPublic(): " + keyPair.getPublic());
            } else {
                AppLog.log("AESEncrytion", "KeyStore already containsAlias alias: " + keyStore.containsAlias(alias));
            }
        } catch (Exception e) {
            AppLog.errLog("AESEncrytion", "createNewKeys: " + e.getMessage());
        }
        //refreshKeys();
    }


    public String encryptString(String alias, String initialText) {
        try {
            //AppLog.log("AESEncrytion", "initialText+++ " + initialText);
            KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
            PublicKey publicKey = privateKeyEntry.getCertificate().getPublicKey();
            //AppLog.log("AESEncrytion", "encryptString keyPair.getPublic(): " + publicKey.getEncoded());
            // RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();

            Cipher input = Cipher.getInstance(CIPHER_TYPE);
            input.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encrypted=input.doFinal(initialText.getBytes("UTF-8"));

//            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//            CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, input);
//            cipherOutputStream.write(initialText.getBytes("UTF-8"));
//            cipherOutputStream.close();
//            byte[] vals = outputStream.toByteArray();
//            AppLog.log("AESEncrytion", "decryptString+++ " + Base64.encodeToString(vals, Base64.DEFAULT));

            return Base64.encodeToString(encrypted, Base64.DEFAULT);
        } catch (Exception e) {
            AppLog.errLog("AESEncrytion", "encryptString " + e.getMessage() + " occured");
        }
        return "";
    }


    public String decryptString(String alias, String cipherText) {
        try {
            //AppLog.log("AESEncrytion", "cipherText : " + cipherText);
            KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
            // RSAPrivateKey privateKey = (RSAPrivateKey) privateKeyEntry.getPrivateKey();
            PrivateKey privateKey = privateKeyEntry.getPrivateKey();
            //AppLog.log("AESEncrytion", "decryptString keyPair.getPrivate(): " + privateKey.getEncoded());

            Cipher output = Cipher.getInstance(CIPHER_TYPE);
            output.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decrypted=output.doFinal(Base64.decode(cipherText, Base64.DEFAULT));

//            CipherInputStream cipherInputStream = new CipherInputStream(
//                    new ByteArrayInputStream(Base64.decode(cipherText, Base64.DEFAULT)), output);
//            ArrayList<Byte> values = new ArrayList<>();
//            int nextByte;
//            while ((nextByte = cipherInputStream.read()) != -1) {
//                values.add((byte) nextByte);
//            }
//            byte[] bytes = new byte[values.size()];
//            for (int i = 0; i < bytes.length; i++) {
//                bytes[i] = values.get(i).byteValue();
//            }
            String finalText = new String(decrypted, 0, decrypted.length, "UTF-8");
           // AppLog.log("AESEncrytion", "decryptString : " + finalText);
            return finalText;
        } catch (Exception e) {
            AppLog.errLog("AESEncrytion", "decryptString:: " + e.getMessage() + " occured");
        }
        return "";
    }

    public boolean isKeysAvail() throws KeyStoreException {
        return keyStore.containsAlias(alias_);
    }

    public void deleteKey() throws KeyStoreException {
        keyStore.deleteEntry(alias_);
    }


}

它解决了我的问题。我已经改变了我的加密和解密方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49527460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档